问:
Sum of Tree Leaves using Lambda (Python)
I'm trying to return the sum of values in its left leaves. My trees are defined with this interface

class Tree(object):
  def __init__(self, x):
    self.value = x
    self.left = None
    self.right = None
```

<p>I am confused as to how/why this lambda function accomplishes this task. Could someone explain what the lambda function is checking for? </p>

<pre class="lang-py prettyprint-override"><code>leftLeavesSum=g=lambda t,f=0:t and f*t.value*(t.left==t.right)+g(t.left,1)+g(t.right) or 0
</code>```

Thanks!

答:
This answer is going to be long. Not because it's complicated, but because I wanted to explain things as simple as I can.

So, let's divide the answer into three parts:

How does this lambda function work?

Let's try out an example to see if it does its job

How to fix any problems if found

First Part

How does this lambda function work? The best way to know that is to divide this whole lambda into simple if..else conditions like so which hopefully will be self-explanatory:

```<code>def g(t, f=0):
    if t:                               #checks if t is not None
        sum_left_branch = g(t.left,1)   #gets the sum of left branch
        sum_right_branch = g(t.right)   #gets the sum of right branch
        is_leaf_node = t.left==t.right  #1 if t is a leaf node (has no children)
        return (f*t.value)*is_leaf_node + sum_left_branch + sum_right_branch
    else:
        return 0
</code>```

This function uses f to filter values. As you can see, f is zero when it's used with t.right which makes the value of (f*t.value)*is_leaf_node of the right branch always zero.

Second part:

In the following code, I'm going to create a simple tree on the following form and see if this function works as it should be:

```<code>#    __1
#   /   \
#  3     2
# / \
#4   5

parent = Tree(1)
brother = Tree(2)
me = Tree(3)
child1 = Tree(4)
child2 = Tree(5)
# set connections
parent.left = me
parent.right = brother
me.left = child1
me.right = child2
</code>```

Now, let's run the function over the parent:

```<code>leftLeavesSum(parent)  #4
</code>```

Which is the value of leftmost leaf node child1 = Tree(4). According to your question, you want the sum of all leaves on the left branch. So, the value should be 7 if you didn't count the root and 8 if you did.

So, I think this function doesn't work properly; which leads us to the third part

Third part

The following is the right implementation to this function (in my opinion) with the minimum amount of change:

```<code>def g(t, f=0):
    if t is not None:
        sum_left_branch = g(t.left,1)
        return (f*t.value) + sum_left_branch
    return 0
</code>```

Let's try this function with the same Tree as before:

```<code># exclude the root
g(parent)    #7

# include the root
g(parent, 1) #8
</code>```

Body:
I'm trying to return the sum of values in its left leaves. My trees are defined with this interface

class Tree(object):
  def __init__(self, x):
    self.value = x
    self.left = None
    self.right = None

I am confused as to how/why this lambda function accomplishes this task. Could someone explain what the lambda function is checking for?

leftLeavesSum=g=lambda t,f=0:t and f*t.value*(t.left==t.right)+g(t.left,1)+g(t.right) or 0

Thanks!

Body:
This answer is going to be long. Not because it's complicated, but because I wanted to explain things as simple as I can.

So, let's divide the answer into three parts:

How does this lambda function work?

Let's try out an example to see if it does its job

How to fix any problems if found

First Part

How does this lambda function work? The best way to know that is to divide this whole lambda into simple if..else conditions like so which hopefully will be self-explanatory:

def g(t, f=0):
    if t:                               #checks if t is not None
        sum_left_branch = g(t.left,1)   #gets the sum of left branch
        sum_right_branch = g(t.right)   #gets the sum of right branch
        is_leaf_node = t.left==t.right  #1 if t is a leaf node (has no children)
        return (f*t.value)*is_leaf_node + sum_left_branch + sum_right_branch
    else:
        return 0

This function uses f to filter values. As you can see, f is zero when it's used with t.right which makes the value of (f*t.value)*is_leaf_node of the right branch always zero.

Second part:

In the following code, I'm going to create a simple tree on the following form and see if this function works as it should be:

#    __1
#   /   \
#  3     2
# / \
#4   5

parent = Tree(1)
brother = Tree(2)
me = Tree(3)
child1 = Tree(4)
child2 = Tree(5)
# set connections
parent.left = me
parent.right = brother
me.left = child1
me.right = child2

Now, let's run the function over the parent:

leftLeavesSum(parent)  #4

Which is the value of leftmost leaf node child1 = Tree(4). According to your question, you want the sum of all leaves on the left branch. So, the value should be 7 if you didn't count the root and 8 if you did.

So, I think this function doesn't work properly; which leads us to the third part

Third part

The following is the right implementation to this function (in my opinion) with the minimum amount of change:

def g(t, f=0):
    if t is not None:
        sum_left_branch = g(t.left,1)
        return (f*t.value) + sum_left_branch
    return 0

Let's try this function with the same Tree as before:

# exclude the root
g(parent)    #7

# include the root
g(parent, 1) #8


来源: stackexchange

问:
Building a stock market trading game in RoR, what libraries are available?
I'd like to build a relatively simple online stock trading application (in RoR). It would just be a game so no real trades- just an online simulation based on real market data.

A good example being http://www.wallstreetsurvivor.com/ or http://www.weseed.com/
(any ideas what libs / platforms they are using?)

There will be no CFD Trading, Spread Betting, Currency Trading or Fixed Odds. It will just be stock trading - using market / stop / limit orders.

Naturally, it will need to generate visualisations and pull in market data.

Can someone point me in the right direction regarding libraries (stuff like yahoo finance gem) / platforms I can use to get me started?

There seems to be some existing java platforms but they are very much geared towards single users.

Also, I'd much prefer to use Rails. If there's a real problem with this then I'd be open to switching platform/language.

答: There are some code referece you will find in EclipseTrader for the same. I think you take the feed from real market and make order matching engine based on people order. </p>

ContentLicense: CC BY-SA 3.0


问:
Firebase deploy errors starting with non-zero exit code (space in project path)
I was having issues with firebase deploy command recently. After firebase deploy command all others were being deployed except firebase (storage, database etc) So I decided to reinstall firebase to fix this situation but after reinstall my problem got bigger. Now none of them are deployed with the following error:

```<code>i deploying database, functions
Running command: npm --prefix $RESOURCE_DIR run lint
npm ERR! path C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\faruk\AppData\Roaming\npm-cache\_logs\2018-01-24T18_21_34_878Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code4294963238
</code>```

After a bit research, I saw some topics about this which advice to change

```<code>$RESOURCE_DIR to %RESOURCE_DIR%
</code>```

in windows systems (I am using windows 10 btw). So, I edited my firebase.json  file which is in one upper level of my functions folder. like this. (I don't know if this is the right file that I should edit)

```<code>  "database": {
    "rules": "database.rules.json"
  },
  "functions": {
    "predeploy": [
      "npm --prefix %RESOURCE_DIR% run lint"
    ]
  }
}
</code>```

but after this edit, I started to get another error message like this.

```<code>i  deploying database, functions
Running command: npm --prefix %RESOURCE_DIR% run lint

Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, profile, prune,
    publish, rb, rebuild, repo, restart, root, run, run-script,
    s, se, search, set, shrinkwrap, star, stars, start, stop, t,
    team, test, token, tst, un, uninstall, unpublish, unstar,
    up, update, v, version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    C:\Users\faruk\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@5.6.0 C:\Program Files\nodejs\node_modules\npm

Error: functions predeploy error: Command terminated with non-zero exit code1
</code>```

Any advice is appreciated. Thanks in advance.

答:
I fixed it: you must pay attention at another place

Do you see the error description

```<code>$ firebase deploy --only functions

=== Deploying to 'fix-firebase-functions'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint C:\Users\vuduc\OneDrive\Tài liệu\Code tutotial         practice\test\functions
> eslint .

C:\Users\vuduc\OneDrive\Tài liệu\Code tutotial practice\test\functions\index.js
  37:16  warning  Avoid nesting promises                      promise/no-nesting
  42:13  error    Expected catch() or return                  promise/catch-or-return
  42:13  warning  Avoid nesting promises                      promise/no-nesting
  42:31  error    Each then() should return a value or throw  promise/always-return

✖ 4 problems (2 errors, 2 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\vuduc\AppData\Roaming\npm-cache\_logs\2020-06-01T14_38_16_060Z-debug.log
events.js:287
    throw er; // Unhandled 'error' event
      ^

Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
    at notFoundError (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
    at verifyENOENT (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
    at ChildProcess.cp.emit (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:25)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Emitted 'error' event on ChildProcess instance at:
    at ChildProcess.cp.emit (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:37)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)

  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn npm --prefix "%RESOURCE_DIR%" run lint',
  path: 'npm --prefix "%RESOURCE_DIR%" run lint',
  spawnargs: []

Error: functions predeploy error: Command terminated with non-zero exit code1
</code>```

error deploy cloud functions
You need to scroll up to see the error description, the line

```<code>functions predeploy error: Command terminated with non-zero exit code1
</code>```

is just a general description that there is an error to fix before deploying.
This is what really needs attention, which instructions do you need to fix?

```<code>✖ 4 problems (2 errors, 2 warnings)
</code>```

Pay attention here

ContentLicense: CC BY-SA 4.0

Body:
I was having issues with firebase deploy command recently. After firebase deploy command all others were being deployed except firebase (storage, database etc) So I decided to reinstall firebase to fix this situation but after reinstall my problem got bigger. Now none of them are deployed with the following error:

i deploying database, functions
Running command: npm --prefix $RESOURCE_DIR run lint
npm ERR! path C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\faruk\AppData\Roaming\npm-cache\_logs\2018-01-24T18_21_34_878Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code4294963238

After a bit research, I saw some topics about this which advice to change

$RESOURCE_DIR to %RESOURCE_DIR%

in windows systems (I am using windows 10 btw). So, I edited my firebase.json  file which is in one upper level of my functions folder. like this. (I don't know if this is the right file that I should edit)

  "database": {
    "rules": "database.rules.json"
  },
  "functions": {
    "predeploy": [
      "npm --prefix %RESOURCE_DIR% run lint"
    ]
  }
}

but after this edit, I started to get another error message like this.

i  deploying database, functions
Running command: npm --prefix %RESOURCE_DIR% run lint

Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, profile, prune,
    publish, rb, rebuild, repo, restart, root, run, run-script,
    s, se, search, set, shrinkwrap, star, stars, start, stop, t,
    team, test, token, tst, un, uninstall, unpublish, unstar,
    up, update, v, version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    C:\Users\faruk\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@5.6.0 C:\Program Files\nodejs\node_modules\npm

Error: functions predeploy error: Command terminated with non-zero exit code1

Any advice is appreciated. Thanks in advance.

Body:
I fixed it: you must pay attention at another place

Do you see the error description

$ firebase deploy --only functions

=== Deploying to 'fix-firebase-functions'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint C:\Users\vuduc\OneDrive\Tài liệu\Code tutotial         practice\test\functions
> eslint .

C:\Users\vuduc\OneDrive\Tài liệu\Code tutotial practice\test\functions\index.js
  37:16  warning  Avoid nesting promises                      promise/no-nesting
  42:13  error    Expected catch() or return                  promise/catch-or-return
  42:13  warning  Avoid nesting promises                      promise/no-nesting
  42:31  error    Each then() should return a value or throw  promise/always-return

✖ 4 problems (2 errors, 2 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\vuduc\AppData\Roaming\npm-cache\_logs\2020-06-01T14_38_16_060Z-debug.log
events.js:287
    throw er; // Unhandled 'error' event
      ^

Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
    at notFoundError (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
    at verifyENOENT (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
    at ChildProcess.cp.emit (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:25)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Emitted 'error' event on ChildProcess instance at:
    at ChildProcess.cp.emit (C:\Users\vuduc\AppData\Local\Yarn\Data\global\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:37)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)

  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn npm --prefix "%RESOURCE_DIR%" run lint',
  path: 'npm --prefix "%RESOURCE_DIR%" run lint',
  spawnargs: []

Error: functions predeploy error: Command terminated with non-zero exit code1

error deploy cloud functions
You need to scroll up to see the error description, the line

functions predeploy error: Command terminated with non-zero exit code1

is just a general description that there is an error to fix before deploying.
This is what really needs attention, which instructions do you need to fix?

✖ 4 problems (2 errors, 2 warnings)

Pay attention here


问:
Making a draft of tic-tac-toe
```<code>import numpy as np
player1 = True

def create_board():
    board = np.zeros((3,3), dtype=int)
    return board

def place(board , player1 , position ):
    if player1 == True:
        player1 = False
        if board[position] == 0:
            board = position
        elif board[position] != 0:
            print("False , place taken 1")
    else:
        if player1 == False:
            if board[position] == 0:
                board = position
            elif board[position] != [0, 0]:
                print("False , place taken 2 ")
    return board
</code>```

Function call:

```<code>place(board=create_board() , player1=1 , position=(0,0))
</code>```

Here is my code, in this code there is a lot going on however there is one part i could not get it right . In the bold section , i am trying to replace

```<code>([0,0,0],
 [0,0,0],
 [0,0,0])
</code>```

to

```<code>([1,0,0],
 [0,0,0],
 [0,0,0])
</code>```

May i know , how can I do this please ... Thank you !

答:
When you try to update your board in board = position you are actually updating the whole board with your pair of coordinates.

What you really want is to pinpoint the exact position in your two-dimensional array that you have to update to store an occupied cell. You could archieve that changing that line with

```<code>board[position] = 1 # occupied cell
</code>```

However, as Hammad said in another answer, it would be convienient to change your

```<code>0 for unoccupied
1 for occupied
</code>```

and having to rely on knowing whose turn is ongoing at the moment, to

```<code>0 for unoccupied
1 for occupied by player one
2 for occupied by player two
</code>```

so you always know who occupied that cell.

Title: Making a draft of tic-tac-toe

Body:
import numpy as np
player1 = True

def create_board():
    board = np.zeros((3,3), dtype=int)
    return board

def place(board , player1 , position ):
    if player1 == True:
        player1 = False
        if board[position] == 0:
            board = position
        elif board[position] != 0:
            print("False , place taken 1")
    else:
        if player1 == False:
            if board[position] == 0:
                board = position
            elif board[position] != [0, 0]:
                print("False , place taken 2 ")
    return board

Function call:

place(board=create_board() , player1=1 , position=(0,0))

Here is my code, in this code there is a lot going on however there is one part i could not get it right . In the bold section , i am trying to replace

([0,0,0],
 [0,0,0],
 [0,0,0])

to

([1,0,0],
 [0,0,0],
 [0,0,0])

May i know , how can I do this please ... Thank you !

Body:
When you try to update your board in board = position you are actually updating the whole board with your pair of coordinates.

What you really want is to pinpoint the exact position in your two-dimensional array that you have to update to store an occupied cell. You could archieve that changing that line with

board[position] = 1 # occupied cell

However, as Hammad said in another answer, it would be convienient to change your

0 for unoccupied
1 for occupied

and having to rely on knowing whose turn is ongoing at the moment, to

0 for unoccupied
1 for occupied by player one
2 for occupied by player two

so you always know who occupied that cell.


问:
Is it possible to achieve "Delayed Execution" with KSQL?

implement KSQL UDF "NOW()"

create stream my_notification_stream as select * from my_event_stream where occurTime + threshold
< NOW()

listening on my_notification_stream topic

答:
I don't think the solution you're proposing would work as you expect, as stream data is processed as soon as it can be.  The result is not recalculated as time advances.

However, you may be able to achieve what you want in other ways.

Take the example of wanting to automatically close orders after 30 minutes if no payment has been received.  This can be achieved by left-joining the orders stream with the payments stream, within a window of 30 minutes, and then filtering out any results with a payment. This would give you a stream of unpaid orders:

```<code>-- create stream of unpaid orders:
CREATE STREAM UNPAID AS
   SELECT * FROM ORDERS
     LEFT JOIN PAYMENTS WITHIN 30 MINUTES ON ORDERS.ORDERID = PAYMENTS.ORDERID
   WHERE PAYMENTS.ORDERID IS NULL;
</code>```

The second example, if I understand it correctly, may be more tricky. You can easily build a table of users, including when their subscription ends. However, that is not sufficient to the '3-day before expiry' you need.   The problem is that the NOW udf you talk about is only executed when the data is processed, not as wall clock time changes. What you need is some other way of prompting ksqlDB to re-evaluate your expression.

I don't think this is currently possible with ksqlDB, at least not until it supports non-key joins.

Body:
I don't think the solution you're proposing would work as you expect, as stream data is processed as soon as it can be.  The result is not recalculated as time advances.

However, you may be able to achieve what you want in other ways.

Take the example of wanting to automatically close orders after 30 minutes if no payment has been received.  This can be achieved by left-joining the orders stream with the payments stream, within a window of 30 minutes, and then filtering out any results with a payment. This would give you a stream of unpaid orders:

-- create stream of unpaid orders:
CREATE STREAM UNPAID AS
   SELECT * FROM ORDERS
     LEFT JOIN PAYMENTS WITHIN 30 MINUTES ON ORDERS.ORDERID = PAYMENTS.ORDERID
   WHERE PAYMENTS.ORDERID IS NULL;

The second example, if I understand it correctly, may be more tricky. You can easily build a table of users, including when their subscription ends. However, that is not sufficient to the '3-day before expiry' you need.   The problem is that the NOW udf you talk about is only executed when the data is processed, not as wall clock time changes. What you need is some other way of prompting ksqlDB to re-evaluate your expression.

I don't think this is currently possible with ksqlDB, at least not until it supports non-key joins.


问:
HTML "checkbox" connect with asp.net core MVC , connecting model to checkbox buttons
So I am making a survey website where you can create survey forms and fill them after, my question is if I have a question where i have a collection of it's options with bool if the option is marked on filling or not, how do I set that value to the model when i click onto Submit form button
In short words get all marked answers from the questions, pass them to the controller as a separate view model that contains only the ID of the question and the given answer

Here is the class of the question :

```<code> public class OptionsQuestionVM
    {
        public Guid Id { get; set; }

        public Guid FormId { get; set; }

        public bool IsAnswered { get; set; }
        public bool IsDeleted { get; set; }

        public string Name { get; set; }
        public ICollection<OptionModelVM> Options { get; set; }
        public bool IsRequired { get; set; }
        public bool HasMultipleAnswers { get; set; }

    }
</code>```

Here is the class of the OptionModelVM:

```<code>public class OptionModelVM
    {
        public Guid Id { get; set; }

        public string Text { get; set; }
        public bool IsMarked { get; set; }
        public OptionsQuestionVM Question { get; set; }
        public Guid OptionsQuestionId { get; set; }
    }
</code>```

And here is my HTML Code for the checkbox that will be displayed for each question and it's available answers:

```<code>@foreach (var item in Model.OptionsQuestions)
                    {
                        if (item.HasMultipleAnswers == true)
                        {
                            <div class="element-checkbox">
                                <hr>
                                <h4>@item.Name</h4>
                                <div class="column column1">

                                    @foreach (var option in item.Options)
                                    {
                                        <label>
                                            <input type="checkbox" name="checkbox[]" value="option 1" />
                                            <span style="font-size:medium">@option.Text</span>
                                        </label>
                                        <br />
                                    }

                                </div><span class="clearfix"></span>
                            </div>
                        }
                        else
                        {

                                <div class="element-checkbox" single>
                                    <hr>
                                    <h4>@item.Name</h4>
                                    <div class="column column1">

                                        @foreach (var option in item.Options)
                                        {
                                            <label>
                                                <input type="checkbox" name="checkbox[]" value="option 1" />
                                                <span style="font-size:medium">@option.Text</span>
                                            </label>
                                            <br />
                                        }

                                    </div><span class="clearfix"></span>
                                </div>

                        }

                    }
</code>```

And also it would help if someone tells me how to set the HasMultipleAnswers bool into the checkbox, so that when its true you can mark more than 1 answer, when false you can choose only 1
Thank you :)

答:
Model binding is done through element names. The easiest way to accomplish model binding is to use the html helpers.
At the top of your view put:

```<code>@model OptionsQuestionVM
</code>```

then where you want a checkbox use (IsAnswered for example):

```<code>@Html.CheckboxFor(m => m.IsAnswered, new { @class="any classes"})
</code>```

If you have a form surrounding this field, when the form is submitted that field will be passed to the server.

Your controller:

```<code>public ActionResult SomeName(OptionsQuestionVM model){}
</code>```

where model is holding the values from the view.

As for handling multiple answers and binding that to a list. This is called complex model binding take a look at this article: https://krishnrajrana.wordpress.com/2015/12/15/asp-net-mvc-post-a-list-or-collection-of-complex-types-with-non-sequential-indices/
and this question from StackOverflow: MVC post a list of complex objects

Body:
So I am making a survey website where you can create survey forms and fill them after, my question is if I have a question where i have a collection of it's options with bool if the option is marked on filling or not, how do I set that value to the model when i click onto Submit form button
In short words get all marked answers from the questions, pass them to the controller as a separate view model that contains only the ID of the question and the given answer

Here is the class of the question :

 public class OptionsQuestionVM
    {
        public Guid Id { get; set; }

        public Guid FormId { get; set; }

        public bool IsAnswered { get; set; }
        public bool IsDeleted { get; set; }

        public string Name { get; set; }
        public ICollection<OptionModelVM> Options { get; set; }
        public bool IsRequired { get; set; }
        public bool HasMultipleAnswers { get; set; }

    }

Here is the class of the OptionModelVM:

public class OptionModelVM
    {
        public Guid Id { get; set; }

        public string Text { get; set; }
        public bool IsMarked { get; set; }
        public OptionsQuestionVM Question { get; set; }
        public Guid OptionsQuestionId { get; set; }
    }

And here is my HTML Code for the checkbox that will be displayed for each question and it's available answers:

@foreach (var item in Model.OptionsQuestions)
                    {
                        if (item.HasMultipleAnswers == true)
                        {

@item.Name

                                    @foreach (var option in item.Options)
                                    {

                                            <input type="checkbox" name="checkbox[]" value="option 1" />
                                            @option.Text

                                    }

                        }
                        else
                        {

@item.Name

                                        @foreach (var option in item.Options)
                                        {

                                                <input type="checkbox" name="checkbox[]" value="option 1" />
                                                @option.Text

                                        }

                        }

                    }

And also it would help if someone tells me how to set the HasMultipleAnswers bool into the checkbox, so that when its true you can mark more than 1 answer, when false you can choose only 1
Thank you :)

Body:
Model binding is done through element names. The easiest way to accomplish model binding is to use the html helpers.
At the top of your view put:

@model OptionsQuestionVM

then where you want a checkbox use (IsAnswered for example):

@Html.CheckboxFor(m => m.IsAnswered, new { @class="any classes"})

If you have a form surrounding this field, when the form is submitted that field will be passed to the server.

Your controller:

public ActionResult SomeName(OptionsQuestionVM model){}

where model is holding the values from the view.

As for handling multiple answers and binding that to a list. This is called complex model binding take a look at this article: https://krishnrajrana.wordpress.com/2015/12/15/asp-net-mvc-post-a-list-or-collection-of-complex-types-with-non-sequential-indices/
and this question from StackOverflow: MVC post a list of complex objects


问:
How to compare "4A4B4C" (string shows hex value) actual string is "JKL"
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO")

How can I check this type of string in c++.. (one string shows the hexadecimal representation of another)

hexadecimal value of

```<code>J=4A, K=4B, L=4C
</code>```

答:
```<code>int hexcmp(const char *string, const char *hex_string)
{
    int len = strlen(string);
    char *hexed_string = new char[2*len+1];
    hexed_string[2*len] = '\0'; //  null-terminate
    for (int i = 0; i < len; i++)
    {
        sprintf(hexed_string, "%X", string[i]);
        hexed_string += 2;
    }
    hexed_string -= 2*len;
    printf("%s\n", hexed_string);
    int res = strcmp(hexed_string, hex_string);
    delete hexed_string;
    return res;
}

if(!hexcmp("JKLMNO", "4A4B4C4D4E4F"))
    printf("Equal\n");
else
    printf("Nonequal\n");
</code>```

Body:
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO")

How can I check this type of string in c++.. (one string shows the hexadecimal representation of another)

hexadecimal value of

J=4A, K=4B, L=4C


问:
Password hashing not working on Put request
Using bcryptjs library and got 2 issues when performing Put request:

1- On insomnia / postman, server returns hashed password, but it returns "unhashed" on client side inspect console tools.

2- I can not perform a login with new password credential.

Any visible syntax mistake on server code or quick suggestions please? Tks!

CLIENT SIDE CODE:

```<code>function DevUpdateForm() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [techs, setTechs] = useState("");

async function updateUser(e) {
        e.preventDefault()
        const dataUpdate = { name, email, password, techs}
        const response = await api.put(`/devs/${dev._id}`, dataUpdate);
              console.log(response);
        setName('');
        setEmail('');
        setPassword('');
        setTechs([]);
    }

        return (
              <div className="update-profile">
                <strong>Alterar</strong>
                <img src={dev.avatar_url} alt={dev.name}/>
                <form onSubmit={updateUser} >
                  <div className="input-block">
                    <label htmlFor="name">Nome:</label>
                    <input
                      name="name"
                      id="name"
                      type="text"
                      placeholder={"Alterar nome"}
                      value={name}
                      onChange={e => setName(e.target.value)}
                      />
                  </div>

                  <div className="input-block">
                    <label htmlFor="email">E-mail:</label>
                    <input
                      name="email"
                      id="email"
                      type="text"
                      placeholder={"Alterar email"}
                      value={email}
                      onChange={e => setEmail(e.target.value)}
                    />
                  </div>
                  <div className="input-block">
                    <label htmlFor="password">Senha:</label>
                    <input
                      name="password"
                      id="password"
                      type="password"
                      placeholder={"Digite nova senha"}
                      value={password}
                      onChange={e => setPassword(e.target.value)}
                      />
                  </div>
                  <div className="input-block">
                    <label htmlFor="techs">Techs:</label>
                    <input
                      name="techs"
                      id="techs"
                      type="text"
                      placeholder={"Alterar tecnologias"}
                      value={techs}
                      onChange={e => setTechs(e.target.value)}
                      />
                  </div>

                  <button type="submit" >Salvar</button>
                </form>
              </div>
        )
    }

    export default DevUpdateForm;
</code>```

SERVER SIDE UPDATE CONTROLLER:

```<code>    async update(req, res, next) {
    try {
        const { name, email, password, techs } = req.body;
        const { _id } = req.params;
        const techsArray = parseStringAsArray(techs);

        let dev = await Dev.findByIdAndUpdate(_id, {
                name,
                email,
                password,
                techs: techsArray
        },
        {new: true});

        dev = await Dev.findById(_id)

        dev.password = await bcrypt.hash(dev.password, 8)

        if (dev !== null) {
            res.status(200).send({
                data: dev,
                message: "Dev has been updated!"
            });
            } else {
            res.status(404).end();
            }

       } catch (error) {
        next(error)
       }
},
</code>```

ROUTE:

```<code>routes.put('/devs/:_id', DevController.allowIfLoggedin, DevController.grantAccess('updateAny', 'profile'), DevController.update);
</code>```

答:
After finding the model and set new values to user model. you have to execute .save() statement to update existing changes.

```<code>async update(req, res, next) {
 try {
    const { name, email, password, techs } = req.body;
    const { _id } = req.params;
    const techsArray = parseStringAsArray(techs);

    let dev = await Dev.findByIdAndUpdate(_id, {
            name,
            email,
            password,
            techs: techsArray
    },
    {new: true});

    dev = await Dev.findById(_id)

    dev.password = await bcrypt.hash(dev.password, 8)
    dev.save();// add this to save new password
    if (dev !== null) {
        res.status(200).send({
            data: dev,
            message: "Dev has been updated!"
        });
        } else {
        res.status(404).end();
        }

   } catch (error) {
    next(error)
   }
},
</code>```

Body:
Using bcryptjs library and got 2 issues when performing Put request:

1- On insomnia / postman, server returns hashed password, but it returns "unhashed" on client side inspect console tools.

2- I can not perform a login with new password credential.

Any visible syntax mistake on server code or quick suggestions please? Tks!

CLIENT SIDE CODE:

function DevUpdateForm() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [techs, setTechs] = useState("");

async function updateUser(e) {
        e.preventDefault()
        const dataUpdate = { name, email, password, techs}
        const response = await api.put(`/devs/${dev._id}`, dataUpdate);
              console.log(response);
        setName('');
        setEmail('');
        setPassword('');
        setTechs([]);
    }

        return (

                Alterar

                <form onSubmit={updateUser} >

                    Nome:
                    <input
                      name="name"
                      id="name"
                      type="text"
                      placeholder={"Alterar nome"}
                      value={name}
                      onChange={e => setName(e.target.value)}
                      />

                    E-mail:
                    <input
                      name="email"
                      id="email"
                      type="text"
                      placeholder={"Alterar email"}
                      value={email}
                      onChange={e => setEmail(e.target.value)}
                    />

                    Senha:
                    <input
                      name="password"
                      id="password"
                      type="password"
                      placeholder={"Digite nova senha"}
                      value={password}
                      onChange={e => setPassword(e.target.value)}
                      />

                    Techs:
                    <input
                      name="techs"
                      id="techs"
                      type="text"
                      placeholder={"Alterar tecnologias"}
                      value={techs}
                      onChange={e => setTechs(e.target.value)}
                      />

                  <button type="submit" >Salvar</button>
                </form>

        )
    }

    export default DevUpdateForm;

SERVER SIDE UPDATE CONTROLLER:

    async update(req, res, next) {
    try {
        const { name, email, password, techs } = req.body;
        const { _id } = req.params;
        const techsArray = parseStringAsArray(techs);

        let dev = await Dev.findByIdAndUpdate(_id, {
                name,
                email,
                password,
                techs: techsArray
        },
        {new: true});

        dev = await Dev.findById(_id)

        dev.password = await bcrypt.hash(dev.password, 8)

        if (dev !== null) {
            res.status(200).send({
                data: dev,
                message: "Dev has been updated!"
            });
            } else {
            res.status(404).end();
            }

       } catch (error) {
        next(error)
       }
},

ROUTE:

routes.put('/devs/:_id', DevController.allowIfLoggedin, DevController.grantAccess('updateAny', 'profile'), DevController.update);

Body:
After finding the model and set new values to user model. you have to execute .save() statement to update existing changes.

async update(req, res, next) {
 try {
    const { name, email, password, techs } = req.body;
    const { _id } = req.params;
    const techsArray = parseStringAsArray(techs);

    let dev = await Dev.findByIdAndUpdate(_id, {
            name,
            email,
            password,
            techs: techsArray
    },
    {new: true});

    dev = await Dev.findById(_id)

    dev.password = await bcrypt.hash(dev.password, 8)
    dev.save();// add this to save new password
    if (dev !== null) {
        res.status(200).send({
            data: dev,
            message: "Dev has been updated!"
        });
        } else {
        res.status(404).end();
        }

   } catch (error) {
    next(error)
   }
},


问:
Can not load some modules in deno
I just started learning deno and I have already faced "bug like" problems.

When I import oak module to my deno app, it compiles successfully; but when I load mongo or bcrypt, it crashes and shows me this error.

error: The system cannot find the path specified. (os error 3)

```<code>export { Application, Router } from "https://deno.land/x/oak/mod.ts";
export { init, mongoClient } from "https://deno.land/x/mongo/mod.ts";
</code>```

Here first line is executed correctly, but the second line throws an error.

答:
First of all, use this line

```<code>export { init, MongoClient } from "https://deno.land/x/mongo/mod.ts";
</code>```

instead of

```<code>export { init, mongoClient } from "https://deno.land/x/mongo/mod.ts";
</code>```

Then reload the cache by running this command:

```<code>deno cache --reload --unstable app.js
</code>```

Then run by using this command:

```<code>deno run -A --unstable app.js
</code>```

Title: Can not load some modules in deno

Body:
I just started learning deno and I have already faced "bug like" problems.

When I import oak module to my deno app, it compiles successfully; but when I load mongo or bcrypt, it crashes and shows me this error.

error: The system cannot find the path specified. (os error 3)

export { Application, Router } from "https://deno.land/x/oak/mod.ts";
export { init, mongoClient } from "https://deno.land/x/mongo/mod.ts";

Here first line is executed correctly, but the second line throws an error.

Body:
First of all, use this line

export { init, MongoClient } from "https://deno.land/x/mongo/mod.ts";

instead of

export { init, mongoClient } from "https://deno.land/x/mongo/mod.ts";

Then reload the cache by running this command:

deno cache --reload --unstable app.js

Then run by using this command:

deno run -A --unstable app.js


问:
Changing a flat image's color with jQuery
I have a flat white circular image (as in a seriously flat #ffffff image). Is there a way I can change it's color in the context of an HTML page (let's assume PNG, so we're working with an RGBA raster)?

My environment uses jQuery, so I'm inclined to think within the jQuery mindset, but if something else makes this possible, I'd like to hear about it as well.

I'm not well versed with the capabilities of Canvas so much, but maybe that can do something like this. With respect to browser support however, I'd really appreciate it if the solution can touch base with IE6 (yeah, I know it's dead, but bear with me on this one).

答:
Have you thought about using a canvas and drawing the circle below the image, then change it's color? Following on from the other answer and make the image transparent and then layer it about the canvas.

http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/


问:
kubernetes prestop hook doesnt work with env variables
I have a deployment template as below. but the prestop hook is never been executed at all.
the idea here is set the zookeeper node offline before the pod is terminated.

I am running kubectl rollout to restart the pods. and old pod is when it terminates the prestop is not run. could someone please check whats wrong ?

Basically how its prestop executed in case of successful stop ? I need this feature because the zookeeper is involved here and the api connects to zookeeper to send the requests.

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: abcd
  labels:
    app: abcd
spec:
  replicas: 1
  selector:
    matchLabels:
      app: abcd
  template:
    metadata:
      labels:
        app: abcd
    spec:
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
#      terminationGracePeriodSeconds: 1
      containers:
      - name: se
        image: "xxx"
        lifecycle:
          preStop:
            exec:
              command: ["zookeepercli","--servers","zk-hs", "-c", "set", "$HOSTNAME", "offline"]
        ports:
        - containerPort: 2345
      - name: pe-1
        image: "xxx"
        lifecycle:
          preStop:
            exec:
              command: ["zookeepercli","--servers","zk-hs", "-c", "set", "$HOSTNAME", "offline"]
        ports:
        - containerPort: 2313
</code>```

答:
As user2511126 mentioned in his/her comment:

the preStop hook doesnt uses env variables. I moved to bash script and works now

According to kubernetes documentation:

PreStop

This hook is called immediately before a container is terminated due to an API request or management event such as liveness probe failure, preemption, resource contention and others. A call to the preStop hook fails if the container is already in terminated or completed state. It is blocking, meaning it is synchronous, so it must complete before the call to delete the container can be sent. No parameters are passed to the handler.

A more detailed description of the termination behavior can be found in Termination of Pods.

No parameters can be passed to the handler, this includes environmental variables.

Body:
I have a deployment template as below. but the prestop hook is never been executed at all.
the idea here is set the zookeeper node offline before the pod is terminated.

I am running kubectl rollout to restart the pods. and old pod is when it terminates the prestop is not run. could someone please check whats wrong ?

Basically how its prestop executed in case of successful stop ? I need this feature because the zookeeper is involved here and the api connects to zookeeper to send the requests.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: abcd
  labels:
    app: abcd
spec:
  replicas: 1
  selector:
    matchLabels:
      app: abcd
  template:
    metadata:
      labels:
        app: abcd
    spec:
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
#      terminationGracePeriodSeconds: 1
      containers:
      - name: se
        image: "xxx"
        lifecycle:
          preStop:
            exec:
              command: ["zookeepercli","--servers","zk-hs", "-c", "set", "$HOSTNAME", "offline"]
        ports:
        - containerPort: 2345
      - name: pe-1
        image: "xxx"
        lifecycle:
          preStop:
            exec:
              command: ["zookeepercli","--servers","zk-hs", "-c", "set", "$HOSTNAME", "offline"]
        ports:
        - containerPort: 2313


问:
Getting horizontal scroll in mobile when close the menu
I am using anime.js and displaying the menu on mobile. I am getting a horizontal scroll on mobile.

I added display:none so that my menu will hide and when user click on the menu then I am adding the display block using the script but the issue is, after closing the menu I am still getting the scroll

Script adding the class

```<code> $('html').addClass('noscroll');
</code>```

and added below css

```<code> html.noscroll {
    overflow: hidden;
}
</code>```

So that scroll will hide. Then also I am getting an issue if I close the menu.

Would you help me out with this issue?

I am using the below code.

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}</code>```

Open

close

Home

About

contact

```

答:
You can set display none on function menuClose using delay 1300 and queue.

```<code>$('.menu-background').delay(1300).queue(function(next) {
      $(this).css('display', 'none');
      next();
  });
</code>```

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
  $('.menu-background').delay(1300).queue(function(next) {
      $(this).css('display', 'none');
      next();
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}</code>```

Open

close

Home

About

contact

```

Body:
I am using anime.js and displaying the menu on mobile. I am getting a horizontal scroll on mobile.

I added display:none so that my menu will hide and when user click on the menu then I am adding the display block using the script but the issue is, after closing the menu I am still getting the scroll

Script adding the class

 $('html').addClass('noscroll');

and added below css

 html.noscroll {
    overflow: hidden;
}

So that scroll will hide. Then also I am getting an issue if I close the menu.

Would you help me out with this issue?

I am using the below code.

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});

.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}

Open

close

Home

About

contact

Body:
You can set display none on function menuClose using delay 1300 and queue.

$('.menu-background').delay(1300).queue(function(next) {
      $(this).css('display', 'none');
      next();
  });

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
  $('.menu-background').delay(1300).queue(function(next) {
      $(this).css('display', 'none');
      next();
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});

.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}

<div class="menu-trigger">Open</div>

<div class="menu-background">
  <div class="menu-icon-close">close</div>
  <ul>
    <li><a href="">Home</a></li>
    <li><a href="">About</a></li>
    <li><a href="">contact</a></li>
  </ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js"></script>


问:
Creating an array of IDs and randomize their age
I have to generate 160k of IDs in a text file and have to randomize their age.
I have generated the IDs using an array but I don't know how to randomize their age into the text file.

There is also a criteria to randomize the age :

10% from 160000 IDs are 60-90 years old,

30% for 25-60

25% for 13-24

35% for 1-12

here are the code for my random ID generate :

```<code>public class Citizenid {
    public static void main(String[] args) {

         try{
             try (PrintWriter p = new PrintWriter("citizen id.txt")) {

                    int totalAgesToGenerate = 160000;
                    int ages60To90 = (int) (totalAgesToGenerate * 0.1);
                    int ages25To59 = (int) (totalAgesToGenerate * 0.3);
                    int ages13To24 = (int) (totalAgesToGenerate * 0.25);
                    int ages1To12 = (int) (totalAgesToGenerate * 0.35);

                    Random r = new Random();
                    int age;
                    int index=0;
                    int []agearray;
                    agearray = new int[160000];

                    //generating age for 60-90 age group
                    for (int i = 0; i < ages60To90; i++) {
                        age = r.nextInt(31) + 60;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 25-59 age group
                    for (int i = 0; i < ages25To59; i++) {
                        age = r.nextInt(35) + 25;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 13-24 age group
                    for (int i = 0; i < ages13To24; i++) {
                        age = r.nextInt(12) + 13;
                        agearray[index]=age;
                        index++;
                    }
                     //generating age for 1-12 age group
                    for (int i = 0; i < ages1To12; i++) {
                        age = r.nextInt(12) + 1;
                        agearray[index]=age;
                        index++;
                    }

                 int a=1;
                 int[]arrayid = new int[160000];
                 for(int i=0;i<arrayid.length;i++){
                     p.printf("%06d , %d \n",a,agearray[r.nextInt(1600001)]);
                     a++;
                 }
                 p.close();
             }
            }
        catch(Exception e)
        {

             System.out.println("No such file exist");
        }
    }
}
</code>```

I have solved the age problem but I wonder why the output is "No such file exist". It doesn't write on the textile

答:
It seems like Random class will do it for you. It has the nextInt(n) method, than generates a random number between 0 and n-1.

So if you want ages between 60 and 90 you would write something like this:

```<code>Random generator = new Random();
int age = generator.nextInt(31) + 60;
</code>```

It will generate a random integer between 0 and 30, and you just add 60 to obtain a range [60, 90].

Plus, if you have to generate ages with percentages, the only thing you have to do is make some loops.

```<code>int totalAgesToGenerate = 160000;
int ages60To90 = totalAgesToGenerate * 0.1;
int ages13To24 = totalAgesToGenerate * 0.25;
int ages25To59 = totalAgesToGenerate * 0.3;
int ages1To12 = totalAgesToGenerate - ages60to90 - ages13To14 - ages25To59;
Random generator = new Random();
int age;
int destinationIndex = 0;
for (int i = 0; i < ages60To90; i++) {
    age = generator.nextInt(31) + 60;
    ageid[destinationIndex] = age;
    destinationIndex++;
}
for (int i = 0; i < ages13To24; i++) {
    age = generator.nextInt(12) + 13;
    ageid[destinationIndex] = age;
    destinationIndex++;
}
</code>```

And so on.

The generation and saving can also be done in other ways. It's just an example.

Body:
I have to generate 160k of IDs in a text file and have to randomize their age.
I have generated the IDs using an array but I don't know how to randomize their age into the text file.

There is also a criteria to randomize the age :

10% from 160000 IDs are 60-90 years old,

30% for 25-60

25% for 13-24

35% for 1-12

here are the code for my random ID generate :

public class Citizenid {
    public static void main(String[] args) {

         try{
             try (PrintWriter p = new PrintWriter("citizen id.txt")) {

                    int totalAgesToGenerate = 160000;
                    int ages60To90 = (int) (totalAgesToGenerate * 0.1);
                    int ages25To59 = (int) (totalAgesToGenerate * 0.3);
                    int ages13To24 = (int) (totalAgesToGenerate * 0.25);
                    int ages1To12 = (int) (totalAgesToGenerate * 0.35);

                    Random r = new Random();
                    int age;
                    int index=0;
                    int []agearray;
                    agearray = new int[160000];

                    //generating age for 60-90 age group
                    for (int i = 0; i < ages60To90; i++) {
                        age = r.nextInt(31) + 60;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 25-59 age group
                    for (int i = 0; i < ages25To59; i++) {
                        age = r.nextInt(35) + 25;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 13-24 age group
                    for (int i = 0; i < ages13To24; i++) {
                        age = r.nextInt(12) + 13;
                        agearray[index]=age;
                        index++;
                    }
                     //generating age for 1-12 age group
                    for (int i = 0; i < ages1To12; i++) {
                        age = r.nextInt(12) + 1;
                        agearray[index]=age;
                        index++;
                    }

                 int a=1;
                 int[]arrayid = new int[160000];
                 for(int i=0;i<arrayid.length;i++){
                     p.printf("%06d , %d \n",a,agearray[r.nextInt(1600001)]);
                     a++;
                 }
                 p.close();
             }
            }
        catch(Exception e)
        {

             System.out.println("No such file exist");
        }
    }
}

I have solved the age problem but I wonder why the output is "No such file exist". It doesn't write on the textile

Body:
It seems like Random class will do it for you. It has the nextInt(n) method, than generates a random number between 0 and n-1.

So if you want ages between 60 and 90 you would write something like this:

Random generator = new Random();
int age = generator.nextInt(31) + 60;

It will generate a random integer between 0 and 30, and you just add 60 to obtain a range [60, 90].

Plus, if you have to generate ages with percentages, the only thing you have to do is make some loops.

int totalAgesToGenerate = 160000;
int ages60To90 = totalAgesToGenerate * 0.1;
int ages13To24 = totalAgesToGenerate * 0.25;
int ages25To59 = totalAgesToGenerate * 0.3;
int ages1To12 = totalAgesToGenerate - ages60to90 - ages13To14 - ages25To59;
Random generator = new Random();
int age;
int destinationIndex = 0;
for (int i = 0; i < ages60To90; i++) {
    age = generator.nextInt(31) + 60;
    ageid[destinationIndex] = age;
    destinationIndex++;
}
for (int i = 0; i < ages13To24; i++) {
    age = generator.nextInt(12) + 13;
    ageid[destinationIndex] = age;
    destinationIndex++;
}

And so on.

The generation and saving can also be done in other ways. It's just an example.


问:
Insert into ... values ( SELECT ... FROM ... )
I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).

Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?

Body:
IF you want to insert some data into a table without want to write column name.

INSERT INTO CUSTOMER_INFO
   (SELECT CUSTOMER_NAME,
           MOBILE_NO,
           ADDRESS
      FROM OWNER_INFO cm)

Where the tables are:

            CUSTOMER_INFO               ||            OWNER_INFO
----------------------------------------||-------------------------------------
CUSTOMER_NAME | MOBILE_NO | ADDRESS     || CUSTOMER_NAME | MOBILE_NO | ADDRESS
--------------|-----------|---------    || --------------|-----------|---------
      A       |     +1    |   DC        ||       B       |     +55   |   RR

Result:

            CUSTOMER_INFO               ||            OWNER_INFO
----------------------------------------||-------------------------------------
CUSTOMER_NAME | MOBILE_NO | ADDRESS     || CUSTOMER_NAME | MOBILE_NO | ADDRESS
--------------|-----------|---------    || --------------|-----------|---------
      A       |     +1    |   DC        ||       B       |     +55   |   RR
      B       |     +55   |   RR        ||


问:
Pathos can't pickle SwigPyObject created by GDAL module
I have a class which opens a large raster image using the GDAL module (https://pypi.org/project/GDAL/) and extracts small images from it at a number of locations, defined by a passed list of coordinate tuples. I want to process a large list of coordinates using Pathos, as in this simplified version of my code:

```<code>import gdal
import pathos.pools as pp

class MyClass:

    def __init__(self, image):
        self.image_object = gdal.Open(image)

    def get_small_image(self, coord, size=100):
        small_image = self.image_object.ReadAsArray(coord[0], coord[1], size, size)

        return small_image

    def run_multi(self, coords_in):
        pool = pp.ProcessPool(2)
        output = pool.map(self.get_small_image, coords_in)

        return output

image = r'C:\path\to\image.JP2'

class_obj = MyClass(image)
coords = [(200, 200), (400, 400), (600, 600), (800, 800)]
results = class_obj.run_multi(coords)

print(results)
</code>```

Running this gives the following error:

```<code>Traceback (most recent call last):
  File "C:/Users/lharris/PycharmProjects/road_condition_py3/error_recreate.py", line 26, in <module>
    results = class_obj.run_multi(coords)
  File "C:/Users/lharris/PycharmProjects/road_condition_py3/error_recreate.py", line 17, in run_multi
    output = pool.map(self.get_small_image, coords_in)
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\pathos\multiprocessing.py", line 137, in map
    return _pool.map(star(f), zip(*args)) # chunksize
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\pool.py", line 266, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\pool.py", line 644, in get
    raise self._value
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\pool.py", line 424, in _handle_tasks
    put(task)
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\connection.py", line 209, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\reduction.py", line 54, in dumps
    cls(buf, protocol).dump(obj)
  File "C:\Python36\lib\pickle.py", line 409, in dump
    self.save(obj)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 751, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 1377, in save_function
    obj.__dict__), obj=obj)
  File "C:\Python36\lib\pickle.py", line 610, in save_reduce
    save(args)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 751, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 1120, in save_cell
    pickler.save_reduce(_create_cell, (f,), obj=obj)
  File "C:\Python36\lib\pickle.py", line 610, in save_reduce
    save(args)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 1069, in save_instancemethod0
    pickler.save_reduce(MethodType, (obj.__func__, obj.__self__), obj=obj)
  File "C:\Python36\lib\pickle.py", line 610, in save_reduce
    save(args)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 521, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python36\lib\pickle.py", line 634, in save_reduce
    save(state)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 893, in save_module_dict
    StockPickler.save_dict(pickler, obj)
  File "C:\Python36\lib\pickle.py", line 821, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python36\lib\pickle.py", line 852, in _batch_setitems
    save(v)
  File "C:\Python36\lib\pickle.py", line 521, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python36\lib\pickle.py", line 634, in save_reduce
    save(state)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 893, in save_module_dict
    StockPickler.save_dict(pickler, obj)
  File "C:\Python36\lib\pickle.py", line 821, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python36\lib\pickle.py", line 852, in _batch_setitems
    save(v)
  File "C:\Python36\lib\pickle.py", line 496, in save
    rv = reduce(self.proto)
TypeError: can't pickle SwigPyObject objects
</code>```

Looking through that, it does look as though Pathos is using Dill and Multiprocess correctly. So is there a way of dealing with SwigPyObjects in parallel, either using Pathos or otherwise?

Something similar was asked a few weeks ago, but didn't get any answers (Python pathos error can't pickle SwigPyObject objects), and I asked a related question when I was previously unable to use Pathos (How can type 'SwigPyObject be registered using copy_reg.pickle in Python?).

I encountered this error using Python 3.6.5, in Windows 7, developing in PyCharm, using a virtual environment onto which any packages I need have been pip installed from .whl files downloaded from PyPi (I'm unable to use pip install normally on my network).

Any help anyone can give me would be great!

答:
Because get_small_image is a bound method each worker is needs a copy of class_obj. With multiprocessing this is done by passing pickled python objects. However because the object contains a member of class SwigPyObject class_obj isn't pickable and the whole thing fails.

The most straight forward fix is something like:

class MyClass:

    def __init__(self, image):
        self.image_object = None
        self.image = image

    def get_small_image(self, coord, size=100):
        if self.image_object is None:
            self.image_object = gdal.Open(self.image)

        small_image = self.image_object.ReadAsArray(coord[0], coord[1], size, size)

        return small_image

    def run_multi(self, coords_in):
        pool = pp.ProcessPool(2)
        output = pool.map(self.get_small_image, coords_in)

        return output
```

This lazy loading of the image causes the SwigPyObject to be created after the object has been pickled/unpickled by the child processes and thus avoiding the issue you are encountering.

Body:
I have a class which opens a large raster image using the GDAL module (https://pypi.org/project/GDAL/) and extracts small images from it at a number of locations, defined by a passed list of coordinate tuples. I want to process a large list of coordinates using Pathos, as in this simplified version of my code:

import gdal
import pathos.pools as pp

class MyClass:

    def __init__(self, image):
        self.image_object = gdal.Open(image)

    def get_small_image(self, coord, size=100):
        small_image = self.image_object.ReadAsArray(coord[0], coord[1], size, size)

        return small_image

    def run_multi(self, coords_in):
        pool = pp.ProcessPool(2)
        output = pool.map(self.get_small_image, coords_in)

        return output

image = r'C:\path\to\image.JP2'

class_obj = MyClass(image)
coords = [(200, 200), (400, 400), (600, 600), (800, 800)]
results = class_obj.run_multi(coords)

print(results)

Running this gives the following error:

Traceback (most recent call last):
  File "C:/Users/lharris/PycharmProjects/road_condition_py3/error_recreate.py", line 26, in <module>
    results = class_obj.run_multi(coords)
  File "C:/Users/lharris/PycharmProjects/road_condition_py3/error_recreate.py", line 17, in run_multi
    output = pool.map(self.get_small_image, coords_in)
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\pathos\multiprocessing.py", line 137, in map
    return _pool.map(star(f), zip(*args)) # chunksize
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\pool.py", line 266, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\pool.py", line 644, in get
    raise self._value
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\pool.py", line 424, in _handle_tasks
    put(task)
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\connection.py", line 209, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\multiprocess\reduction.py", line 54, in dumps
    cls(buf, protocol).dump(obj)
  File "C:\Python36\lib\pickle.py", line 409, in dump
    self.save(obj)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 751, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 1377, in save_function
    obj.__dict__), obj=obj)
  File "C:\Python36\lib\pickle.py", line 610, in save_reduce
    save(args)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 751, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 1120, in save_cell
    pickler.save_reduce(_create_cell, (f,), obj=obj)
  File "C:\Python36\lib\pickle.py", line 610, in save_reduce
    save(args)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 1069, in save_instancemethod0
    pickler.save_reduce(MethodType, (obj.__func__, obj.__self__), obj=obj)
  File "C:\Python36\lib\pickle.py", line 610, in save_reduce
    save(args)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python36\lib\pickle.py", line 736, in save_tuple
    save(element)
  File "C:\Python36\lib\pickle.py", line 521, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python36\lib\pickle.py", line 634, in save_reduce
    save(state)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 893, in save_module_dict
    StockPickler.save_dict(pickler, obj)
  File "C:\Python36\lib\pickle.py", line 821, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python36\lib\pickle.py", line 852, in _batch_setitems
    save(v)
  File "C:\Python36\lib\pickle.py", line 521, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python36\lib\pickle.py", line 634, in save_reduce
    save(state)
  File "C:\Python36\lib\pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Users\lharris\PycharmProjects\road_condition_py3\venv\lib\site-packages\dill\_dill.py", line 893, in save_module_dict
    StockPickler.save_dict(pickler, obj)
  File "C:\Python36\lib\pickle.py", line 821, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python36\lib\pickle.py", line 852, in _batch_setitems
    save(v)
  File "C:\Python36\lib\pickle.py", line 496, in save
    rv = reduce(self.proto)
TypeError: can't pickle SwigPyObject objects

Looking through that, it does look as though Pathos is using Dill and Multiprocess correctly. So is there a way of dealing with SwigPyObjects in parallel, either using Pathos or otherwise?

Something similar was asked a few weeks ago, but didn't get any answers (Python pathos error can't pickle SwigPyObject objects), and I asked a related question when I was previously unable to use Pathos (How can type 'SwigPyObject be registered using copy_reg.pickle in Python?).

I encountered this error using Python 3.6.5, in Windows 7, developing in PyCharm, using a virtual environment onto which any packages I need have been pip installed from .whl files downloaded from PyPi (I'm unable to use pip install normally on my network).

Any help anyone can give me would be great!

Body:
Because get_small_image is a bound method each worker is needs a copy of class_obj. With multiprocessing this is done by passing pickled python objects. However because the object contains a member of class SwigPyObject class_obj isn't pickable and the whole thing fails.

The most straight forward fix is something like:

class MyClass:

    def __init__(self, image):
        self.image_object = None
        self.image = image

    def get_small_image(self, coord, size=100):
        if self.image_object is None:
            self.image_object = gdal.Open(self.image)

        small_image = self.image_object.ReadAsArray(coord[0], coord[1], size, size)

        return small_image

    def run_multi(self, coords_in):
        pool = pp.ProcessPool(2)
        output = pool.map(self.get_small_image, coords_in)

        return output

This lazy loading of the image causes the SwigPyObject to be created after the object has been pickled/unpickled by the child processes and thus avoiding the issue you are encountering.


问:
Can we analyse internal pages of a website using Google LIghthouse?
As an example, lets say I have a website and after user logged in using user credentials, a summary page is loading as a dashboard which has a large set of api calls and rendering. I want to get stats for the second page (summary page). Is there a way we can get that using google lighthouse? When I click generate the report when I'm inside the summary page it still gives the stats for the initial page, I mean login page. Can anyone help with this?</p>

答: You would need to use lighthouse as a Node module or via the cli as described in the README. I typically use Puppeteer with lighthouse for this use case, similar to the auth recipe example. </p>


问:
automatically start typing in tkinter Entry
I'm trying to make a input screen with Tkinter that will when i type automatically receive my input without me having to click it first. would this be possible?
I wasn't able to find a tutorial or text document online to do this, and hope someone can help me with this problem! I'm on Windows 10 (bootcamped on a mac) with Python 3.8.3 64-bit.</p>

答:
The concept you are looking for is called "focus". When you type, the widget with the focus will receive the keypress events. So, to let you immediately type into an entry widget, force the UI to set the focus to that widget by using focus_set:

```<code>the_entry = Entry(root, ...)
the_entry.focus_set()
</code>```

When the window as a whole is focused (ie: brought to the front), this will cause the keyboard focus to be set to the entry widget.

Body:
The concept you are looking for is called "focus". When you type, the widget with the focus will receive the keypress events. So, to let you immediately type into an entry widget, force the UI to set the focus to that widget by using focus_set:

the_entry = Entry(root, ...)
the_entry.focus_set()

When the window as a whole is focused (ie: brought to the front), this will cause the keyboard focus to be set to the entry widget.


问:
Error in accessing authserver from resource server with auth server as eureka client
Hi I have a implemented oauth2 service in springboot. Auth-server and resource servers are enabled with eureka client they have successfully registered to eureka server as well. URI for auth-server in resource server is configured this way

```<code>security:
  oauth2:
    resource:
      token-info-uri: http://auth-server/oauth/check_token
</code>```

Now auth-server in the above URI is the app name of authserver. I am expecting resource server should contact auth server using token-info-uri after it gets url resolved from eureka server. But with this setup I am getting an error nested exception is java.net.UnknownHostException: auth-server

I modified my configuration to this

```<code>security:
  oauth2:
    resource:
      prefer-token-info: false
      service-id: auth-server
      token-info-uri: http://${security.oauth2.resource.service-id}/oauth/check_token
      loadBalanced: true
</code>```

but I am getting response

```<code>{
    "error": "invalid_token",
    "error_description": "e2f95093-085c-4b59-90a5-c89fb5d1eccb"
}
</code>```

When I debug I have this log

```<code>asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.048  INFO 1 --- [nio-6001-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 21 ms
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.086 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : Getting user info from: null
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.109 DEBUG 1 --- [nio-6001-exec-2] org.springframework.web.HttpLogging      : HTTP GET
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.117 DEBUG 1 --- [nio-6001-exec-2] org.springframework.web.HttpLogging      : Accept=[application/json, application/*+json]
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.119  WARN 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class java.lang.IllegalStateException, Request URI does not contain a valid hostname:
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.120 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : userinfo returned error: Could not fetch user details
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.127 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.audit.listener.AuditListener     : AuditEvent [timestamp=2019-11-16T17:52:08.125Z, principal=access-token, type=AUTHENTICATION_FAILURE, data={type=org.springframework.security.authentication.BadCredentialsException, message=e2f95093-085c-4b59-90a5-c89fb5d1eccb}]
</code>```

Basically URI is picked up is what I see

答:
In the error log presented by Darshu, there is the following message:" asset-mgmt-v1.1_1 | 2019-11-16 17:52:08.120 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices : userinfo returned error: Could not fetch user details".

The prefer-token-info must be set true to determine that token-info-uri is preferred over user-info-uri.

```<code>security:
      oauth2:
           resource:
                  prefer-token-info: true
</code>```

See more in https://docs.spring.io/spring-security-oauth2-boot/docs/2.0.0.RC2/reference/htmlsingle/#boot-features-security-oauth2-resource-server

Body:
Hi I have a implemented oauth2 service in springboot. Auth-server and resource servers are enabled with eureka client they have successfully registered to eureka server as well. URI for auth-server in resource server is configured this way

security:
  oauth2:
    resource:
      token-info-uri: http://auth-server/oauth/check_token

Now auth-server in the above URI is the app name of authserver. I am expecting resource server should contact auth server using token-info-uri after it gets url resolved from eureka server. But with this setup I am getting an error nested exception is java.net.UnknownHostException: auth-server

I modified my configuration to this

security:
  oauth2:
    resource:
      prefer-token-info: false
      service-id: auth-server
      token-info-uri: http://${security.oauth2.resource.service-id}/oauth/check_token
      loadBalanced: true

but I am getting response

{
    "error": "invalid_token",
    "error_description": "e2f95093-085c-4b59-90a5-c89fb5d1eccb"
}

When I debug I have this log

asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.048  INFO 1 --- [nio-6001-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 21 ms
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.086 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : Getting user info from: null
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.109 DEBUG 1 --- [nio-6001-exec-2] org.springframework.web.HttpLogging      : HTTP GET
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.117 DEBUG 1 --- [nio-6001-exec-2] org.springframework.web.HttpLogging      : Accept=[application/json, application/*+json]
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.119  WARN 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class java.lang.IllegalStateException, Request URI does not contain a valid hostname:
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.120 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : userinfo returned error: Could not fetch user details
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.127 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.audit.listener.AuditListener     : AuditEvent [timestamp=2019-11-16T17:52:08.125Z, principal=access-token, type=AUTHENTICATION_FAILURE, data={type=org.springframework.security.authentication.BadCredentialsException, message=e2f95093-085c-4b59-90a5-c89fb5d1eccb}]

Basically URI is picked up is what I see

Body:
In the error log presented by Darshu, there is the following message:" asset-mgmt-v1.1_1 | 2019-11-16 17:52:08.120 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices : userinfo returned error: Could not fetch user details".

The prefer-token-info must be set true to determine that token-info-uri is preferred over user-info-uri.

security:
      oauth2:
           resource:
                  prefer-token-info: true

See more in https://docs.spring.io/spring-security-oauth2-boot/docs/2.0.0.RC2/reference/htmlsingle/#boot-features-security-oauth2-resource-server


问:
Plot based on group
I have dataset with total of 500 rows: 250 pop, 250 heavy-metal. How can i produce this plot in R?

My actual dataset is not seperated like the example i give though. Should i just seperate it?

What i have done so far

```<code>ggplot(data = playlist, aes(x = genre, y = danceability)) +
  geom_jitter(aes(col = genre))
</code>```

答:
The problem you're having is that you've mapped x = genre. Thus, genre gets converted to a factor and then plotted at either 1 or 2.

Instead, what you want to do is have the data plotted at a random point on the x-axis. A simple way to do this is to randomly sample 1:nrow(playlist) like this:

```<code>ggplot(data = playlist, aes(x = sample(1:nrow(playlist),nrow(playlist)),
                            color = genre, y = danceability)) +
  geom_point(aes(col = genre)) + labs(x = "data")
</code>```

Note that you no longer need geom_jitter.

Data:

```<code>playlist <- structure(list(danceability = c(0.683, 0.768, 0.693, 0.765, 0.506,
0.809, 0.628, 0.556, 0.72, 0.706, 0.414, 0.448, 0.687, 0.747,
0.532, 0.483, 0.491, 0.224, 0.666, 0.416, 0.44, 0.362, 0.28,
0.42, 0.115, 0.35, 0.519, 0.538, 0.507, 0.261), genre = c("pop",
"pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop",
"pop", "pop", "pop", "pop", "pop", "heavy-metal", "heavy-metal",
"heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal",
"heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal",
"heavy-metal", "heavy-metal", "heavy-metal")), row.names = c(NA,
-30L), class = "data.frame")
</code>```

Note: This data was derived by optical character recognition from your screen shot, please excuse any errors.

Title: Plot based on group

Body:
I have dataset with total of 500 rows: 250 pop, 250 heavy-metal. How can i produce this plot in R?

My actual dataset is not seperated like the example i give though. Should i just seperate it?

What i have done so far

ggplot(data = playlist, aes(x = genre, y = danceability)) +
  geom_jitter(aes(col = genre))

Body:
The problem you're having is that you've mapped x = genre. Thus, genre gets converted to a factor and then plotted at either 1 or 2.

Instead, what you want to do is have the data plotted at a random point on the x-axis. A simple way to do this is to randomly sample 1:nrow(playlist) like this:

ggplot(data = playlist, aes(x = sample(1:nrow(playlist),nrow(playlist)),
                            color = genre, y = danceability)) +
  geom_point(aes(col = genre)) + labs(x = "data")

Note that you no longer need geom_jitter.

Data:

playlist <- structure(list(danceability = c(0.683, 0.768, 0.693, 0.765, 0.506,
0.809, 0.628, 0.556, 0.72, 0.706, 0.414, 0.448, 0.687, 0.747,
0.532, 0.483, 0.491, 0.224, 0.666, 0.416, 0.44, 0.362, 0.28,
0.42, 0.115, 0.35, 0.519, 0.538, 0.507, 0.261), genre = c("pop",
"pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop",
"pop", "pop", "pop", "pop", "pop", "heavy-metal", "heavy-metal",
"heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal",
"heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal",
"heavy-metal", "heavy-metal", "heavy-metal")), row.names = c(NA,
-30L), class = "data.frame")

Note: This data was derived by optical character recognition from your screen shot, please excuse any errors.


问:
How to remove mapped network drive when created with a random letter
I am creating a mapped network drive with a random letter like this:

```<code> $drive = Get-ChildItem function:[f-z]: -n | Where { !(Test-Path $_) } | select -First 1
 $PsDrive = New-PSDrive -Name ($drive)[0] -PSProvider "FileSystem" -Root $somePath
</code>```

This code works fine. I have a problem when want to remove the newly created mapped drive at the end of my script. How I do it:

```<code>$someEnv = Remove-PSDrive -Name $drive
</code>```

The problem here is that $drive adds the colon after the name ':'. For example if $drive is called M, it will be "M:" and Remove-PsDrive fails.

Probably it will be removed automatically when the session is over, but I want to remove it explicitly.

Do you guys have an idea how I can remove this drive?

Thanks

答:
here is another, somewhat different way to do it that uses just powershell. [grin]

what it does ...

creates a list of possible drive letters

in this case, it is just F thru Z.

== uses 'F'[0] to convert the letter string to a character

== uses the range operator to coerce the chars to ascii code numbers

== generates a range from those code numbers

== coerces the code numbers back to characters & stuffs them into an array

in PoSh7, you can make that array with 'F'..'Z'. [grin]

grabs the in-use drive letters

filters the candidate letters against the in-use letters

grabs the 1st remaining letter

sets a target root

in this case it is the temp dir.

creates a new PSDrive with that letter

shows the drive letter in use by that new PSDrive

gets a dir list of the 1st three items in that PSDrive

removes the PSDrive

shows the current filesystem PSDrives

the code ...

```<code>$CandidateDriveLetters = [char[]]('F'[0]..'Z'[0])
$InUseDriveLetters = (Get-PSDrive -PSProvider FileSystem).Name
$1stAvailableDL = ($CandidateDriveLetters |
    Where-Object {
        $_ -notin $InUseDriveLetters
        })[0]

$TargetDriveRoot = $env:TEMP
$NewDrive = New-PSDrive -Name $1stAvailableDL -PSProvider FileSystem -Root $TargetDriveRoot

$NewDrive.Name
'=' * 30
Get-ChildItem -Path ('{0}:' -f $NewDrive.Name) |
    Select-Object -First 3

'=' * 30
Remove-PSDrive -Name $NewDrive.Name

(Get-PSDrive -PSProvider FileSystem).Name
</code>```

output ...

```<code>H
==============================

    Directory: C:\Temp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2020-04-21   6:39 PM                2ccdytd4
d-----       2020-04-21   6:39 PM                30u23uyw
d-----       2020-04-21   6:39 PM                55zoq3fj
==============================
C
D
E
F
G
R
S
Z
</code>```

Body:
I am creating a mapped network drive with a random letter like this:

 $drive = Get-ChildItem function:[f-z]: -n | Where { !(Test-Path $_) } | select -First 1
 $PsDrive = New-PSDrive -Name ($drive)[0] -PSProvider "FileSystem" -Root $somePath

This code works fine. I have a problem when want to remove the newly created mapped drive at the end of my script. How I do it:

$someEnv = Remove-PSDrive -Name $drive

The problem here is that $drive adds the colon after the name ':'. For example if $drive is called M, it will be "M:" and Remove-PsDrive fails.

Probably it will be removed automatically when the session is over, but I want to remove it explicitly.

Do you guys have an idea how I can remove this drive?

Thanks

Body:
here is another, somewhat different way to do it that uses just powershell. [grin]

what it does ...

creates a list of possible drive letters

in this case, it is just F thru Z.

== uses 'F'[0] to convert the letter string to a character

== uses the range operator to coerce the chars to ascii code numbers

== generates a range from those code numbers

== coerces the code numbers back to characters & stuffs them into an array

in PoSh7, you can make that array with 'F'..'Z'. [grin]

grabs the in-use drive letters

filters the candidate letters against the in-use letters

grabs the 1st remaining letter

sets a target root

in this case it is the temp dir.

creates a new PSDrive with that letter

shows the drive letter in use by that new PSDrive

gets a dir list of the 1st three items in that PSDrive

removes the PSDrive

shows the current filesystem PSDrives

the code ...

$CandidateDriveLetters = [char[]]('F'[0]..'Z'[0])
$InUseDriveLetters = (Get-PSDrive -PSProvider FileSystem).Name
$1stAvailableDL = ($CandidateDriveLetters |
    Where-Object {
        $_ -notin $InUseDriveLetters
        })[0]

$TargetDriveRoot = $env:TEMP
$NewDrive = New-PSDrive -Name $1stAvailableDL -PSProvider FileSystem -Root $TargetDriveRoot

$NewDrive.Name
'=' * 30
Get-ChildItem -Path ('{0}:' -f $NewDrive.Name) |
    Select-Object -First 3

'=' * 30
Remove-PSDrive -Name $NewDrive.Name

(Get-PSDrive -PSProvider FileSystem).Name

output ...

H
==============================

    Directory: C:\Temp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2020-04-21   6:39 PM                2ccdytd4
d-----       2020-04-21   6:39 PM                30u23uyw
d-----       2020-04-21   6:39 PM                55zoq3fj
==============================
C
D
E
F
G
R
S
Z


问:
Migration Cordova to Capacitor - error: package android.support.v4.content does not exist
I'm trying to migrate my ionic app from cordova to capacitor.

But I'm getting an error in Android build.

```<code>android\capacitor-cordova-android-plugins\src\main\java\nl\xservices\plugins\FileProvider.java:4: error: package android.support.v4.content does not exist
public class FileProvider extends android.support.v4.content.FileProvider {
</code>```

Does anyone knows how to solve this problem?

答:
I was having the same issue, and I fixed it in these foollowing steps:

Go to the FileProvider file where the issue is happening, you can click the path that Android Studio gives you.

Instead of "public class FileProvider extends android.support.v4.content.FileProvider" replace it with "public class FileProvider extends androidx.core.content.FileProvider".

This should fix the issue, hope this helps buddy.

PS. This error does not appear when starting the a project with Capacitor, hopefully they fix these kind of errors with Capacitor 2.0

Body:
I'm trying to migrate my ionic app from cordova to capacitor.

But I'm getting an error in Android build.

android\capacitor-cordova-android-plugins\src\main\java\nl\xservices\plugins\FileProvider.java:4: error: package android.support.v4.content does not exist
public class FileProvider extends android.support.v4.content.FileProvider {

Does anyone knows how to solve this problem?