答:
Here is how I solved it</p>

```<code>import js2py

#split
splitt = (json.loads(m)["k"]).split('window.initialRoomDossier = "')
splitt = splitt[1].split('";')

final = str(splitt[0])
final = 'var kek = "'+final+'";'#Turning it into javascript code (Later we will run it)

#Javascript Virtual Machine
context = js2py.EvalJs({'python_sum': sum})

#Slides the sexy code
context.execute(final)#Running the javascript code
#print (context.kek)#

m3u8_url = json.loads(context.kek)["hls_source"]
</code>```

Title: How to decode javascript-unicode string in python?

Body:
I have this string:

{\u0022allow_group_shows\u0022: true, \u0022needs_supporter_to_pm\u0022: true, \u0022ads_zone_ids\u0022: {\u0022300x250,centre\u0022: \u0022\u0022, \u0022300x250,right\u0022: \u0022\u0022, \u0022300x250,left\u0022: \u0022\u0022, \u0022468x60\u0022: \u0022\u0022, \u0022160x600,top\u0022: \u0022\u0022, \u0022160x600,bottom\u0022: \u0022\u0022, \u0022160x600,middle\u0022: \u0022\u0022}, \u0022chat_settings\u0022: {\u0022sort_users_key\u0022: \u0022a\u0022, \u0022silence_broadcasters\u0022: \u0022false\u0022, \u0022highest_token_color\u0022: \u0022darkpurple\u0022, \u0022emoticon_autocomplete_delay\u0022: \u00220\u0022, \u0022ignored_users\u0022: \u0022\u0022, \u0022show_emoticons\u0022: true, \u0022font_size\u0022: \u00229pt\u0022, \u0022b_tip_vol\u0022: \u002210\u0022, \u0022allowed_chat\u0022: \u0022all\u0022, \u0022room_leave_for\u0022: \u0022org\u0022, \u0022font_color\u0022: \u0022#494949\u0022, \u0022font_family\u0022: \u0022default\u0022, \u0022room_entry_for\u0022: \u0022org\u0022, \u0022v_tip_vol\u0022: \u002280\u0022}, \u0022is_age_verified\u0022: true, \u0022flash_host\u0022: \u0022edge143.stream.highwebmedia.com\u0022, \u0022tips_in_past_24_hours\u0022: 0, \u0022dismissible_messages\u0022: [], \u0022show_mobile_site_banner_link\u0022: false, \u0022last_vote_in_past_90_days_down\u0022: false, \u0022server_name\u0022: \u0022113\u0022, \u0022num_users_required_for_group\u0022: 2, \u0022group_show_price\u0022: 18, \u0022is_mobile\u0022: false, \u0022chat_username\u0022: \u0022__anonymous__eiwBXR\u0022, \u0022recommender_hmac\u0022: \u0022dae28e4e9afa15da7c6227af2e8fb8abd85a3714aca8f86f01a53a6dd1377115\u0022, \u0022broadcaster_gender\u0022: \u0022couple\u0022, \u0022hls_source\u0022: \u0022https://localhost/live\u002Dhls/amlst:jimmy_and_amy\u002Dsd\u002De73f4b67186a2ec4c13137607d02470ac61f32b60ac15e691bf33493423ef477_trns_h264/playlist.m3u8\u0022, \u0022allow_show_recordings\u0022: true, \u0022is_moderator\u0022: false, \u0022room_status\u0022: \u0022public\u0022, \u0022edge_auth\u0022: \u0022{\u005C\u0022username\u005C\u0022:\u005C\u0022__anonymous__eiwBXR\u005C\u0022,\u005C\u0022org\u005C\u0022:\u005C\u0022A\u005C\u0022,\u005C\u0022expire\u005C\u0022:1590669977,\u005C\u0022sig\u005C\u0022:\u005C\u0022454d96141c66fb42f74e9620b9d79e937de3a774a5687021f8650cc4f563d371\u005C\u0022,\u005C\u0022room\u005C\u0022:\u005C\u0022jimmy_and_amy\u005C\u0022}\u0022, \u0022is_supporter\u0022: false, \u0022chat_password\u0022: \u0022{\u005C\u0022username\u005C\u0022:\u005C\u0022__anonymous__eiwBXR\u005C\u0022,\u005C\u0022org\u005C\u0022:\u005C\u0022A\u005C\u0022,\u005C\u0022expire\u005C\u0022:1590669977,\u005C\u0022sig\u005C\u0022:\u005C\u0022454d96141c66fb42f74e9620b9d79e937de3a774a5687021f8650cc4f563d371\u005C\u0022,\u005C\u0022room\u005C\u0022:\u005C\u0022jimmy_and_amy\u005C\u0022}\u0022, \u0022room_pass\u0022: \u0022b5b2408cd91e6c595a3f732a5b7b1567b566bcc92f384ce5e6a00a26a24fb5c7\u0022, \u0022low_satisfaction_score\u0022: false, \u0022tfa_enabled\u0022: false, \u0022room_title\u0022: \u0022(STEP SIS CUM FACE) shh... Luna is here and dont know what we are doing #hairy #creampie #stockings #new #lush [3536 tokens remaining]\u0022, \u0022satisfaction_score\u0022: {\u0022down_votes\u0022: 15, \u0022up_votes\u0022: 67, \u0022percent\u0022: 82, \u0022max\u0022: 31222657}, \u0022viewer_username\u0022: \u0022AnonymousUser\u0022, \u0022hidden_message\u0022: \u0022\u0022, \u0022following\u0022: false, \u0022wschat_host\u0022: \u0022https://chatws\u002D45.stream.highwebmedia.com/ws\u0022, \u0022has_studio\u0022: false, \u0022num_followed\u0022: 0, \u0022spy_private_show_price\u0022: 30, \u0022hide_satisfaction_score\u0022: false, \u0022broadcaster_username\u0022: \u0022jimmy_and_amy\u0022, \u0022ignored_emoticons\u0022: [], \u0022apps_running\u0022: \u0022[[\u005C\u0022Tip Goal\u005C\u0022,\u005C\u0022\u005C\u005C/apps\u005C\u005C/app_details\u005C\u005C/tip\u002Dgoal\u005C\u005C/?slot\u003D0\u005C\u0022],[\u005C\u0022Ultra Bot \u002D 4Sci\u005C\u0022,\u005C\u0022\u005C\u005C/apps\u005C\u005C/app_details\u005C\u005C/ultra\u002Dbot\u002D4sci\u005C\u005C/?slot\u003D2\u005C\u0022],[\u005C\u0022Roll The Dice\u005C\u0022,\u005C\u0022\u005C\u005C/apps\u005C\u005C/app_details\u005C\u005C/roll\u002Dthe\u002Ddice\u002D5\u005C\u005C/?slot\u003D3\u005C\u0022]]\u0022, \u0022token_balance\u0022: 0, \u0022private_min_minutes\u0022: 10, \u0022viewer_gender\u0022: \u0022m\u0022, \u0022allow_anonymous_tipping\u0022: false, \u0022num_users_waiting_for_group\u0022: 0, \u0022last_vote_in_past_24_hours\u0022: null, \u0022is_widescreen\u0022: true, \u0022num_viewers\u0022: 1672, \u0022broadcaster_on_new_chat\u0022: false, \u0022private_show_price\u0022: 30, \u0022num_followed_online\u0022: 0, \u0022allow_private_shows\u0022: true}

and I want to decode it in python to view to make it easier for me to send it over the internet into our android app... anyways that why I am here it should look like

"{"allow_group_shows": true, "needs_supporter_to_pm": true, "ads_zone_ids": {"300x250,centre": "", "300x250,right": "", "300x250,left": "", "468x60": "", "160x600,top": "", "160x600,bottom": "", "160x600,middle": ""}, "chat_settings": {"sort_users_key": "a", "silence_broadcasters": "false", "highest_token_color": "darkpurple", "emoticon_autocomplete_delay": "0", "ignored_users": "", "show_emoticons": true, "font_size": "9pt", "b_tip_vol": "10", "allowed_chat": "all", "room_leave_for": "org", "font_color": "#494949", "font_family": "default", "room_entry_for": "org", "v_tip_vol": "80"}, "is_age_verified": true, "flash_host": "edge306.stream.highwebmedia.com", "tips_in_past_24_hours": 0, "dismissible_messages": [], "show_mobile_site_banner_link": false, "last_vote_in_past_90_days_down": false, "server_name": "115", "num_users_required_for_group": 2, "group_show_price": 18, "is_mobile": false, "chat_username": "bom4b5", "recommender_hmac": "ed05e292bb82262255a96944d81bb04dc2d248ca69fff35cf5d7015889c005b1", "broadcaster_gender": "couple", "hls_source": "https://***/live-edge/****-sd-e73f4b67186a2ec4c13137607d02470ac61f32b60***%22%7D", "allow_show_recordings": true, "is_moderator": false, "room_status": "public", "edge_auth": "{\"username\":\"bom4b5\",\"org\":\"A\",\"expire\":1590666696,\"sig\":\"49b6844fde2c47c2430bd05946b6cfbc9c7864788b9236d7f5af5ff88efd3f95\",\"room\":\"jimmy_and_amy\"}", "is_supporter": false, "chat_password": "****", "room_pass": "b5b2408cd91e6c595a3f732a5b7b1567b566bcc92f384ce5e6a00a26a24fb5c7", "low_satisfaction_score": false, "tfa_enabled": false, "room_title": "(STEP SIS CUM FACE) shh... Luna is here and dont know what we are doing #hairy #creampie #stockings #new #lush [4310 tokens remaining]", "satisfaction_score": {"down_votes": 15, "up_votes": 67, "percent": 82, "max": 31222657}, "viewer_username": "bom4b5", "hidden_message": "", "following": false, "wschat_host": "https://chatws-45.stream.highwebmedia.com/ws", "has_studio": false, "num_followed": 0, "spy_private_show_price": 30, "hide_satisfaction_score": false, "broadcaster_username": "jimmy_and_amy", "ignored_emoticons": [], "apps_running": "[[\"Tip Goal\",\"\\/apps\\/app_details\\/tip-goal\\/?slot=0\"],[\"Ultra Bot - 4Sci\",\"\\/apps\\/app_details\\/ultra-bot-4sci\\/?slot=2\"],[\"Roll The Dice\",\"\\/apps\\/app_details\\/roll-the-dice-5\\/?slot=3\"]]", "token_balance": 0, "private_min_minutes": 10, "viewer_gender": "f", "allow_anonymous_tipping": false, "num_users_waiting_for_group": 0, "last_vote_in_past_24_hours": null, "is_widescreen": true, "num_viewers": 331, "broadcaster_on_new_chat": false, "private_show_price": 30, "num_followed_online": 0, "allow_private_shows": true}"

I tried How to decode javascript unicode string in python?
it worked but the only one issue is that I cant decode it after I split

gett = s.get("https://localhost.com/34534535/")
# print(gett.text + "\n\n\n\n")

m = json.dumps({"k": gett.text})  # decodes it

# split
testt = (json.loads(m)["k"]).split('window.initialRoomDossier = "')
testt = testt[1].split('";')

final = testt[0]  # show the same

the thing is that if I load it from a string like

a = "{\u0022allow_group_shows\u0022: true, \u0022nee..."

it does work but not after I split

Body:
Here is how I solved it

import js2py

#split
splitt = (json.loads(m)["k"]).split('window.initialRoomDossier = "')
splitt = splitt[1].split('";')

final = str(splitt[0])
final = 'var kek = "'+final+'";'#Turning it into javascript code (Later we will run it)

#Javascript Virtual Machine
context = js2py.EvalJs({'python_sum': sum})

#Slides the sexy code
context.execute(final)#Running the javascript code
#print (context.kek)#

m3u8_url = json.loads(context.kek)["hls_source"]


来源: stackexchange

问:
How to grant admin admin role?
I got this error:

```<code>SEC-NOADMIN: (err:FOER0000) User does not have admin role.
in /MarkLogic/security.xqy, at 6875:7, in sec:check-admin() [1.0-ml]
in /MarkLogic/Admin/lib/status-check.xqy, at 27:2, in adlib:status-check() [1.0-ml]
in /, at 6:0 [1.0-ml]
</code>```

How can I grant admin role back to admin user?

答: Michael:  I manage to restore the database. As such I create backup super user to mitigate risks. I appreciate your prompt attention! </p>

ContentLicense: CC BY-SA 4.0

Title: How to grant admin admin role?

Body:
I got this error:

SEC-NOADMIN: (err:FOER0000) User does not have admin role.
in /MarkLogic/security.xqy, at 6875:7, in sec:check-admin() [1.0-ml]
in /MarkLogic/Admin/lib/status-check.xqy, at 27:2, in adlib:status-check() [1.0-ml]
in /, at 6:0 [1.0-ml]

How can I grant admin role back to admin user?


问:
Rebasing remote branches in Git
I am using an intermediate Git repository to mirror a remote SVN repository, from which people can clone and work on. The intermediate repository has its master branch rebased nightly from the upstream SVN, and we are working on feature branches. For example:

```<code>remote:
  master

local:
  master
  feature
</code>```

I can successfully push my feature branch back to the remote, and end up with what I expect:

```<code>remote:
  master
  feature

local:
  master
  feature
</code>```

I then re-setup the branch to track the remote:

```<code>remote:
  master
  feature

local:
  master
  feature -> origin/feature
</code>```

And all is well. What I would like to do from here is to rebase the feature branch to the master branch on the remote, but I would like to do this from my local machine. I'd like to be able to do:

```<code>git checkout master
git pull
git checkout feature
git rebase master
git push origin feature
</code>```

To keep the remote feature branch up-to-date with the remote master. However, this method causes Git to complain:

```<code>To <remote>
 ! [rejected]        feature -> feature (non-fast-forward)
error: failed to push some refs to '<remote>'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.
</code>```

git pull does the trick but causes a merge commit that I'd like to avoid. I'm concerned that the message states feature -> feature rather than feature -> origin/feature but this may just be a presentation thing.

Am I missing something, or going about this in completely the wrong way? It's not critical to avoid doing the rebase on the remote server, but it makes fixing any merge conflicts from the rebase much harder.

答:
This is an important thing/concept in git that a lof of git users would benefit from knowing. git rebase is a very powerful tool and enables you to squash commits together, remove commits etc. But as with any powerful tool, you basically need to know what you're doing or something might go really wrong.

When you are working locally and messing around with your local branches, you can do whatever you like as long as you haven't pushed the changes to the central repository. This means you can rewrite your own history, but not others history. By only messing around with your local stuff, nothing will have any impact on other repositories.

This is why it's important to remember that once you have pushed commits, you should not rebase them later on. The reason why this is important, is that other people might pull in your commits and base their work on your contributions to the code base, and if you later on decide to move that content from one place to another (rebase it) and push those changes, then other people will get problems and have to rebase their code. Now imagine you have 1000 developers :) It just causes a lot of unnecessary rework.

Title: Rebasing remote branches in Git

Body:
I am using an intermediate Git repository to mirror a remote SVN repository, from which people can clone and work on. The intermediate repository has its master branch rebased nightly from the upstream SVN, and we are working on feature branches. For example:

remote:
  master

local:
  master
  feature

I can successfully push my feature branch back to the remote, and end up with what I expect:

remote:
  master
  feature

local:
  master
  feature

I then re-setup the branch to track the remote:

remote:
  master
  feature

local:
  master
  feature -> origin/feature

And all is well. What I would like to do from here is to rebase the feature branch to the master branch on the remote, but I would like to do this from my local machine. I'd like to be able to do:

git checkout master
git pull
git checkout feature
git rebase master
git push origin feature

To keep the remote feature branch up-to-date with the remote master. However, this method causes Git to complain:

To <remote>
 ! [rejected]        feature -> feature (non-fast-forward)
error: failed to push some refs to '<remote>'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

git pull does the trick but causes a merge commit that I'd like to avoid. I'm concerned that the message states feature -> feature rather than feature -> origin/feature but this may just be a presentation thing.

Am I missing something, or going about this in completely the wrong way? It's not critical to avoid doing the rebase on the remote server, but it makes fixing any merge conflicts from the rebase much harder.


问:
Adding headers with AWS SES
I've written a small node AWS Lambda function that uses AWS SES to send emails.

I'm trying to include a tracking pixel, and I'd like to add a no-cache email header:

```<code>HTTP 200 OK
Content-Type: image/png
Cache-Control: no-cache, max-age=0
</code>```

Is there a way to do this with the regular ses.sendEmail() function? Or do I need to use the sendRawEmail() function (which seems like a huge pain)?

If the latter, are there simple node libraries to support this?

ContentLicense: CC BY-SA 3.0

Title: Adding headers with AWS SES

Body:
I've written a small node AWS Lambda function that uses AWS SES to send emails.

I'm trying to include a tracking pixel, and I'd like to add a no-cache email header:

HTTP 200 OK
Content-Type: image/png
Cache-Control: no-cache, max-age=0

Is there a way to do this with the regular ses.sendEmail() function? Or do I need to use the sendRawEmail() function (which seems like a huge pain)?

If the latter, are there simple node libraries to support this?

Body:
Tracking pixel is not attached image, it's just link to remote image.

 Looks like <img src="http://example.com/pixel.png?params">


问:
Is there a way to change the css of the button on keypress?
https://codepen.io/corpsist/pen/NWGZqOb

```<code>class DrumPad extends React.Component{
constructor(props){
super(props);
}

render(){
return(
  <div>
              <button type="button" id='Q' className="btn btn-lg btn-dark" onClick=this.handleClick}>Q</button>

  </div> )
</code>```

}
}

Need to change the CSS so that the button looks the same when pressed as when clicked.

答:
Use a combination of keypress/keyup to toggle the color by the help of jquery

$("button").keydown(function(e) {
    // Sets the color when the key is down...
    if(e.which === 13) {
     $(this).css("background-color", "purple");
    }
});
$("button").keyup(function() {
    // Removes the color when any key is lifted...
    $(this).css("background-color", "");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Test
</button></code>```

Body:
https://codepen.io/corpsist/pen/NWGZqOb

class DrumPad extends React.Component{
constructor(props){
super(props);
}

render(){
return(

              <button type="button" id='Q' className="btn btn-lg btn-dark" onClick=this.handleClick}>Q</button>

 )

}
}

Need to change the CSS so that the button looks the same when pressed as when clicked.

Body:
Use a combination of keypress/keyup to toggle the color by the help of jquery

$("button").keydown(function(e) {
    // Sets the color when the key is down...
    if(e.which === 13) {
     $(this).css("background-color", "purple");
    }
});
$("button").keyup(function() {
    // Removes the color when any key is lifted...
    $(this).css("background-color", "");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Test
</button>


答:
I assume you use Bootstrap framework, so you have to redefine styles for .btn-*** pseudo-classes like this: </p>

```<code>.btn-dark.focus, .btn-dark:focus {
...your styles go here...
}

.btn-dark(:disabled):not(.disabled).active, .btn-dark(:disabled):not(.disabled):active {
    ...your styles go here...
}
</code>```

Title: Is there a way to change the css of the button on keypress?

Body:
I assume you use Bootstrap framework, so you have to redefine styles for .btn-*** pseudo-classes like this:

.btn-dark.focus, .btn-dark:focus {
...your styles go here...
}

.btn-dark(:disabled):not(.disabled).active, .btn-dark(:disabled):not(.disabled):active {
    ...your styles go here...
}


问:
Compare String with each element of a String Array using Streams
Hi i want to count how many time a String is found in a Array of Strings using Streams

What i have thought so far is this:

```<code>Stream<String> stream=Arrays.stream(array);

int counter= (int) stream.filter(c-> c.contains("something")).count();

return counter;
</code>```

The problem that i get is that most of the time i get an error of NullPointerException and i think is because of .count() if it doesn't get any much inside filter(c-> c.contains("something")).
And i came to this conclusion cause if i run it with out .count() like that stream.filter(c-> c.contains("something")); without returning nothing, it won't throw an Exception. I'm not sure about it but that's what i think.

Any ideas on how i can count the times a String appears in and Array of Strings using Streams?

答:
null is a valid element of an array, so you have to be prepared to handle these. For example:

```<code>int counter = stream.filter(c -> c != null && c.contains("something")).count();
</code>```

Body:
Hi i want to count how many time a String is found in a Array of Strings using Streams

What i have thought so far is this:

Stream<String> stream=Arrays.stream(array);

int counter= (int) stream.filter(c-> c.contains("something")).count();

return counter;

The problem that i get is that most of the time i get an error of NullPointerException and i think is because of .count() if it doesn't get any much inside filter(c-> c.contains("something")).
And i came to this conclusion cause if i run it with out .count() like that stream.filter(c-> c.contains("something")); without returning nothing, it won't throw an Exception. I'm not sure about it but that's what i think.

Any ideas on how i can count the times a String appears in and Array of Strings using Streams?

Body:
null is a valid element of an array, so you have to be prepared to handle these. For example:

int counter = stream.filter(c -> c != null && c.contains("something")).count();


问:
SQL query to display data in gridview
I have a grid view that displays data from a SQL Server database during page load. My gridview contains these columns:

```<code>AssetType, IssuedOn, ReturnedOn
</code>```

I have used a query:

```<code>SqlCommand cmd = new SqlCommand(
    "SELECT * FROM AssetRequest WHERE ReturnedOn IS NULL OR ReturnedOn ='' ORDER BY id DESC",
    conn);
</code>```

which will display data from SQL Server in the gridview when ReturnedOn column doesn't have any data.

The new query has to satisfy these conditions,

It Should not displays a record when Assetype="Laptop" or "Desktop" and IssuedOn is not empty.

But if the Assetype="Laptop" or "Desktop" and IssuedOn is empty it should display the record.

If the Assetype=anything and Returnedon is not empty it should not display that record in gridview.

答:
According to your conditions above, this should meet your requirements:</p>

```<code>select *
from AssetRequest
where
  ((IssuedOn IS NULL OR IssuedOn = '') AND (Assetype IN ('Laptop', 'Desktop')) OR
  (ReturnedOn IS NULL OR ReturnedOn = '')
</code>```

Title: SQL query to display data in gridview

Body:
I have a grid view that displays data from a SQL Server database during page load. My gridview contains these columns:

AssetType, IssuedOn, ReturnedOn

I have used a query:

SqlCommand cmd = new SqlCommand(
    "SELECT * FROM AssetRequest WHERE ReturnedOn IS NULL OR ReturnedOn ='' ORDER BY id DESC",
    conn);

which will display data from SQL Server in the gridview when ReturnedOn column doesn't have any data.

The new query has to satisfy these conditions,

It Should not displays a record when Assetype="Laptop" or "Desktop" and IssuedOn is not empty.

But if the Assetype="Laptop" or "Desktop" and IssuedOn is empty it should display the record.

If the Assetype=anything and Returnedon is not empty it should not display that record in gridview.

Body:
According to your conditions above, this should meet your requirements:

select *
from AssetRequest
where
  ((IssuedOn IS NULL OR IssuedOn = '') AND (Assetype IN ('Laptop', 'Desktop')) OR
  (ReturnedOn IS NULL OR ReturnedOn = '')


问:
parallel calls to menu_rebuild after drush updatedb
Anyone have any idea why multiple calls to menu_rebuild could be made after the site comes up after a successful drush database update? Before I jump down the rabbit hole?

UPDATE:

To clarify I am using Pressflow.

Specifically when we run an update, multiple menu_router rebuilds are called resulting in duplicate key errors and max connection timeouts. The former issue occurs even with smaller updates.

UPDATE: to mitigate against this, is there a non-hack way to increase the lock timeout used by menu_rebuild? It calls that function with no parameters which defaults to 30s and we'd like to increase that.

答:
Drupal 6, right?

From what I have read there are some concurrency issues in the menu rebuild code that can cause it to get executed multiple times if multiple users hit the site right after you finish flushing the caches. I have seen this on our Drupal instance...

For example, if I hit "flush all caches" and it takes a few seconds, then I open a second browser and also browse to our site, open a third, etc... depending on how long this takes and the sequence it can trigger multiple menu rebuilds.

After the flush all appears to be fine after the first error.

Here's a couple of long posts I haven't fully read through that explain some of the concurrency issues:

http://drupal.org/node/246653

http://drupal.org/node/251792


问:
Why create method is not called in django serializer?
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image.

I want to be able to POST an entry one POST at a time.

```<code>localhost:8000/my_app/images/IMG_123/image_tags/
</code>```

I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why?

This is my source code:

```<code>#models.py
class ImageTag(models.Model):
    name = models.CharField()
    description = models.CharField()

class Image(models.Model):
    image_id = models.CharField(unique=True)
    image_tags = models.ManyToManyField(ImageTag, blank=True)
    ...

#serializers.py
class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = '__all__'

class ImageTagSerializer(serializers.ModelSerializer):
    image_tags = serializers.StringRelatedField(many=True)

    class Meta:
        model = Image
        fields = ('image_tags',)

    def to_internal_value(self, data):
        return data

    def create(self, validated_data):
        print("GOTHERE")
        print("VALI", validated_data)
        return validated_data

#views.py
class ImageExtraAction(viewsets.ModelViewSet):

    @action(detail=True, methods=['get', 'post', 'delete'])
    def image_tags(self, request, capture_id=None):
        capture = self.get_object()

        serializer = ImageTagSerializer(capture, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    lookup_field = 'image_id'
    ...

#urls.py
router.register(r'images', ImageTagViewSet, basename='image')
</code>```

答:
Because you are passing the instance too while initializing the serializer.

```<code>serializer = ImageTagSerializer(capture, data=request.data)
</code>```

Here, the capture is the model instance, at that time DRF thinks it is an update operation hence, DRF uses the update(...) method of the serializer.

Body:
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image.

I want to be able to POST an entry one POST at a time.

localhost:8000/my_app/images/IMG_123/image_tags/

I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why?

This is my source code:

#models.py
class ImageTag(models.Model):
    name = models.CharField()
    description = models.CharField()

class Image(models.Model):
    image_id = models.CharField(unique=True)
    image_tags = models.ManyToManyField(ImageTag, blank=True)
    ...

#serializers.py
class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = '__all__'

class ImageTagSerializer(serializers.ModelSerializer):
    image_tags = serializers.StringRelatedField(many=True)

    class Meta:
        model = Image
        fields = ('image_tags',)

    def to_internal_value(self, data):
        return data

    def create(self, validated_data):
        print("GOTHERE")
        print("VALI", validated_data)
        return validated_data

#views.py
class ImageExtraAction(viewsets.ModelViewSet):

    @action(detail=True, methods=['get', 'post', 'delete'])
    def image_tags(self, request, capture_id=None):
        capture = self.get_object()

        serializer = ImageTagSerializer(capture, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    lookup_field = 'image_id'
    ...

#urls.py
router.register(r'images', ImageTagViewSet, basename='image')

Body:
Because you are passing the instance too while initializing the serializer.

serializer = ImageTagSerializer(capture, data=request.data)

Here, the capture is the model instance, at that time DRF thinks it is an update operation hence, DRF uses the update(...) method of the serializer.


问:
ORACLE NLS_LANG
How set and check NLS_LANG settings? I did

```<code>set NLS_LANG = DANISH_DENMARK.WE8ISO8859P2
</code>```

in command prompt but I don't know if it is correct.

答:
It depends on the OS  and on the command interpreter:

Linux/bash:

```<code>echo $NLS_LANG
export NLS_LANG=...
</code>```

Windows/cmd.exe:

```<code>echo %NLS_LANG%
set NLS_LANG=...
</code>```

Make sure to have no space before and after =.

Title: ORACLE NLS_LANG

Body:
How set and check NLS_LANG settings? I did

set NLS_LANG = DANISH_DENMARK.WE8ISO8859P2

in command prompt but I don't know if it is correct.

Body:
It depends on the OS  and on the command interpreter:

Linux/bash:

echo $NLS_LANG
export NLS_LANG=...

Windows/cmd.exe:

echo %NLS_LANG%
set NLS_LANG=...

Make sure to have no space before and after =.


问:
JS how to stop previous while true when calling it again
I am trying to code a snake game using JS so I am rendering the game using SVG and moving the drawn parts using JS and loops

my problem is that I want to keep the rendering life "The while loop" but Every time I press a new key to change the snake direction The loop call stacks.

I tried looking for ways to stop that but I have no idea.

Does anyone have an idea on how to approach this problem?

const changeDirection = async key => {
  while(true){
    move(key);
    await sleep(10 * speed);
  }
}
```

答:
I found an answer to this by using setInterval

let prevKey = // last key stroke
let prevID  = //Interval Id

const changeDirection = async key => {
  if(prevKey !== key){
    clearInterval(prevID)
    prevKey = key
  }
  prevID = setInterval( () => {
    move(key);
  }, 10 * speed)

}
```

by saving the previous key and the Interval ID and clearing the interval when new valid key event happens

Body:
I found an answer to this by using setInterval

let prevKey = // last key stroke
let prevID  = //Interval Id

const changeDirection = async key => {
  if(prevKey !== key){
    clearInterval(prevID)
    prevKey = key
  }
  prevID = setInterval( () => {
    move(key);
  }, 10 * speed)

}

by saving the previous key and the Interval ID and clearing the interval when new valid key event happens


问:
Encountering errors when stacking convolutional network using keras
I am making a chess AI using keras. I encounter errors when stacking convolutional layers, as it states that the shape is inconsistent with the previous pooling layer. The error is as states below:

```<code>Input 0 of layer conv2d is incompatible with the layer: expected axis -1 of input shape to have value 12 but received input with shape [None, 3, 3, 2]
</code>```

A reproducible segment:

```<code>import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

board_inputs = keras.Input(shape=(8, 8, 12))

conv = layers.Conv2D(2, 3, activation='relu')
pooling = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = keras.layers.Flatten(data_format=None)

x = conv(board_inputs)
x = pooling(x)
x = conv(x)
# x = flatten(x)
# x = conv(x)
# x = pooling(x)
x = flatten(x)
output = layers.Dense(12)(x)
model = keras.Model(inputs=board_inputs, outputs=output, name="chess_ai_v3")
model.summary()

model.compile(
    loss=keras.losses.mse,
    optimizer=keras.optimizers.Adam(),
    metrics=None,
)

history = model.fit(trans_data[:len(trans_data)], pieces[:len(trans_data)], batch_size=64, epochs=1000)
</code>```

答:
you have to create another conv layer</p>

```<code>conv1 = Conv2D(2, 3, activation='relu')
conv2 = Conv2D(2, 3, activation='relu')
pooling = MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = Flatten(data_format=None)

board_inputs = Input(shape=(8, 8, 12))
x = conv1(board_inputs)
x = pooling(x)
x = conv2(x)
x = flatten(x)
output = Dense(12)(x)
model = Model(inputs=board_inputs, outputs=output, name="chess_ai_v3")
model.summary()
</code>```

Body:
I am making a chess AI using keras. I encounter errors when stacking convolutional layers, as it states that the shape is inconsistent with the previous pooling layer. The error is as states below:

Input 0 of layer conv2d is incompatible with the layer: expected axis -1 of input shape to have value 12 but received input with shape [None, 3, 3, 2]

A reproducible segment:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

board_inputs = keras.Input(shape=(8, 8, 12))

conv = layers.Conv2D(2, 3, activation='relu')
pooling = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = keras.layers.Flatten(data_format=None)

x = conv(board_inputs)
x = pooling(x)
x = conv(x)
# x = flatten(x)
# x = conv(x)
# x = pooling(x)
x = flatten(x)
output = layers.Dense(12)(x)
model = keras.Model(inputs=board_inputs, outputs=output, name="chess_ai_v3")
model.summary()

model.compile(
    loss=keras.losses.mse,
    optimizer=keras.optimizers.Adam(),
    metrics=None,
)

history = model.fit(trans_data[:len(trans_data)], pieces[:len(trans_data)], batch_size=64, epochs=1000)

Body:
you have to create another conv layer

conv1 = Conv2D(2, 3, activation='relu')
conv2 = Conv2D(2, 3, activation='relu')
pooling = MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = Flatten(data_format=None)

board_inputs = Input(shape=(8, 8, 12))
x = conv1(board_inputs)
x = pooling(x)
x = conv2(x)
x = flatten(x)
output = Dense(12)(x)
model = Model(inputs=board_inputs, outputs=output, name="chess_ai_v3")
model.summary()


问:
javax.swing.JTabbedPane not serializable?
When I want to deserialize a JTabbedPane, I get a NullPointerException.

My code is the following:

```<code>import javax.swing.*;
import java.io.*;

public class Bee {

    public static void main(final String[] args) {

        // --------- create tabbed pane
        JTabbedPane tabbedPane = new JTabbedPane();

        // ------------ Test serializing -------------------
        final String file = "/tmp/swing.ser";
        FileOutputStream fout = null;
        ObjectOutputStream out = null;
        FileInputStream fin = null;
        ObjectInputStream oin = null;

        try {
        // ______________________ Write tabbedPane... _______________________
            fout = new FileOutputStream(file);
            out = new ObjectOutputStream(fout);

            out.writeObject(tabbedPane);

            out.close();

            // ____________________________reading pane___________________
            fin = new FileInputStream(file);
            oin = new ObjectInputStream(fin);

            final JTabbedPane readPane = (JTabbedPane) oin.readObject();
            System.out.println("readPane: " + readPane.toString());
            oin.close();
            fin.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e2) {
            e2.printStackTrace();
        }
    }
}
</code>```

When I run this code with OpenJDK 8 9, OpenJDK 11 or Oracle JDK 14.0.1 on Ubuntu 20.04 as well as OpenJDK 9 and Oracle JDK 14 on Win 10 (version 1909), I get the following or very similar stacktrace (here, I show the output of Oracle JDK 14.0.1 on Ubuntu 20.04):

```<code>Exception in thread "main" java.lang.NullPointerException
at java.desktop/javax.swing.JTabbedPane.getTabCount(JTabbedPane.java:1118)
at java.desktop/javax.swing.plaf.basic.BasicTabbedPaneUI.installTabContainer(BasicTabbedPaneUI.java:308)
at java.desktop/javax.swing.plaf.basic.BasicTabbedPaneUI.installComponents(BasicTabbedPaneUI.java:304)
at java.desktop/javax.swing.plaf.basic.BasicTabbedPaneUI.installUI(BasicTabbedPaneUI.java:248)
at java.desktop/javax.swing.JComponent.setUI(JComponent.java:685)
at java.desktop/javax.swing.JTabbedPane.setUI(JTabbedPane.java:253)
at java.desktop/javax.swing.JTabbedPane.updateUI(JTabbedPane.java:269)
at java.desktop/javax.swing.SwingUtilities.updateComponentTreeUI0(SwingUtilities.java:1363)
at java.desktop/javax.swing.SwingUtilities.updateComponentTreeUI(SwingUtilities.java:1354)
at java.desktop/javax.swing.JComponent$ReadObjectCallback.validateObject(JComponent.java:5457)
at java.base/java.io.ObjectInputStream$ValidationList$1.run(ObjectInputStream.java:2758)
at java.base/java.io.ObjectInputStream$ValidationList$1.run(ObjectInputStream.java:2756)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:691)
at java.base/java.io.ObjectInputStream$ValidationList.doCallbacks(ObjectInputStream.java:2754)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:506)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:457)
at Bee.main(Bee.java:31)
</code>```

I know, it is a bad idea to serialize Swing objects. But, the code I have to work on makes heavy use of the serialization feature of Java Swing.

Thus, I would appreciate if anyone could point me to the mistake I made on deserializing JTabbedPane.

Update: @GeorgeZ.'s comment made me look into different JDKs ans OSs: JDK 8 works without NullPointerException on Ubuntu 20.04 (OpenJDK 1.8.0_252 - contrary to what I've written in my orginal post) and Win 10 build 1909 (OpenJDK 1.8.0_41). JDK 9 and above produces the NullPointerException (on Win10: OpenJDK 9 build 9+181 and Oracle JDK 14.0.1; on Ubuntu 20.04: OpenJDK 9 build 9+181, OpenJDK 11.0.7 and Oracle JDK 14.0.1). Therefore, it seems to be a regression.

答:
Currently, JTabbedPane cannot be deserialized in JDK versions of JDK 9 and newer including early access release of JDK 15.

I filed a bug report, which you can find at https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8245785.

As a workaround, you could

NOT serialize Swing GUI elements, but only the data model necessary to recreate the GUI (as @DontKnowMuchBut_GettingBetter pointed out) or

use JDK 8 (thanks for the hint, @GeorgeZ).

Body:
When I want to deserialize a JTabbedPane, I get a NullPointerException.

My code is the following:

import javax.swing.*;
import java.io.*;

public class Bee {

    public static void main(final String[] args) {

        // --------- create tabbed pane
        JTabbedPane tabbedPane = new JTabbedPane();

        // ------------ Test serializing -------------------
        final String file = "/tmp/swing.ser";
        FileOutputStream fout = null;
        ObjectOutputStream out = null;
        FileInputStream fin = null;
        ObjectInputStream oin = null;

        try {
        // ______________________ Write tabbedPane... _______________________
            fout = new FileOutputStream(file);
            out = new ObjectOutputStream(fout);

            out.writeObject(tabbedPane);

            out.close();

            // ____________________________reading pane___________________
            fin = new FileInputStream(file);
            oin = new ObjectInputStream(fin);

            final JTabbedPane readPane = (JTabbedPane) oin.readObject();
            System.out.println("readPane: " + readPane.toString());
            oin.close();
            fin.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e2) {
            e2.printStackTrace();
        }
    }
}

When I run this code with OpenJDK 8 9, OpenJDK 11 or Oracle JDK 14.0.1 on Ubuntu 20.04 as well as OpenJDK 9 and Oracle JDK 14 on Win 10 (version 1909), I get the following or very similar stacktrace (here, I show the output of Oracle JDK 14.0.1 on Ubuntu 20.04):

Exception in thread "main" java.lang.NullPointerException
at java.desktop/javax.swing.JTabbedPane.getTabCount(JTabbedPane.java:1118)
at java.desktop/javax.swing.plaf.basic.BasicTabbedPaneUI.installTabContainer(BasicTabbedPaneUI.java:308)
at java.desktop/javax.swing.plaf.basic.BasicTabbedPaneUI.installComponents(BasicTabbedPaneUI.java:304)
at java.desktop/javax.swing.plaf.basic.BasicTabbedPaneUI.installUI(BasicTabbedPaneUI.java:248)
at java.desktop/javax.swing.JComponent.setUI(JComponent.java:685)
at java.desktop/javax.swing.JTabbedPane.setUI(JTabbedPane.java:253)
at java.desktop/javax.swing.JTabbedPane.updateUI(JTabbedPane.java:269)
at java.desktop/javax.swing.SwingUtilities.updateComponentTreeUI0(SwingUtilities.java:1363)
at java.desktop/javax.swing.SwingUtilities.updateComponentTreeUI(SwingUtilities.java:1354)
at java.desktop/javax.swing.JComponent$ReadObjectCallback.validateObject(JComponent.java:5457)
at java.base/java.io.ObjectInputStream$ValidationList$1.run(ObjectInputStream.java:2758)
at java.base/java.io.ObjectInputStream$ValidationList$1.run(ObjectInputStream.java:2756)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:691)
at java.base/java.io.ObjectInputStream$ValidationList.doCallbacks(ObjectInputStream.java:2754)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:506)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:457)
at Bee.main(Bee.java:31)

I know, it is a bad idea to serialize Swing objects. But, the code I have to work on makes heavy use of the serialization feature of Java Swing.

Thus, I would appreciate if anyone could point me to the mistake I made on deserializing JTabbedPane.

Update: @GeorgeZ.'s comment made me look into different JDKs ans OSs: JDK 8 works without NullPointerException on Ubuntu 20.04 (OpenJDK 1.8.0_252 - contrary to what I've written in my orginal post) and Win 10 build 1909 (OpenJDK 1.8.0_41). JDK 9 and above produces the NullPointerException (on Win10: OpenJDK 9 build 9+181 and Oracle JDK 14.0.1; on Ubuntu 20.04: OpenJDK 9 build 9+181, OpenJDK 11.0.7 and Oracle JDK 14.0.1). Therefore, it seems to be a regression.


问:
Message: Session: Configured save path 'C:\Windows\Temp' is not writable by the PHP process
Codeigniter HMVC application is working fine on Linux hosting and xampp local server but after uploading on Plesk windows hosting it's throwing error. I have tried everything to fix it but still got same error.

```<code>An uncaught Exception was encountered
Type: Exception

Message: Session: Configured save path 'C:\Windows\Temp' is not writable by the PHP process.

Filename: G:\PleskVhosts\rkingmart.com\httpdocs\system\libraries\Session\drivers\Session_files_driver.php

Line Number: 143

Backtrace:

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 173
Function: _ci_load_library

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 190
Function: library

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 153
Function: libraries

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 65
Function: initialize

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Base.php
Line: 55
Function: __construct

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Base.php
Line: 60
Function: __construct

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Controller.php
Line: 4
Function: require

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Modules.php
Line: 123
Function: include_once

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\core\MY_Controller.php
Line: 3
Function: spl_autoload_call

File: G:\PleskVhosts\rkingmart.com\httpdocs\index.php
Line: 292
Function: require_once
</code>```

How can I fix this problem?

答:
finally, I got a solution. I have just replaced session configuration

application\config\config.php

```<code>$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
</code>```

to

```<code>$config['sess_driver']             = 'files';
$config['sess_cookie_name']        = 'pcfx_session_';
$config['sess_expiration']         = 7200;
$config['sess_save_path']          = APPPATH.'writable';
$config['sess_match_ip']           = FALSE;
$config['sess_time_to_update']     = 300;
$config['sess_regenerate_destroy'] = FALSE;
</code>```

Body:
Codeigniter HMVC application is working fine on Linux hosting and xampp local server but after uploading on Plesk windows hosting it's throwing error. I have tried everything to fix it but still got same error.

An uncaught Exception was encountered
Type: Exception

Message: Session: Configured save path 'C:\Windows\Temp' is not writable by the PHP process.

Filename: G:\PleskVhosts\rkingmart.com\httpdocs\system\libraries\Session\drivers\Session_files_driver.php

Line Number: 143

Backtrace:

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 173
Function: _ci_load_library

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 190
Function: library

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 153
Function: libraries

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Loader.php
Line: 65
Function: initialize

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Base.php
Line: 55
Function: __construct

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Base.php
Line: 60
Function: __construct

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Controller.php
Line: 4
Function: require

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\third_party\MX\Modules.php
Line: 123
Function: include_once

File: G:\PleskVhosts\rkingmart.com\httpdocs\application\core\MY_Controller.php
Line: 3
Function: spl_autoload_call

File: G:\PleskVhosts\rkingmart.com\httpdocs\index.php
Line: 292
Function: require_once

How can I fix this problem?

Body:
finally, I got a solution. I have just replaced session configuration

application\config\config.php

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

to

$config['sess_driver']             = 'files';
$config['sess_cookie_name']        = 'pcfx_session_';
$config['sess_expiration']         = 7200;
$config['sess_save_path']          = APPPATH.'writable';
$config['sess_match_ip']           = FALSE;
$config['sess_time_to_update']     = 300;
$config['sess_regenerate_destroy'] = FALSE;


问:
Why does `ann = F` not work when plotting with `as.factor` in R?
I am plotting a continuous variable against a factor using plot() in R (see example below).  I do not want the labels on the axes.  Without the as.factor call in the formula ann = F suppresses the printing of the labels but it doesn't work with as.factor in the formula.

Why is this?

Thank you.

```<code># example for SO
# example data
x <- sample(1:100, 10)
y <- c(rep(1, 5), rep(2, 5))

# ann = F doesn't work here
plot(x ~ as.factor(y), ann = F)

# ann = F does work here
plot(x ~ y, ann = F)
</code>```

答:
The dispatching system sends the non-working one to plot.factor, which then sends it to boxplot, which doesn't have an ann= argument, while the "working " one goes to plot.data.frame, which goes to plot.default eventually, which does honor the ann= argument. To suppress the naming. use:

plot(x ~ as.factor(y), names = rep("", 2))

Body:
I am plotting a continuous variable against a factor using plot() in R (see example below).  I do not want the labels on the axes.  Without the as.factor call in the formula ann = F suppresses the printing of the labels but it doesn't work with as.factor in the formula.

Why is this?

Thank you.

# example for SO
# example data
x <- sample(1:100, 10)
y <- c(rep(1, 5), rep(2, 5))

# ann = F doesn't work here
plot(x ~ as.factor(y), ann = F)

# ann = F does work here
plot(x ~ y, ann = F)


问:
Phalcon - Calling function from other controller
How to call function from another controller in Phalcon PHP framework. Here is example for CakePHP http://sherwinrobles.blogspot.com/2013/02/cakephp-calling-function-from-other.html</p>

答:
This is already Tested

For the people that aren't using CakePHP
another way to do this would be to do a helper Folder and write actions, in this case methods.

public/index.php

Add the path helper

```<code>$loader->registerDirs(
    [
        APP_PATH . '/helper/'
    ]
);
</code>```

Add a helper Order in apps

```<code>└── apps
    ├── controllers
       └─ exampleController.php
    ├── models
    └── helpers
       └─ myHelper.php
    ...
</code>```

In myHelper.php

```<code> <?php

    use Phalcon\Di\Injectable;

    class myHelper extends Injectable
        {
          function myNameFunction() {
          // here you should write your function

        }
    }
</code>```

In exampleController where you want to call the other action, in this case function

```<code><?php

use Phalcon\Mvc\Controller;

class exampleController extends Controller {
  public function yourAction() {
    //your code
    //there are 2 ways of calling the function. either use this one
    $myHelper = new myHelper();
    $myHelper->myNameFunction();

    //or this one
    (new UnmatchHelper())->myNameFunction();
  }
}
</code>```

Body:
This is already Tested

For the people that aren't using CakePHP
another way to do this would be to do a helper Folder and write actions, in this case methods.

public/index.php

Add the path helper

$loader->registerDirs(
    [
        APP_PATH . '/helper/'
    ]
);

Add a helper Order in apps

└── apps
    ├── controllers
       └─ exampleController.php
    ├── models
    └── helpers
       └─ myHelper.php
    ...

In myHelper.php

 <?php

    use Phalcon\Di\Injectable;

    class myHelper extends Injectable
        {
          function myNameFunction() {
          // here you should write your function

        }
    }

In exampleController where you want to call the other action, in this case function

<?php

use Phalcon\Mvc\Controller;

class exampleController extends Controller {
  public function yourAction() {
    //your code
    //there are 2 ways of calling the function. either use this one
    $myHelper = new myHelper();
    $myHelper->myNameFunction();

    //or this one
    (new UnmatchHelper())->myNameFunction();
  }
}


问:
Whatsapp otp verification wso2 is 5.10
Whether in wso2is can do otp via whatsapp? if can do it, please let us know how to configure. thanks you</p>

答:
Twilio provides an API for WhatsApp [1]. You can use the generic WSO2 SMS OTP authenticator [2] and configure it to send messages to users via WhatsApp. The only difference in the configuration on the WSO2 IS side is the from and to parameters of the HTTP payload.

```<code>Body=$ctx.msg&To=whatsapp:$ctx.num&From=whatsapp:+111222333
</code>```

WhatsApp provides their own API [2] as well, but the set up it seems to be bit complex. If you set it up successfully, I believe you can integrate with the exciting WSO2 SMS OTP authenticator [2] for this as well.

https://www.twilio.com/docs/whatsapp/api

https://is.docs.wso2.com/en/5.10.0/learn/configuring-sms-otp/

https://www.whatsapp.com/business/api

Title: Whatsapp otp verification wso2 is 5.10

Body:
Twilio provides an API for WhatsApp [1]. You can use the generic WSO2 SMS OTP authenticator [2] and configure it to send messages to users via WhatsApp. The only difference in the configuration on the WSO2 IS side is the from and to parameters of the HTTP payload.

Body=$ctx.msg&To=whatsapp:$ctx.num&From=whatsapp:+111222333

WhatsApp provides their own API [2] as well, but the set up it seems to be bit complex. If you set it up successfully, I believe you can integrate with the exciting WSO2 SMS OTP authenticator [2] for this as well.

https://www.twilio.com/docs/whatsapp/api

https://is.docs.wso2.com/en/5.10.0/learn/configuring-sms-otp/

https://www.whatsapp.com/business/api


问:
Having trouble coding a REACT onChange
I'm new to REACT and I'm having trouble trying to figure out not only the onChange event props, but many of the others. Its the props being passed in thats getting me. eg

```<code>handleSubmit(e) {
  let s = this.state;
  s.data[e.target.name] = e.target.value;
  this.setState(s);
}
</code>```

its given like this in pretty much all the examples I have seen (the declaration of the function) and always complains about e in the function def as being implicitly an 'any' type. If I declare it as e:any it stops complaining, but then I cant get the s.data[e.target.name] to work as it says I cant have an 'any' type as an index. I cant figure out how it's meant to be declared, or if I have a configuration issue somewhere. It works if I replace e.target.name with a string constant like 'myarray'.

The REACT app was generated with a plain

```<code>npx create-react-app test --template typescript
</code>```

with no changes to the generated configuration files.

The state was declared as

```<code>state = {
  data: { fldName: 'something', anotherField: 'somethingelse'}
}
</code>```

Any ideas ?

答: Try changing let s = this.state; to let s = Object.assign({}, this.state);. If you are changing it rather than copying it, that will be a reason it might not work. You may need to also do s.data = { ...s.data, [e.target.name]: e.target.value } which is doing the same thing to s.data, I usually keep my state flat.

Title: Having trouble coding a REACT onChange

Body:
I'm new to REACT and I'm having trouble trying to figure out not only the onChange event props, but many of the others. Its the props being passed in thats getting me. eg

handleSubmit(e) {
  let s = this.state;
  s.data[e.target.name] = e.target.value;
  this.setState(s);
}

its given like this in pretty much all the examples I have seen (the declaration of the function) and always complains about e in the function def as being implicitly an 'any' type. If I declare it as e:any it stops complaining, but then I cant get the s.data[e.target.name] to work as it says I cant have an 'any' type as an index. I cant figure out how it's meant to be declared, or if I have a configuration issue somewhere. It works if I replace e.target.name with a string constant like 'myarray'.

The REACT app was generated with a plain

npx create-react-app test --template typescript

with no changes to the generated configuration files.

The state was declared as

state = {
  data: { fldName: 'something', anotherField: 'somethingelse'}
}

Any ideas ?


问:
Extension Methods in VB 2008 assembly cannot be used in a C# project?
I wrote some string extension methods in a VB assembly and am unit testing them from a C# project. However, C# acts like it cannot see the the extension methods, when other VB projects reference the VB assembly they have no problem. Both the VB assemebly and the C# test project are targeting .Net 3.5.

Is there a way around this?

VB.Net extension methods:

```<code>Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions
Imports System.Linq

Namespace ExtensionMethods
    Module StringExtensions

        <Extension()> _
        Public Function Remove( _
                            ByVal input As String, _
                            ByVal subStrings As String()) As String
            ...
        End Function

        <Extension()> _
        Public Function Substrings( _
                            ByVal input As String, _
                            ByVal regexPattern As String, _
                            ByVal regexOptions As RegexOptions) As IEnumerable(Of String)
            ...
        End Function

        <Extension()> _
        Public Function Substrings( _
                            ByVal input As String, _
                            ByVal regexPattern As String) As IEnumerable(Of String)
            ...
        End Function
    End Module
End Namespace
</code>```

VB.Net usage:

```<code>Imports SomeNamespace.ExtensionMethods
...
someString = someString.Remove(subStringsToRemove)
</code>```

C# usage (doesn't work):

```<code>using SomeNamespace.ExtensionMethods;               //No error, but ExtensionMethods is not in the intellisense
...
someString = someString.Remove(subStringsToRemove);  //error, can't find matching overlaod
</code>```

答:
Tried to make the module 'Public'?

Update:

Can't explain why it worked with other VB assemblies. Think that C# has its own vision of class access modifiers or something.

Body:
I wrote some string extension methods in a VB assembly and am unit testing them from a C# project. However, C# acts like it cannot see the the extension methods, when other VB projects reference the VB assembly they have no problem. Both the VB assemebly and the C# test project are targeting .Net 3.5.

Is there a way around this?

VB.Net extension methods:

Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions
Imports System.Linq

Namespace ExtensionMethods
    Module StringExtensions

        <Extension()> _
        Public Function Remove( _
                            ByVal input As String, _
                            ByVal subStrings As String()) As String
            ...
        End Function

        <Extension()> _
        Public Function Substrings( _
                            ByVal input As String, _
                            ByVal regexPattern As String, _
                            ByVal regexOptions As RegexOptions) As IEnumerable(Of String)
            ...
        End Function

        <Extension()> _
        Public Function Substrings( _
                            ByVal input As String, _
                            ByVal regexPattern As String) As IEnumerable(Of String)
            ...
        End Function
    End Module
End Namespace

VB.Net usage:

Imports SomeNamespace.ExtensionMethods
...
someString = someString.Remove(subStringsToRemove)

C# usage (doesn't work):

using SomeNamespace.ExtensionMethods;               //No error, but ExtensionMethods is not in the intellisense
...
someString = someString.Remove(subStringsToRemove);  //error, can't find matching overlaod


问:
Not sure where to autogenerate Primary Keys in Room
I am a beginner of Android development and I am trying to write a Notes demo app following the app architecture of this example by Google.

According to the example, the ViewModel should access the model defined in the domain package i.e. the ViewModel doesn't need to know what the model is like from the API or the Database. (At least that's what I understand from the tutorial)

So in my Note app, I have data class in the domain package and database package. (which are essentially the same)

```<code>data class Note (
    val id: Long,
    val title: String,
    val body: String
)
</code>```

```<code>@Entity(tableName = "notes_table")
data class DatabaseNote constructor(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    var title: String = "TITLE",
    var body: String = "BODY"
)
</code>```

To create a new note in the ViewModel, I need to create a new Note object, where the id is required!
My question is, should I just create a DatabaseNote object from the ViewModel, so I can autogenerate an id?
If that's the case, what's the point of the domain model?

Thanks in advance!

答:
Make the id nullable

```<code>data class Note (
    val id: Long?,
    val title: String,
    val body: String
)
</code>```

the database will then create one for you when an id is not supplied

Body:
I am a beginner of Android development and I am trying to write a Notes demo app following the app architecture of this example by Google.

According to the example, the ViewModel should access the model defined in the domain package i.e. the ViewModel doesn't need to know what the model is like from the API or the Database. (At least that's what I understand from the tutorial)

So in my Note app, I have data class in the domain package and database package. (which are essentially the same)

data class Note (
    val id: Long,
    val title: String,
    val body: String
)

@Entity(tableName = "notes_table")
data class DatabaseNote constructor(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    var title: String = "TITLE",
    var body: String = "BODY"
)

To create a new note in the ViewModel, I need to create a new Note object, where the id is required!
My question is, should I just create a DatabaseNote object from the ViewModel, so I can autogenerate an id?
If that's the case, what's the point of the domain model?

Thanks in advance!

Body:
Make the id nullable

data class Note (
    val id: Long?,
    val title: String,
    val body: String
)

the database will then create one for you when an id is not supplied


问:
convert tiff to netcdf
i try to convert a tiff to netcdf file. errors is saying index error:

```<code>import numpy as np
from netCDF4 import Dataset
import rasterio

with rasterio.drivers():
    src=rasterio.open(r"ia.tiff","r")
    dst_transform=src.transform
    dst_width=src.width
    dst_height=src.height
    print (dst_transform)
    xmin = dst_transform[0]
    xmax = dst_transform[0] + dst_transform[1]*dst_width
    print (xmax)
    min = dst_transform[3] + dst_transform[5]*dst_height
    print(ymin)
    ymax = dst_transform[3]

    dst_width=dst_width+1
    dst_height=dst_height+1
    outf=Dataset(r'ia.nc','w',format='NETCDF4_CLASSIC')
    lats=np.linspace(ymin,ymax,dst_width)
    lons=np.linspace(xmin,xmax,dst_height)

    lat=outf.createDimension('lon',len(lats))
    lon=outf.createDimension('lat',len(lons))
    longitude=outf.createVariable('longitude',np.float64,('lon',))
    latitude=outf.createVariable('latitude',np.float64,('lat',))
    SHIA=outf.createVariable('SHIA',np.int8,('lon','lat'))

    outf.variables['longitude'][:]=lons
    outf.varibales['longitude'][:]=lat
    im=src.read()
    SHIA[:,:]=im

    outf.description="IA for"
    longitude.units="degrees east"
    latitude.units='degrees north'

    print ("created empty array")

    outf.close()

outf.close()
</code>```

error is that index error: size of the data array does not conform to slice. can somebody take a look and help me where i did wrong. Much appreciated!

答:
The easiest way I could think of is to use the GDAL tool.</p>

```<code># Convert TIF to netCDF
gdal_translate -of netCDF -co "FOMRAT=NC4" ia.tif ia.nc

# Convert SHP to netCDF
gdal_rasterize -of netCDF -burn 1 -tr 0.01 0.01 input.shp output.nc
</code>```

Title: convert tiff to netcdf

Body:
i try to convert a tiff to netcdf file. errors is saying index error:

import numpy as np
from netCDF4 import Dataset
import rasterio

with rasterio.drivers():
    src=rasterio.open(r"ia.tiff","r")
    dst_transform=src.transform
    dst_width=src.width
    dst_height=src.height
    print (dst_transform)
    xmin = dst_transform[0]
    xmax = dst_transform[0] + dst_transform[1]*dst_width
    print (xmax)
    min = dst_transform[3] + dst_transform[5]*dst_height
    print(ymin)
    ymax = dst_transform[3]

    dst_width=dst_width+1
    dst_height=dst_height+1
    outf=Dataset(r'ia.nc','w',format='NETCDF4_CLASSIC')
    lats=np.linspace(ymin,ymax,dst_width)
    lons=np.linspace(xmin,xmax,dst_height)

    lat=outf.createDimension('lon',len(lats))
    lon=outf.createDimension('lat',len(lons))
    longitude=outf.createVariable('longitude',np.float64,('lon',))
    latitude=outf.createVariable('latitude',np.float64,('lat',))
    SHIA=outf.createVariable('SHIA',np.int8,('lon','lat'))

    outf.variables['longitude'][:]=lons
    outf.varibales['longitude'][:]=lat
    im=src.read()
    SHIA[:,:]=im

    outf.description="IA for"
    longitude.units="degrees east"
    latitude.units='degrees north'

    print ("created empty array")

    outf.close()

outf.close()

error is that index error: size of the data array does not conform to slice. can somebody take a look and help me where i did wrong. Much appreciated!

Body:
The easiest way I could think of is to use the GDAL tool.

# Convert TIF to netCDF
gdal_translate -of netCDF -co "FOMRAT=NC4" ia.tif ia.nc

# Convert SHP to netCDF
gdal_rasterize -of netCDF -burn 1 -tr 0.01 0.01 input.shp output.nc


问:
Redshift - Find percentage of contribution by category
I have my data in the below format:

```<code>product, person
prod_a, person_1
prod_a, person_2
prod_a, person_3
prod_b, person_1
</code>```

I am trying to find the percent contributed by each person per product. Expected output is :

```<code>product, person, prct
prod_a, person_1, 0.33
prod_a, person_2, 0.33
prod_a, person_3, 0.33
prod_b, person_1, 1
</code>```

答:
You can use window functions:

```<code>select
    product,
    person,
    1.0 * count(*) over(partition by product, person)
        / count(*) over(partition by product) as prct
from mytable
</code>```

If, as shown in your sample data, there are no duplicate (product, person) tuples, then it is a bit simpler:

```<code>select
    product,
    person,
    1.0 / count(*) over(partition by product) as prct
from mytable
</code>```

Body:
I have my data in the below format:

product, person
prod_a, person_1
prod_a, person_2
prod_a, person_3
prod_b, person_1

I am trying to find the percent contributed by each person per product. Expected output is :

product, person, prct
prod_a, person_1, 0.33
prod_a, person_2, 0.33
prod_a, person_3, 0.33
prod_b, person_1, 1

Body:
You can use window functions:

select
    product,
    person,
    1.0 * count(*) over(partition by product, person)
        / count(*) over(partition by product) as prct
from mytable

If, as shown in your sample data, there are no duplicate (product, person) tuples, then it is a bit simpler:

select
    product,
    person,
    1.0 / count(*) over(partition by product) as prct
from mytable


问:
WARNING in c called " 's1' and 's2' is used uninitialized in this function"
cant solve the warning in c called s1 s2 is used uninitialized this function </p>

```<code>int main()
{
    char *s1, *s2;
    printf("Please enter string s1 and then s2:\n");
    scanf("%s %s", s1, s2);
    printf("%s %s", *s1, *s2);
return 0;
}
</code>```

答:
You have to allocate for s1 and s2:

```<code>// do not forget to include the library <stdlib.h> for malloc function
s1 = malloc(20); // string length of s1 ups to 19;
if(!s1) {return -1;}
s2 = malloc(20) // // string length of s2 ups to 19 also;
if(!s2) {return -1;}
</code>```

The in scanf function, should change to (Disadvantages of scanf):

```<code>scanf("%19s %19s", s1, s2); // or using fgets
</code>```

Or you can use the array of character instead of using pointer:

```<code>char s1[20], s2[20];
// Or you can define a maximum length MAX_LEN, then using:
// char s1[MAX_LEN], s2[MAX_LEN];
</code>```

Body:
cant solve the warning in c called s1 s2 is used uninitialized this function

int main()
{
    char *s1, *s2;
    printf("Please enter string s1 and then s2:\n");
    scanf("%s %s", s1, s2);
    printf("%s %s", *s1, *s2);
return 0;
}

Body:
You have to allocate for s1 and s2:

// do not forget to include the library <stdlib.h> for malloc function
s1 = malloc(20); // string length of s1 ups to 19;
if(!s1) {return -1;}
s2 = malloc(20) // // string length of s2 ups to 19 also;
if(!s2) {return -1;}

The in scanf function, should change to (Disadvantages of scanf):

scanf("%19s %19s", s1, s2); // or using fgets

Or you can use the array of character instead of using pointer:

char s1[20], s2[20];
// Or you can define a maximum length MAX_LEN, then using:
// char s1[MAX_LEN], s2[MAX_LEN];


问:
toFixed(2) rounds "x.525" inconsistently?
I'm experiencing rounding errors when using toFixed:

I used toFixed(2) on my numeric value calculations, but the rounding results are not as expected for few cases.

Suppose that toFixed(2) is applied for value 17.525 then it gives the result 17.52, And if it is applied for 5.525 then it gives the result 5.53.

In the later case the rounding result is accurate, so can you please suggest what needs to be done to get the accurate rounding result as in the later case. Or can you please suggest an alternative to this toFixed function to get correct rounding results?

答:
Use Intl.NumberFormat and in options set minimumFractionDigits and maximumFractionDigits to the same number (number of digits you want to display).

const formatter = [0, 1, 2, 3, 4, 5].map(
    (decimals) =>
        new Intl.NumberFormat('en-US', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals,
        }),
);

console.log(formatter[2].format(17.525)); // 17.53
console.log(formatter[2].format(5.525)); // 5.53
console.log(formatter[2].format(1.005)); // 1.01
console.log(formatter[2].format(8.635)); // 8.64
console.log(formatter[2].format(8.575)); // 8.58
console.log(formatter[2].format(35.855)); // 35.86
console.log(formatter[2].format(859.385)); // 589.39
console.log(formatter[2].format(859.3844)); // 589.38
console.log(formatter[2].format(.004)); // 0.00
console.log(formatter[2].format(0.0000001)); // 0.00

// keep in mind that this will not be formatted as expected, as the value that
// you pass is actually 0.07499999999998863.
console.log(formatter[2].format(239.575 - 239.5)); // 0.07
console.log(formatter[2].format(0.07499999999998863)); // 0.07```


问:
OpenEdge AppServer timeout
I'm using plain old OpenEdge AppServer (not PAS) 11.7 using a generated proxy dll (Proxy Generator for Open Clients) for C#.

This works quite good apart from setting a timeout for connections.
If I call a function using that proxy I want to set a timeout so that the call fails (e.g. by throwing an exception)

I've tried following Progress.Open4GL.RunTimeProperties

RunTimeProperties.ConnectionTimeout

Undocumented. Does not do what the name suggests

RunTimeProperties.SocketTimeout = 8000;

Not documented. Default is 0. Value mostlikely to be milliseconds

Getting closer with this setting. If the execution time of the called function exceeeds this
value an Progress.Open4GL.Exceptions.Open4GLException is thrown

BUT: It only throws when the calling function returns thus it is quite useless.
Easy to test by adding a "PAUSE 100" to the function to be called. After 100 seconds the exception gets thrown (and not after 8 seconds)

How to implement a timeout for a function call?

答:
Sort of...

You can set a global timeout for app server calls.  But not a function by function timeout.

According to https://knowledgebase.progress.com/articles/Article/P174143

Two new features were introduced in OpenEdge 10.2B in order to achieve
  this goal, either at the procedure block level or at the Application
  Server level.

At the procedure block level:

The first way to time restrict procedure calls involves the use of the
  STOP-AFTER phrase. This phrase specifies a time-out value for a DO,
  FOR, or REPEAT block. The integer expression that specifies the number
  of seconds each iteration of a block has until a time-out occurs. If a
  time-out occurs, the AVM raises the STOP condition.

At the Application Server level:

Another way to limit the execution time of procedure calls is to set
  the property called srvrExecutionTimeLimit in the global [UBroker] or
  specific [UBroker.] section of the ubroker.properties
  file. This is a non-negative integer property that specifies the
  maximum time in seconds that a remote procedure may execute on the
  given AppServer. This timeout value applies to all remote procedures
  that execute on the AppServer.  The default value is zero, which
  indicates that no time limit is in effect. AppServer
  srvrExecutionTimeLimit property only controls the execution time of a
  procedure on the remote AppServer. The data transfer between the
  client and AppServer endpoints do not account for the procedure
  execution time.

STOP-AFTER apparently doesn't interrupt most statements. It seems that it is checked between statements.  Consider the following:

```<code>etime( yes ).

repeat stop-after 5 on stop undo, leave:

  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.

end.

display etime.
pause.
</code>```

vs.

```<code>etime( yes ).

repeat stop-after 5 on stop undo, leave:

  pause 10.

end.

display etime.
pause.
</code>```

vs.

```<code>etime( yes ).

repeat stop-after 5 on stop undo, leave:

  pause 1.

end.

display etime.
pause.
</code>```

So, depending on what your app server code is actually doing this may, or may not, help.

Title: OpenEdge AppServer timeout

Body:
Sort of...

You can set a global timeout for app server calls.  But not a function by function timeout.

According to https://knowledgebase.progress.com/articles/Article/P174143

Two new features were introduced in OpenEdge 10.2B in order to achieve
  this goal, either at the procedure block level or at the Application
  Server level.

At the procedure block level:

The first way to time restrict procedure calls involves the use of the
  STOP-AFTER phrase. This phrase specifies a time-out value for a DO,
  FOR, or REPEAT block. The integer expression that specifies the number
  of seconds each iteration of a block has until a time-out occurs. If a
  time-out occurs, the AVM raises the STOP condition.

At the Application Server level:

Another way to limit the execution time of procedure calls is to set
  the property called srvrExecutionTimeLimit in the global [UBroker] or
  specific [UBroker.] section of the ubroker.properties
  file. This is a non-negative integer property that specifies the
  maximum time in seconds that a remote procedure may execute on the
  given AppServer. This timeout value applies to all remote procedures
  that execute on the AppServer.  The default value is zero, which
  indicates that no time limit is in effect. AppServer
  srvrExecutionTimeLimit property only controls the execution time of a
  procedure on the remote AppServer. The data transfer between the
  client and AppServer endpoints do not account for the procedure
  execution time.

STOP-AFTER apparently doesn't interrupt most statements. It seems that it is checked between statements.  Consider the following:

etime( yes ).

repeat stop-after 5 on stop undo, leave:

  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.
  pause 1.

end.

display etime.
pause.

vs.

etime( yes ).

repeat stop-after 5 on stop undo, leave:

  pause 10.

end.

display etime.
pause.

vs.

etime( yes ).

repeat stop-after 5 on stop undo, leave:

  pause 1.

end.

display etime.
pause.

So, depending on what your app server code is actually doing this may, or may not, help.


问:
How to get back first character to end of previous line with Vim
I have following code:

```<code>mapping make_episode(string series, string title, string episode, array date)
{
    return ([ "series":series, "episode":episode, "title":title, "date":date ]);
}

void print_episode(mapping episode)
{
    write("  %-30s %10s %-30s (%{%d.%})\n",
          episode->series, episode->episode, episode->title, episode->date);
}
</code>```

I want to get all "{" (opening curly braces) at beginning of lines to be moved to end of previous lines.

I searched for it on the net but could not find it.

What command do I give in Vim to do above task (moving all such characters in one go)?

答:
You can match lines of interest with :global and then join them with :join

```<code>g/^{$/-join
</code>```

(use join! if you don't need an extra space).

To go step by step:

```<code>g/.../...     ----> for every line matching regex do a command
 /^{$/        ----> regex: single left brace on a line
      -join   ----> join previous line with the next one (i.e. the currently matched line)
</code>```

Body:
I have following code:

mapping make_episode(string series, string title, string episode, array date)
{
    return ([ "series":series, "episode":episode, "title":title, "date":date ]);
}

void print_episode(mapping episode)
{
    write("  %-30s %10s %-30s (%{%d.%})\n",
          episode->series, episode->episode, episode->title, episode->date);
}

I want to get all "{" (opening curly braces) at beginning of lines to be moved to end of previous lines.

I searched for it on the net but could not find it.

What command do I give in Vim to do above task (moving all such characters in one go)?

Body:
You can match lines of interest with :global and then join them with :join

g/^{$/-join

(use join! if you don't need an extra space).

To go step by step:

g/.../...     ----> for every line matching regex do a command
 /^{$/        ----> regex: single left brace on a line
      -join   ----> join previous line with the next one (i.e. the currently matched line)


Title: svg-sprite: symbol conversion to single svg icon

Body:
I have a svg sprite like the following:

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width:0;height:0;visibility:hidden;">
    <symbol viewBox="0 0 500 500" id="test-icon"><title>test</title><ellipse class="background" id="test-background" fill="#fff" cx="248.8" cy="251.4" rx="246.2" ry="244.8"/>
        <path class="test-frame" d="M249.4 18C121.1 18 16.8 122.3 16.8 250.6S121.3 483 249.4 483 482 378.8 482 250.5 377.7 18 249.4 18m0 480.8c-66 0-128.3-26.4-176.2-73.1C27.6 378.9 1.3 316.5 1.3 249.3s26.3-128.2 73.1-175 109.1-73.1 175-73.1 128.3 26.4 176.2 73.1c46.7 46.8 73.1 109.2 73.1 176.2s-26.4 128.3-73.1 176.2c-46.7 45.6-109 72.1-176.2 72.1"/>
        <path class="test-figure" d="M133.8 103.5v293h232.5V148.9l-22-22-23.4-23.4H133.8zm17.9 22h108.7v12.4H151.7v-12.4zm0 24.8h108.7v12.4H151.7v-12.4zm192.5 211.8H151.7v-24.7h191.2v24.7h1.3zm0-41.2H151.7v-24.7h191.2v24.7h1.3zm0-42.7H151.7v-24.7h191.2v24.7h1.3zm0-44H151.7v-23.4h191.2v23.4h1.3z"/>
    </symbol>
    <symbol viewBox="0 0 500 500" id="test-icon"><title>test</title><ellipse class="background" id="test-background" fill="#fff" cx="248.8" cy="251.4" rx="246.2" ry="244.8"/>
        <path class="test-frame" d="M249.4 18C121.1 18 16.8 122.3 16.8 250.6S121.3 483 249.4 483 482 378.8 482 250.5 377.7 18 249.4 18m0 480.8c-66 0-128.3-26.4-176.2-73.1C27.6 378.9 1.3 316.5 1.3 249.3s26.3-128.2 73.1-175 109.1-73.1 175-73.1 128.3 26.4 176.2 73.1c46.7 46.8 73.1 109.2 73.1 176.2s-26.4 128.3-73.1 176.2c-46.7 45.6-109 72.1-176.2 72.1"/>
        <path class="test-figure" d="M133.8 103.5v293h232.5V148.9l-22-22-23.4-23.4H133.8zm17.9 22h108.7v12.4H151.7v-12.4zm0 24.8h108.7v12.4H151.7v-12.4zm192.5 211.8H151.7v-24.7h191.2v24.7h1.3zm0-41.2H151.7v-24.7h191.2v24.7h1.3zm0-42.7H151.7v-24.7h191.2v24.7h1.3zm0-44H151.7v-23.4h191.2v23.4h1.3z"/>
    </symbol>
    <symbol viewBox="0 0 500 500" id="test-icon"><title>test</title><ellipse class="background" id="test-background" fill="#fff" cx="248.8" cy="251.4" rx="246.2" ry="244.8"/>
        <path class="test-frame" d="M249.4 18C121.1 18 16.8 122.3 16.8 250.6S121.3 483 249.4 483 482 378.8 482 250.5 377.7 18 249.4 18m0 480.8c-66 0-128.3-26.4-176.2-73.1C27.6 378.9 1.3 316.5 1.3 249.3s26.3-128.2 73.1-175 109.1-73.1 175-73.1 128.3 26.4 176.2 73.1c46.7 46.8 73.1 109.2 73.1 176.2s-26.4 128.3-73.1 176.2c-46.7 45.6-109 72.1-176.2 72.1"/>
        <path class="test-figure" d="M133.8 103.5v293h232.5V148.9l-22-22-23.4-23.4H133.8zm17.9 22h108.7v12.4H151.7v-12.4zm0 24.8h108.7v12.4H151.7v-12.4zm192.5 211.8H151.7v-24.7h191.2v24.7h1.3zm0-41.2H151.7v-24.7h191.2v24.7h1.3zm0-42.7H151.7v-24.7h191.2v24.7h1.3zm0-44H151.7v-23.4h191.2v23.4h1.3z"/>
    </symbol>
</svg>

Now my question is: can I just make a svg out of the symbol, just by extracting the symbol and then replacing the symbol-tag with an svg-tag? Or how can I achieve this conversion to separate svg?

I thought of a little script, that can inject several svg icons from an svg-sprite like above, so the icons can be style by css better/individually.

The thing here is that in the sprite there are symbols, which (as far as I read) can only be used with <use xlink:href>. But then the icon can't be styled individually like inline svg could be (as it is a clone).

Edit:
I found open-iconic svgIncetor that uses an img-src and single svgs to inject into the html.
Also to mention is that I alread read following articles by Chris Coyier:

http://css-tricks.com/svg-use-external-source/

http://css-tricks.com/svg-symbol-good-choice-icons/

http://css-tricks.com/icon-fonts-vs-svg/

http://css-tricks.com/svg-sprites-use-better-icon-fonts/

Basically I want to combine the technics used there to have an icon system, that can have multi-color icons based on css and icon-sprite (with inline svg through js-inject).
The open-iconic injector can only inject sinlge svgs and not from sprites afaik.

Body:
I have created a small script using Nodejs and svg-parser, to split a SVG icons sprite file:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol id="act" viewBox="0 0 48 48">
      <path d="M24 22c0.552 0 1-0.448 1-1v-18c0-0.552-0.448-1-1-1s-1 0.448-1 1v18c0 0.552 0.448 1 1 1z" />
      <path
        d="M33.027 8.148c0 0-0.010 0.013-0.012 0.015-0.152-0.094-0.322-0.163-0.515-0.163-0.552 0-1 0.448-1 1 0 0.377 0.217 0.693 0.525 0.864 0.004 0.004-0.001 0.015 0.004 0.018 5.503 2.817 9.971 8.868 9.971 16.118 0 9.625-7.866 18-18 18-10.17 0-18-8.375-18-18 0-7.33 4.443-13.31 9.972-16.118 0.005-0.002 0-0.014 0.003-0.018 0.308-0.171 0.525-0.487 0.525-0.864 0-0.552-0.448-1-1-1-0.191 0-0.359 0.068-0.511 0.16-0.002-0.002-0.011-0.015-0.011-0.015-6.513 3.298-10.978 10.055-10.978 17.855 0 11.046 8.954 20 20 20s20-8.954 20-20c0-7.798-4.462-14.553-10.973-17.852z" />
    </symbol>
    ...
  </defs>
</svg>

const fs = require('fs');
const { parse } = require('svg-parser');

// Read from sprite file
fs.readFile('file.svg', 'utf8', function (err, contents) {
  console.log(err);
  const parsed = parse(contents);
  const symbols = parsed.children[0].children[0].children;

  symbols.forEach(symbol => {
    let paths = '';
    const name = symbol.properties.id;
    symbol.children.forEach(path => {
      paths = paths + `<path d="${path.properties.d}" />`
    });

    // Build SVG content
    const newIcon = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50">
      <g>
        ${paths}
      </g>
    </svg>`

    // White to file
    fs.writeFile(`export/${name}.svg`, newIcon, () => {
      console.log(name);
    });
  });

});


问:
Scrapy crawlspider does not follow links
I'm trying to make a crawler that will crawl an entire website and output a list of all the domains that the said websites links to (without duplicates).

I have come up with the following code :

```<code>import scrapy
from crawler.items import CrawlerItem
from crawler.functions import urlToDomain
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class domainSpider(CrawlSpider):
    global allDomains
    allDomains = []
    name = "domainSpider"
    allowed_domains = ["example.com"]
    start_urls = [
        "https://example.com/"
    ]

    rules = (
        Rule(LinkExtractor(), callback='parse', follow=True),
    )

    def parse(self, response):

        urls = response.xpath("//a/@href").extract()
        # formating all URL formats to the same one (https://url.com)
        urlsOk = []
        for elt in urls :
            if elt [:2] == "//" : # link is external, append http
                urlsOk.append(elt)
            elif elt[:4] == "http" :
                urlsOk.append(elt)

        domaines = list(set([urlToDomain(x) for x in urlsOk]))
        item = CrawlerItem()
        item["domaines"] = []
        item["url"] = response.url
        for elt in domaines:
            if elt not in allDomains :
                item['domaines'].append(elt)
                allDomains.append(elt)

                yield({
                    'domaines':elt

                })
</code>```

This is workinge exactly like expected in retrieving the domains, but it stops crawling (finished) after the very first page.

答:
I was overriding a built-in CrawlSpider method (parse) which caused the bug...

The solution was to change the callback method's name from parse to anything else.

Body:
I'm trying to make a crawler that will crawl an entire website and output a list of all the domains that the said websites links to (without duplicates).

I have come up with the following code :

import scrapy
from crawler.items import CrawlerItem
from crawler.functions import urlToDomain
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class domainSpider(CrawlSpider):
    global allDomains
    allDomains = []
    name = "domainSpider"
    allowed_domains = ["example.com"]
    start_urls = [
        "https://example.com/"
    ]

    rules = (
        Rule(LinkExtractor(), callback='parse', follow=True),
    )

    def parse(self, response):

        urls = response.xpath("//a/@href").extract()
        # formating all URL formats to the same one (https://url.com)
        urlsOk = []
        for elt in urls :
            if elt [:2] == "//" : # link is external, append http
                urlsOk.append(elt)
            elif elt[:4] == "http" :
                urlsOk.append(elt)

        domaines = list(set([urlToDomain(x) for x in urlsOk]))
        item = CrawlerItem()
        item["domaines"] = []
        item["url"] = response.url
        for elt in domaines:
            if elt not in allDomains :
                item['domaines'].append(elt)
                allDomains.append(elt)

                yield({
                    'domaines':elt

                })

This is workinge exactly like expected in retrieving the domains, but it stops crawling (finished) after the very first page.


问:
null value in column "installed_on" violates not-null constraint
We created a new database by coping from an older flyway managed database. (flyway version table also copied over)

Running flyway against this new database produces the following flyway error

Apr 24 19:00:19 ip-xx flyway: Unable to insert row for version '184' in Schema History table "public"."flyway_schema_history"
Apr 24 19:00:19 ip--xx flyway: -----------------------------------------------------------------------------------------------
Apr 24 19:00:19 ip--xx flyway: SQL State  : 23502
Apr 24 19:00:19 ip--xx flyway: Error Code : 0
Apr 24 19:00:19 ip--xx flyway: Message    : ERROR: null value in column "installed_on" violates not-null constraint

答:
In my case, the error occurred while upgrading from flyway version 5.x to 6.4.3.
The definition of installed_on column of the flyway_schema_history table (at least in PostgreSQL) has changed from:

```<code>installed_on timestamp NOT NULL;
</code>```

to:

```<code>installed_on timestamp NOT NULL DEFAULT now ()
</code>```

Adding DEFAULT now() on the existing table has fixed the problem.

Body:
In my case, the error occurred while upgrading from flyway version 5.x to 6.4.3.
The definition of installed_on column of the flyway_schema_history table (at least in PostgreSQL) has changed from:

installed_on timestamp NOT NULL;

to:

installed_on timestamp NOT NULL DEFAULT now ()

Adding DEFAULT now() on the existing table has fixed the problem.


问:
Get Email Details through IMAP
I used javax.mail to get Emails. I'm able to fetch email details like attachments, cc, bcc, from, to, text, subject. The issue I'm facing is It is getting only that email not all the messages in that email. Let suppose A sent email to B and B replied back to A. Then again replied to B. Now if I'm login with A's profile and I fetch INBOX folder of A. I get this email and when I check message.content() of that email It shows only reply of B. I want to get content of first message and third message sent by A as both of the messages belong to this thread.

答:
IIRC conversation threads are implementation dependent cause it's not enforced nor covered in the IMAP RFC. There are some servers like gmail that lets you configure those settings. In your case it might be possible to read a specific message and then performing other IMAP verbs to retrieve the rest of the thread.

More info: https://www.rfc-editor.org/rfc/rfc3501

Title: Get Email Details through IMAP


问:
Get data from a APIview in django rest framework
In my app I am trying to get the User data using a get request and it works in Postman but the problem occurs when I try to send the data from FrontEnd as we cannot send Body in get Request

URL:

```<code>           path('user/meta/', UserDetails.as_view()),
</code>```

Views.py

```<code>class UserDetails(APIView):
    """Get basic details of user"""

    def get(self, request):

        username = request.data["username"]
        if User.objects.filter(username = username).exists():

            user = User.objects.get(username = username)
            print(user)

            return Response({
                'verified': user.verified,
            })
        else:
            return Response("User doesn't exists", status=status.HTTP_400_BAD_REQUEST)
</code>```

How should I modify it such that I can get the data from get request?

答:
So, your requesting URL will become ```<code>/user-info/?<b>username=john</b></code>```
and then, use request.GET

```<code> username = request<b>.GET</b>.get("username","default_value")</code>```

Body:
In my app I am trying to get the User data using a get request and it works in Postman but the problem occurs when I try to send the data from FrontEnd as we cannot send Body in get Request

URL:

           path('user/meta/', UserDetails.as_view()),

Views.py

class UserDetails(APIView):
    """Get basic details of user"""

    def get(self, request):

        username = request.data["username"]
        if User.objects.filter(username = username).exists():

            user = User.objects.get(username = username)
            print(user)

            return Response({
                'verified': user.verified,
            })
        else:
            return Response("User doesn't exists", status=status.HTTP_400_BAD_REQUEST)

How should I modify it such that I can get the data from get request?

Body:
So, your requesting URL will become
/user-info/?username=john

and then, use request.GET

 username = request.GET.get("username","default_value")


问:
Why create method is not called in django serializer?
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image.

I want to be able to POST an entry one POST at a time.

```<code>localhost:8000/my_app/images/IMG_123/image_tags/
</code>```

I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why?

This is my source code:

```<code>#models.py
class ImageTag(models.Model):
    name = models.CharField()
    description = models.CharField()

class Image(models.Model):
    image_id = models.CharField(unique=True)
    image_tags = models.ManyToManyField(ImageTag, blank=True)
    ...

#serializers.py
class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = '__all__'

class ImageTagSerializer(serializers.ModelSerializer):
    image_tags = serializers.StringRelatedField(many=True)

    class Meta:
        model = Image
        fields = ('image_tags',)

    def to_internal_value(self, data):
        return data

    def create(self, validated_data):
        print("GOTHERE")
        print("VALI", validated_data)
        return validated_data

#views.py
class ImageExtraAction(viewsets.ModelViewSet):

    @action(detail=True, methods=['get', 'post', 'delete'])
    def image_tags(self, request, capture_id=None):
        capture = self.get_object()

        serializer = ImageTagSerializer(capture, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    lookup_field = 'image_id'
    ...

#urls.py
router.register(r'images', ImageTagViewSet, basename='image')
</code>```

答:
You try to put everything in your @action() function, as if it was a new viewsets.ModelViewSet. It's not working that way.

If you want to have all the mixins of viewsets.ModelViewSet, you have to create a separate ModelViewSet, or reimplement all methods in your action (see, in your image_tags(), the HTTP method is not even used)

Body:
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image.

I want to be able to POST an entry one POST at a time.

localhost:8000/my_app/images/IMG_123/image_tags/

I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why?

This is my source code:

#models.py
class ImageTag(models.Model):
    name = models.CharField()
    description = models.CharField()

class Image(models.Model):
    image_id = models.CharField(unique=True)
    image_tags = models.ManyToManyField(ImageTag, blank=True)
    ...

#serializers.py
class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = '__all__'

class ImageTagSerializer(serializers.ModelSerializer):
    image_tags = serializers.StringRelatedField(many=True)

    class Meta:
        model = Image
        fields = ('image_tags',)

    def to_internal_value(self, data):
        return data

    def create(self, validated_data):
        print("GOTHERE")
        print("VALI", validated_data)
        return validated_data

#views.py
class ImageExtraAction(viewsets.ModelViewSet):

    @action(detail=True, methods=['get', 'post', 'delete'])
    def image_tags(self, request, capture_id=None):
        capture = self.get_object()

        serializer = ImageTagSerializer(capture, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    lookup_field = 'image_id'
    ...

#urls.py
router.register(r'images', ImageTagViewSet, basename='image')


问:
Timeout issue during data transfer from MySQL to SQL Server using SSIS
I am trying to transfer 67,714,854 rows from MySQL to SQL Server using SSIS. The package times out after transferring 14,282,990 rows. I changed the time out property to 0 also, but that didn't help.

How do I resolve this issue?

答:
Does MySQL give you the error or are you using PHP (or another language) to transfer the data and does that timeout? In the case of the latter, in PHP you can set the script timeout to infinite using this:

```<code>set_time_limit(0);
</code>```

Either way, based on the information given, I'm not sure what type of database it is, but typically I would set up a cron script to transfer the data bit by bit in order to keep the load at an acceptable level. Please give more information...

Body:
Does MySQL give you the error or are you using PHP (or another language) to transfer the data and does that timeout? In the case of the latter, in PHP you can set the script timeout to infinite using this:

set_time_limit(0);

Either way, based on the information given, I'm not sure what type of database it is, but typically I would set up a cron script to transfer the data bit by bit in order to keep the load at an acceptable level. Please give more information...