问:
Quick method of shuffling a long array python
Hi there Im looking to shuffle an array of 15 integers.  I can do this in a long winded manner i'm sure however I was wondering if there is a simple function to do this? i have tried importing random and using random.shuffle however it tells me it can only take a maximum of 3 positional arguments. Is there a function that can do this for a long array? Im struggling to find a way so far</p>

```<code> import random

a = random.shuffle(9,
6,
7,
5,
6,
8,
8,
9,
8,
6,
6,
7,
7,
7)

print(a)
</code>```

答:
You need to pass in array to the shuffle() method, something like this:-

```<code>import random
arr = [9,6,7,5,6,8,8,9,8,6,6,7,7,7]
random.shuffle(arr)
print(arr)
</code>```

Hope this helps!

Body:
Hi there Im looking to shuffle an array of 15 integers.  I can do this in a long winded manner i'm sure however I was wondering if there is a simple function to do this? i have tried importing random and using random.shuffle however it tells me it can only take a maximum of 3 positional arguments. Is there a function that can do this for a long array? Im struggling to find a way so far

 import random

a = random.shuffle(9,
6,
7,
5,
6,
8,
8,
9,
8,
6,
6,
7,
7,
7)

print(a)

Body:
You need to pass in array to the shuffle() method, something like this:-

import random
arr = [9,6,7,5,6,8,8,9,8,6,6,7,7,7]
random.shuffle(arr)
print(arr)

Hope this helps!


来源: stackexchange

问:
Select a JQuery UI Tab after client validation
I have Tab1, Tab2 and Tab3...
All tabs have inputs that are validated ...

My save method validates the required inputs:

```<code>var validator = $("form").validate(); // obtain validator
var anyError = false;
$('#tabs').find(":input").each(function ()
{
    if (!validator.element(this)) { // validate every input element inside this step
        anyError = true;
    }
});
if (anyError)
    return false; // exit if any error found

//save ...
</code>```

Its working fine... But I´d like to select the first Tab that has an "error"... How can I do that?

Thanks

答:
Untested but could you not do this:

```<code>$('#tabs').find(":input").each(function ()
{
    if (!validator.element(this)) { // validate every input element inside this step
        anyError = true;
        // trigger click on the tab that is linked to $(this).parents('yourtabcontainername') here
        return false; // ends each
    }
});
if (anyError)
    return false; // exit if any error found

//save ...
</code>```

Alternatively if you want all inputs to be checked regardless you could do something like this:

```<code>var validator = $("form").validate(); // obtain validator
var anyError = false;
var firstError;
$('#tabs').find(":input").each(function ()
{
    if (!validator.element(this)) { // validate every input element inside this step
        anyError = true;
        if(firstError === undefined){
            //set firstError to reference the tab that is linked to $(this).parents('yourtabcontainername')
        }
    }
});
if (anyError) {
        //trigger click on firstError
        return false; // exit if any error found
    }

//save ...
</code>```

are either of those about what you are looking for?

ContentLicense: CC BY-SA 3.0

Body:
I have Tab1, Tab2 and Tab3...
All tabs have inputs that are validated ...

My save method validates the required inputs:

var validator = $("form").validate(); // obtain validator
var anyError = false;
$('#tabs').find(":input").each(function ()
{
    if (!validator.element(this)) { // validate every input element inside this step
        anyError = true;
    }
});
if (anyError)
    return false; // exit if any error found

//save ...

Its working fine... But I´d like to select the first Tab that has an "error"... How can I do that?

Thanks

Body:
Untested but could you not do this:

$('#tabs').find(":input").each(function ()
{
    if (!validator.element(this)) { // validate every input element inside this step
        anyError = true;
        // trigger click on the tab that is linked to $(this).parents('yourtabcontainername') here
        return false; // ends each
    }
});
if (anyError)
    return false; // exit if any error found

//save ...

Alternatively if you want all inputs to be checked regardless you could do something like this:

var validator = $("form").validate(); // obtain validator
var anyError = false;
var firstError;
$('#tabs').find(":input").each(function ()
{
    if (!validator.element(this)) { // validate every input element inside this step
        anyError = true;
        if(firstError === undefined){
            //set firstError to reference the tab that is linked to $(this).parents('yourtabcontainername')
        }
    }
});
if (anyError) {
        //trigger click on firstError
        return false; // exit if any error found
    }

//save ...

are either of those about what you are looking for?


问:
How to use su command over adb shell?
I need to make a script that executes a lots of thing on Android device, my device is rooted, when I enter on the shell, I can give the command su, and it works but I need pass this command like:

```<code>adb shell "
su;
mv /sdcard/Download/app_test /data/local;
cd /data/local;
./app_test;
exit;
exit;
"
</code>```

when I put some commands before the su it works, according what I read su creates a new shell that return immediately, but I need give commands on the su shell, how can I do that?

答:
for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.</p>

```<code>adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""
</code>```

Title: How to use su command over adb shell?

Body:
I need to make a script that executes a lots of thing on Android device, my device is rooted, when I enter on the shell, I can give the command su, and it works but I need pass this command like:

adb shell "
su;
mv /sdcard/Download/app_test /data/local;
cd /data/local;
./app_test;
exit;
exit;
"

when I put some commands before the su it works, according what I read su creates a new shell that return immediately, but I need give commands on the su shell, how can I do that?

Body:
for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

ContentLicense: CC BY-SA 4.0


问:
What is Google expecting from a /token enpoint?
I'm developing a Google Actions Application and a Webhook to make this app comunicate with a server with client credentials. When implementing the OAuth & Google Sign-in flows with my server I can't seem to find what is the response the Google side is waiting from /token endpoint, it is supposed to return the access token that then will be used in every request made from the action (..if I got that part correctly..). I currently returning a ContentResult with the appropriate StatusCode (i think) and a json body with the access token it is supposed to return. Something like this:

```<code>ContentResult result = null;
data.Add(@"token_type", @"Bearer");
data.Add(@"access_token", FAKE_ACCESS_TOKEN);
data.Add(@"refresh_token", FAKE_REFRESH_TOKEN);
data.Add(@"expires_in", FAKE_SECONDS_TO_EXPIRATION);

jsonResponse = data.ToString();

result = new ContentResult
{
     Content = jsonResponse,
     ContentType = "application/json"
     StatusCode = (int?)HttpStatusCode.OK
};

return result;
</code>```

The Documentation on this part seems to be vague. Maybe Someone could help me figure it out ? Thanks in advance

答:
Assuming you are using the code flow, then your /token endpoint has two things it needs to handle:

Exchanging an auth code for the access token and refresh token

Exchanging the refresh token for a new access token

The responses for each are similar, but slightly different (most notably, the second one shouldn't return a new refresh token).

For an auth code exchange, the parameter grant_type that is sent to you will have a value of "authorization_code", so you'll return JSON looking something like this:

```<code>{
"token_type": "Bearer",
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"expires_in": SECONDS_TO_EXPIRATION
}
</code>```

for a refresh token exchange, the grant_type parameter will have a value of "refresh_token", and the response will roughly be the same, but without a refresh token:

```<code>{
"token_type": "Bearer",
"access_token": "ACCESS_TOKEN",
"expires_in": SECONDS_TO_EXPIRATION
}
</code>```

Body:
I'm developing a Google Actions Application and a Webhook to make this app comunicate with a server with client credentials. When implementing the OAuth & Google Sign-in flows with my server I can't seem to find what is the response the Google side is waiting from /token endpoint, it is supposed to return the access token that then will be used in every request made from the action (..if I got that part correctly..). I currently returning a ContentResult with the appropriate StatusCode (i think) and a json body with the access token it is supposed to return. Something like this:

ContentResult result = null;
data.Add(@"token_type", @"Bearer");
data.Add(@"access_token", FAKE_ACCESS_TOKEN);
data.Add(@"refresh_token", FAKE_REFRESH_TOKEN);
data.Add(@"expires_in", FAKE_SECONDS_TO_EXPIRATION);

jsonResponse = data.ToString();

result = new ContentResult
{
     Content = jsonResponse,
     ContentType = "application/json"
     StatusCode = (int?)HttpStatusCode.OK
};

return result;

The Documentation on this part seems to be vague. Maybe Someone could help me figure it out ? Thanks in advance

Body:
Assuming you are using the code flow, then your /token endpoint has two things it needs to handle:

Exchanging an auth code for the access token and refresh token

Exchanging the refresh token for a new access token

The responses for each are similar, but slightly different (most notably, the second one shouldn't return a new refresh token).

For an auth code exchange, the parameter grant_type that is sent to you will have a value of "authorization_code", so you'll return JSON looking something like this:

{
"token_type": "Bearer",
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"expires_in": SECONDS_TO_EXPIRATION
}

for a refresh token exchange, the grant_type parameter will have a value of "refresh_token", and the response will roughly be the same, but without a refresh token:

{
"token_type": "Bearer",
"access_token": "ACCESS_TOKEN",
"expires_in": SECONDS_TO_EXPIRATION
}


问:
Protractor-net and Azure AD
I'm new to Protractor and am wanting to write C# tests that run against an Angular 8 application.  The problem is, the application uses Azure AD for authentication and I don't know the correct approach to authenticate automatically when running the test.  If I navigate to the application URL it redirects to the Microsoft login page for authentication but I can't seem to access this. </p>

答:
You can use the libraries given by Microsoft to implement applications for authenticating to Azure.MSAL is one of the libreary whiich is best to use. If you want to use MSAL to acquire a token, you need to:

Register an application in Azure AD.

Add target API, and grant consent to select permissions.

Generate a secret key.

Then you can get a token as Acquire a token and call Microsoft Graph API.

However, I think what you really want is to integrate AAD. You can easily enable AAD authentication for your .NET web application.  It uses OWIN middleware.

Title: Protractor-net and Azure AD


问:
Invalid argument: Input to reshape is a tensor with 64 values, but the requested shape has 4
I am working on face detection task and I am new to computer vision. but i am getting some issue I have tried with some change but not work for me.

```<code>import numpy as np
data = np.load("images.npy",allow_pickle=True)

IMAGE_HEIGHT=224
IMAGE_WIDTH=224
masks = np.zeros((int(data.shape[0]), IMAGE_HEIGHT, IMAGE_WIDTH))
X_train = np.zeros((int(data.shape[0]), IMAGE_HEIGHT, IMAGE_WIDTH, 3))
for index in range(data.shape[0]):
   img = data[index][0]
   img = cv2.resize(img, dsize=(IMAGE_HEIGHT, IMAGE_WIDTH), interpolation=cv2.INTER_CUBIC)
   try:
     img = img[:, :, :3]
   except:
     continue
   X_train[index] = preprocess_input(np.array(img, dtype=np.float32))
   for i in data[index][1]:
      x1 = int(i["points"][0]['x'] * IMAGE_WIDTH)
      x2 = int(i["points"][1]['x'] * IMAGE_WIDTH)
      y1 = int(i["points"][0]['y'] * IMAGE_HEIGHT)
      y2 = int(i["points"][1]['y'] * IMAGE_HEIGHT)
      masks[index][y1:y2, x1:x2] = 1

      model.fit(X_train,masks, epochs=30,batch_size = 1, verbose=1, callbacks=[checkpoint, reduce_lr, stop])
</code>```

I have read image data from image.npy

after executing above code and getting below error:

```<code>  validArgumentError: 2 root error(s) found.
     (0) Invalid argument: Input to reshape is a tensor with 64 values, but the requested shape has 4
     [[{{node reshape/Reshape}}]]
     [[loss/mul/_1213]]
     (1) Invalid argument: Input to reshape is a tensor with 64 values, but the requested shape has 4
     [[{{node reshape/Reshape}}]]
     0 successful operations.
     0 derived errors ignored.
</code>```

data format is as below

```<code>    array([array([[[207, 216, 227, 255],
    [206, 216, 227, 255],
    [207, 216, 227, 255],
    ...,
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255]],

   [[207, 216, 227, 255],
    [207, 216, 227, 255],
    [207, 216, 227, 255],
    ...,
    [ 35,  32,  33, 255],
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255]],

   [[207, 216, 227, 255],
    [207, 216, 227, 255],
    [207, 215, 227, 255],
    ...,
    [ 35,  33,  33, 255],
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255]],

   ...,

   [[ 31,  21,  17, 255],
    [ 31,  22,  18, 255],
    [ 31,  22,  18, 255],
    ...,
    [  0,   1,   4, 255],
    [  0,   1,   4, 255],
    [  0,   1,   4, 255]],

   [[ 31,  22,  18, 255],
    [ 31,  22,  18, 255],
    [ 31,  22,  18, 255],
    ...,
    [  0,   1,   4, 255],
    [  0,   1,   4, 255],
    [  0,   1,   4, 255]],

   [[ 31,  22,  18, 255],
    [ 30,  22,  17, 255],
    [ 31,  22,  18, 255],
    ...,
    [  0,   1,   4, 255],
    [  0,   1,   4, 255],
    [  0,   1,   4, 255]]], dtype=uint8),

     list([{'label': ['Face'], 'notes': '', 'points': [{'x':
     0.7053087757313109, 'y': 0.23260437375745527}, {'x':
     0.7692307692307693, 'y': 0.36182902584493043}], 'imageWidth': 1280,
     'imageHeight': 697}])],
     dtype=object)
</code>```

I am just confused with what will be x and y and how to resolve this issue

答:
You might be using tf.reshape in some function in your code.

The tf.reshape does not change the order of or the total number of elements in the tensor. The error as states, you are trying to reduce total number of elements from 64 to 4.

In below example, I have recreated your scenario where I have the given the shape argument as 2 for tf.reshape which doesn't accommodate all the elements of original tensor, thus throws the error -

Code -

```<code>%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, 2)
</code>```

Output -

```<code>---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-3-0ff1d701ff22> in <module>()
      3 t1 = tf.Variable([1,2,2,4,5,6])
      4
----> 5 t2 = tf.reshape(t1, 2)

3 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Input to reshape is a tensor with 6 values, but the requested shape has 2 [Op:Reshape]
</code>```

tf.reshape should be in such a way that the arrangement of elements can change but total number of elements must remain the same. So the fix would be to change the shape to [2,3] -

Code -

```<code>%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, [2,3])
print(t2)
</code>```

Output -

```<code>tf.Tensor(
[[1 2 2]
 [4 5 6]], shape=(2, 3), dtype=int32)
</code>```

Hope this answers your question. Happy Learning.

Body:
I am working on face detection task and I am new to computer vision. but i am getting some issue I have tried with some change but not work for me.

import numpy as np
data = np.load("images.npy",allow_pickle=True)

IMAGE_HEIGHT=224
IMAGE_WIDTH=224
masks = np.zeros((int(data.shape[0]), IMAGE_HEIGHT, IMAGE_WIDTH))
X_train = np.zeros((int(data.shape[0]), IMAGE_HEIGHT, IMAGE_WIDTH, 3))
for index in range(data.shape[0]):
   img = data[index][0]
   img = cv2.resize(img, dsize=(IMAGE_HEIGHT, IMAGE_WIDTH), interpolation=cv2.INTER_CUBIC)
   try:
     img = img[:, :, :3]
   except:
     continue
   X_train[index] = preprocess_input(np.array(img, dtype=np.float32))
   for i in data[index][1]:
      x1 = int(i["points"][0]['x'] * IMAGE_WIDTH)
      x2 = int(i["points"][1]['x'] * IMAGE_WIDTH)
      y1 = int(i["points"][0]['y'] * IMAGE_HEIGHT)
      y2 = int(i["points"][1]['y'] * IMAGE_HEIGHT)
      masks[index][y1:y2, x1:x2] = 1

      model.fit(X_train,masks, epochs=30,batch_size = 1, verbose=1, callbacks=[checkpoint, reduce_lr, stop])

I have read image data from image.npy

after executing above code and getting below error:

  validArgumentError: 2 root error(s) found.
     (0) Invalid argument: Input to reshape is a tensor with 64 values, but the requested shape has 4
     [[{{node reshape/Reshape}}]]
     [[loss/mul/_1213]]
     (1) Invalid argument: Input to reshape is a tensor with 64 values, but the requested shape has 4
     [[{{node reshape/Reshape}}]]
     0 successful operations.
     0 derived errors ignored.

data format is as below

    array([array([[[207, 216, 227, 255],
    [206, 216, 227, 255],
    [207, 216, 227, 255],
    ...,
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255]],

   [[207, 216, 227, 255],
    [207, 216, 227, 255],
    [207, 216, 227, 255],
    ...,
    [ 35,  32,  33, 255],
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255]],

   [[207, 216, 227, 255],
    [207, 216, 227, 255],
    [207, 215, 227, 255],
    ...,
    [ 35,  33,  33, 255],
    [ 35,  33,  34, 255],
    [ 35,  33,  34, 255]],

   ...,

   [[ 31,  21,  17, 255],
    [ 31,  22,  18, 255],
    [ 31,  22,  18, 255],
    ...,
    [  0,   1,   4, 255],
    [  0,   1,   4, 255],
    [  0,   1,   4, 255]],

   [[ 31,  22,  18, 255],
    [ 31,  22,  18, 255],
    [ 31,  22,  18, 255],
    ...,
    [  0,   1,   4, 255],
    [  0,   1,   4, 255],
    [  0,   1,   4, 255]],

   [[ 31,  22,  18, 255],
    [ 30,  22,  17, 255],
    [ 31,  22,  18, 255],
    ...,
    [  0,   1,   4, 255],
    [  0,   1,   4, 255],
    [  0,   1,   4, 255]]], dtype=uint8),

     list([{'label': ['Face'], 'notes': '', 'points': [{'x':
     0.7053087757313109, 'y': 0.23260437375745527}, {'x':
     0.7692307692307693, 'y': 0.36182902584493043}], 'imageWidth': 1280,
     'imageHeight': 697}])],
     dtype=object)

I am just confused with what will be x and y and how to resolve this issue

Body:
You might be using tf.reshape in some function in your code.

The tf.reshape does not change the order of or the total number of elements in the tensor. The error as states, you are trying to reduce total number of elements from 64 to 4.

In below example, I have recreated your scenario where I have the given the shape argument as 2 for tf.reshape which doesn't accommodate all the elements of original tensor, thus throws the error -

Code -

%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, 2)

Output -

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-3-0ff1d701ff22> in <module>()
      3 t1 = tf.Variable([1,2,2,4,5,6])
      4
----> 5 t2 = tf.reshape(t1, 2)

3 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Input to reshape is a tensor with 6 values, but the requested shape has 2 [Op:Reshape]

tf.reshape should be in such a way that the arrangement of elements can change but total number of elements must remain the same. So the fix would be to change the shape to [2,3] -

Code -

%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, [2,3])
print(t2)

Output -

tf.Tensor(
[[1 2 2]
 [4 5 6]], shape=(2, 3), dtype=int32)

Hope this answers your question. Happy Learning.


问:
Count the number of appearances of char given a ID
I have to perform a query where I can count the number of distinct codes per Id.

```<code>   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C
</code>```

The output should be something like:

```<code>   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0
</code>```

Can you give me some advise on this?

答:
This answers the original version of the question.

You are looking for count(distinct):

```<code>select id, count(distinct code)
from t
group by id;
</code>```

Body:
I have to perform a query where I can count the number of distinct codes per Id.

   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C

The output should be something like:

   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0

Can you give me some advise on this?

Body:
This answers the original version of the question.

You are looking for count(distinct):

select id, count(distinct code)
from t
group by id;


问:
how to insert Date into TempTable inside Cursor?
I have a cursor (just for practice and test cursor) and I want to Insert My Result into TempTable I tried this But I got this error

An INTO clause is not allowed in a cursor declaration.

My code:

```<code>DECLARE cursor_brand CURSOR FOR
     SELECT firstname, LastName
     INTO #tempTable_2
     FROM Person.Person
     JOIN Sales.SalesOrderDetail ON SalesOrderDetail.SalesOrderDetailID = Person.BusinessEntityID
     JOIN Sales.SalesOrderHeader ON SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID
     WHERE OrderDate LIKE '%2011%' AND LineTotal > 10000
     ORDER BY LastName

OPEN cursor_brand;

FETCH NEXT FROM cursor_brand

WHILE @@FETCH_STATUS = 0
    FETCH NEXT FROM cursor_brand
    CLOSE cursor_brand
    DEALLOCATE cursor_brand;
</code>```

答:
I really don't see why you would need a cursor here. To insert into the temp table, using the select ... into ...  syntax is just enough, so I think your whole code should be simplified as:

```<code>select p.firstname, p.LastName
into #tempTable_2
from Person.Person p
join Sales.SalesOrderDetail sod on sod.SalesOrderDetailID = p.BusinessEntityID
join Sales.SalesOrderHeader soh on soh.SalesOrderID = sod.SalesOrderID
where soh.OrderDate like '%2011%' and sod.LineTotal > 10000
</code>```

Note that I used table aliases to shorten the query - I had to make assumptions about columns in the select and where clauses. If these assumptions are correct, then you are only selecting person columns, so I am actually unsure that this code does exactly what you want: if a person has more than one row that satisfies the conditions on salesOrder and salesOrderDetail, then it would be inserted more than once in the temp table. You can avoid that by using exists instead of joins:

```<code>select p.firstname, p.LastName
into #tempTable_2
from Person.Person p
where exists (
    select 1
    from Sales.SalesOrderDetail sod
    join Sales.SalesOrderHeader soh on soh.SalesOrderID = sod.SalesOrderID
    where
        soh.OrderDate like '%2011%'
        and sod.LineTotal > 10000
        and sod.SalesOrderDetailID = p.BusinessEntityID
)
</code>```

Finally, if soh.OrderDate is of a date-like datatype (as it should), then you should use date functions rather than string functions to filter it. That is, replace this:

```<code>soh.OrderDate like '%2011%'
</code>```

With:

```<code>soh.OrderDate >= '2011-01-01' and soh.OrderDate < '2012-01-01'
</code>```

Body:
I have a cursor (just for practice and test cursor) and I want to Insert My Result into TempTable I tried this But I got this error

An INTO clause is not allowed in a cursor declaration.

My code:

DECLARE cursor_brand CURSOR FOR
     SELECT firstname, LastName
     INTO #tempTable_2
     FROM Person.Person
     JOIN Sales.SalesOrderDetail ON SalesOrderDetail.SalesOrderDetailID = Person.BusinessEntityID
     JOIN Sales.SalesOrderHeader ON SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID
     WHERE OrderDate LIKE '%2011%' AND LineTotal > 10000
     ORDER BY LastName

OPEN cursor_brand;

FETCH NEXT FROM cursor_brand

WHILE @@FETCH_STATUS = 0
    FETCH NEXT FROM cursor_brand
    CLOSE cursor_brand
    DEALLOCATE cursor_brand;

Body:
I really don't see why you would need a cursor here. To insert into the temp table, using the select ... into ...  syntax is just enough, so I think your whole code should be simplified as:

select p.firstname, p.LastName
into #tempTable_2
from Person.Person p
join Sales.SalesOrderDetail sod on sod.SalesOrderDetailID = p.BusinessEntityID
join Sales.SalesOrderHeader soh on soh.SalesOrderID = sod.SalesOrderID
where soh.OrderDate like '%2011%' and sod.LineTotal > 10000

Note that I used table aliases to shorten the query - I had to make assumptions about columns in the select and where clauses. If these assumptions are correct, then you are only selecting person columns, so I am actually unsure that this code does exactly what you want: if a person has more than one row that satisfies the conditions on salesOrder and salesOrderDetail, then it would be inserted more than once in the temp table. You can avoid that by using exists instead of joins:

select p.firstname, p.LastName
into #tempTable_2
from Person.Person p
where exists (
    select 1
    from Sales.SalesOrderDetail sod
    join Sales.SalesOrderHeader soh on soh.SalesOrderID = sod.SalesOrderID
    where
        soh.OrderDate like '%2011%'
        and sod.LineTotal > 10000
        and sod.SalesOrderDetailID = p.BusinessEntityID
)

Finally, if soh.OrderDate is of a date-like datatype (as it should), then you should use date functions rather than string functions to filter it. That is, replace this:

soh.OrderDate like '%2011%'

With:

soh.OrderDate >= '2011-01-01' and soh.OrderDate < '2012-01-01'


问:
Filtering SQLite database with SearchBar
i´ve been able to generate and show a SQList database and now i wanna filter it with a Search Bar, i´ve been reading many tutorials, but i´m not able to make it work...

I have an SQLite Model with this code:

```<code>using SQLite;
namespace AppListo
{
public class Employee
  {
    [PrimaryKey, AutoIncrement]
    public long EmpId
    { get; set; }
    [NotNull]
    public string EmpName
    { get; set; }

  }
}
</code>```

...and i retrieve a datalist from the database with:

```<code>public List<Employee> GetAllEmployees()
    {
        return dbConn.Query<Employee>("Select * From [Employee]");
    }
</code>```

...and i show the list in a ContentPage with this xaml code:

```<code><ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" Padding="5,5,5,5">
                            <Label Text="{Binding EmpName}" FontSize="Medium" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>
</code>```

...and this code behind:

```<code>var vList = App.DAUtil.GetAllEmployees();
lstData.ItemsSource = vList;
</code>```

...but i don´t know how to filter this list with a searchbar.
Could you help me to achieve it?

Thanks in advance

答:
Create a property on your View Model like

public ObservableCollection<Employee> Employees { get; set; }

```<code><ListView x:Name="lstData" HasUnevenRows="false" ItemsSource="{Binding Employees}" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" Padding="5,5,5,5">
                            <Label Text="{Binding EmpName}" FontSize="Medium" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>
</code>```

Then create a method to bind your dataset values to your list view

```<code>        private async Task BindEmployees()
        {

            List<Employee> employees = await GetAllEmployees();

            Employees = new ObservableCollection<Employee>(

                            vList.Where(e => e.Name.Contains(mySearchString)).
                            OrderBy(x => x.EmpName).ToList());

            await RaisePropertyChanged("Employees");

        }
</code>```

Call this method on page load or inside your View Model's constructor

```<code>            Task.Run(async() => {
                await BindEmployees();
            });
</code>```

Also, create a Handler method which will be called every time your enter any thing on search bar

and again call BindEmployees method inside that handler function

```<code>
 FilterEmployee_Handler(TextChangedEventArgs args) {
await BindEmployees(),

}
</code>```

Body:
i´ve been able to generate and show a SQList database and now i wanna filter it with a Search Bar, i´ve been reading many tutorials, but i´m not able to make it work...

I have an SQLite Model with this code:

using SQLite;
namespace AppListo
{
public class Employee
  {
    [PrimaryKey, AutoIncrement]
    public long EmpId
    { get; set; }
    [NotNull]
    public string EmpName
    { get; set; }

  }
}

...and i retrieve a datalist from the database with:

public List<Employee> GetAllEmployees()
    {
        return dbConn.Query<Employee>("Select * From [Employee]");
    }

...and i show the list in a ContentPage with this xaml code:

<ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" Padding="5,5,5,5">

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

...and this code behind:

var vList = App.DAUtil.GetAllEmployees();
lstData.ItemsSource = vList;

...but i don´t know how to filter this list with a searchbar.
Could you help me to achieve it?

Thanks in advance

Body:
Create a property on your View Model like

public ObservableCollection<Employee> Employees { get; set; }

<ListView x:Name="lstData" HasUnevenRows="false" ItemsSource="{Binding Employees}" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" Padding="5,5,5,5">
                            <Label Text="{Binding EmpName}" FontSize="Medium" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

Then create a method to bind your dataset values to your list view

        private async Task BindEmployees()
        {

            List<Employee> employees = await GetAllEmployees();

            Employees = new ObservableCollection<Employee>(

                            vList.Where(e => e.Name.Contains(mySearchString)).
                            OrderBy(x => x.EmpName).ToList());

            await RaisePropertyChanged("Employees");

        }

Call this method on page load or inside your View Model's constructor

            Task.Run(async() => {
                await BindEmployees();
            });

Also, create a Handler method which will be called every time your enter any thing on search bar

and again call BindEmployees method inside that handler function

 FilterEmployee_Handler(TextChangedEventArgs args) {
await BindEmployees(),

}


问:
How do I pass additional dependencies to a React custom hook
I am using a custom hook to load initial data into components. It works fine but I get a warning because I pass dynamically constructed dependencies to my useEffect hook:
React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies

Here is the code for my custom hook:

const useApiData = (path: string, dependancies: any[], defaultValue: any) => {
    const client = useApi();
    const modelTemplate = {
        isLoading: true,
        data: defaultValue ? defaultValue : null
    };

    const [model, setModel] = useState(modelTemplate);
    const dependencies: any[] = dependancies ? [...dependancies, client, path, model.isLoading] : [client, path, model.isLoading];

    useEffect(() => {
        if (!model.isLoading) {
            setModel({ isLoading: true, data: null });
        }
        client.get(path).then(data => {
            setModel({ isLoading: false, data: data });
        }).catch(error => {
            //do nothing, errors will be shown in notifications
        });
    }, dependencies);

    return model;
}```
</div>
</div>
</p>

<p>And here is an example of passing an additional dependency:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const product = useApiData(`/products/${productId}`, [model.reviewAdded]);</code>```

In this component I am showing a product details and its reviews. I want to update the product details when a review gets added because the product rating gets changed. Can I do this with using my custom hook and not receiving a warning?

答:
This is lint issue.
It seems that you are using ts-lint, according to your files extensions (*.ts).
In my project, I have similar custom hooks but I use es-lint. With es-lint, I did the next:

Disable warning inside hook via:

```<code>const useCustomHook = (deps) => {
  useEffect(() => {
   doStuff(deps)

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)
}
</code>```

Add custom hook to default validator so that es-lint treats custom hook as out-of-the-box hook and do static checks:

.eslintrc.js

```<code>module.exports = {
 rules: {
   'react-hooks/exhaustive-deps': [
     'error',
     {
       additionalHooks: 'useCustomHook',
     },
   ],
 },
}
</code>```

I believe, you can do something similar for ts-lint

Body:
I am using a custom hook to load initial data into components. It works fine but I get a warning because I pass dynamically constructed dependencies to my useEffect hook:
React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies

Here is the code for my custom hook:

const useApiData = (path: string, dependancies: any[], defaultValue: any) => {
    const client = useApi();
    const modelTemplate = {
        isLoading: true,
        data: defaultValue ? defaultValue : null
    };

    const [model, setModel] = useState(modelTemplate);
    const dependencies: any[] = dependancies ? [...dependancies, client, path, model.isLoading] : [client, path, model.isLoading];

    useEffect(() => {
        if (!model.isLoading) {
            setModel({ isLoading: true, data: null });
        }
        client.get(path).then(data => {
            setModel({ isLoading: false, data: data });
        }).catch(error => {
            //do nothing, errors will be shown in notifications
        });
    }, dependencies);

    return model;
}

And here is an example of passing an additional dependency:

const product = useApiData(`/products/${productId}`, [model.reviewAdded]);

In this component I am showing a product details and its reviews. I want to update the product details when a review gets added because the product rating gets changed. Can I do this with using my custom hook and not receiving a warning?

Body:
This is lint issue.
It seems that you are using ts-lint, according to your files extensions (*.ts).
In my project, I have similar custom hooks but I use es-lint. With es-lint, I did the next:

Disable warning inside hook via:

const useCustomHook = (deps) => {
  useEffect(() => {
   doStuff(deps)

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)
}

Add custom hook to default validator so that es-lint treats custom hook as out-of-the-box hook and do static checks:

.eslintrc.js

module.exports = {
 rules: {
   'react-hooks/exhaustive-deps': [
     'error',
     {
       additionalHooks: 'useCustomHook',
     },
   ],
 },
}

I believe, you can do something similar for ts-lint


问:
How to correctly load and execute JavaScript within Webpacker
I have a Ruby on Rails 6 app with Webpacker. I am implementing an existing bootstrap theme that was not developed for Webpacker.

The theme uses node_modules for various JavaScript features. The theme also has lots of little JavaScript files that specify options and trigger the execution of various node_modules. I have one JavaScript file from the theme for the Typed.js feature that types out sentences in an animation. That file contains an IIFE function.

/app/javascript/src/typed.js

(function() {

  //
  // Variables
  //

  var toggle = document.querySelectorAll('[data-toggle="typed"]');

  //
  // Functions
  //

  function init(el) {
    var elementOptions = el.dataset.options;
        elementOptions = elementOptions ? JSON.parse(elementOptions) : {};
    var defaultOptions = {
      typeSpeed: 40,
      backSpeed: 40,
      backDelay: 1000,
      loop: true
    }
    var options = Object.assign(defaultOptions, elementOptions);

    // Init
    new Typed(el, options);
  }

  //
  // Events
  //

  if (typeof Typed !== 'undefined' && toggle) {
    [].forEach.call(toggle, function(el) {
      init(el);
    });
  }
})();
```
<p>In my Ruby on Rails application.js file, I then load the node_module class like so. Take note that the 'typed.js' file here is not my src/typed.js file -- two separate things:</p>
<h3>File <em>/app/javascript/packs/application.js</em></h3>
```import Typed from 'typed.js';

document.addEventListener("turbolinks:load", () => {
    var inputTZ = document.getElementById("timezone");
    if(inputTZ) {
        inputTZ.value = jstz.determine().name();
    }
});
```
<p>Now I need to load and execute the code from the <em>src/typed.js</em> file within the EventListener block.</p>
```document.addEventListener("turbolinks:load", () => { ... });
```

How do I correctly export the code from the src/typed.js file, import it to the application.js file and then execute it within the EventListener block? Do I even need an IIFE inside the src/typed.js file?

What I've tried: I copied all the code from the src/typed.js file and pasted that inside the EventListener block and it runs fine. But, I want to keep the src/typed.js file in place as I have a lot more of these types of files for other node_module features.

答:
Ok, I am getting it working like this, but please let me know if there are better ways to do this.

I change the src/typed.js file to the below, getting rid of the IIFE and, importantly, I import the core class from within this file:

```<code>import Typed from 'typed.js';

export default function() {
  // ... same code as in the original file ...
}
</code>```

Then, in the application.js file, I do:

```<code>import typed from '../src/typed.js';

document.addEventListener("turbolinks:load", () => {

    typed();

});
</code>```

Body:
I have a Ruby on Rails 6 app with Webpacker. I am implementing an existing bootstrap theme that was not developed for Webpacker.

The theme uses node_modules for various JavaScript features. The theme also has lots of little JavaScript files that specify options and trigger the execution of various node_modules. I have one JavaScript file from the theme for the Typed.js feature that types out sentences in an animation. That file contains an IIFE function.

/app/javascript/src/typed.js

(function() {

  //
  // Variables
  //

  var toggle = document.querySelectorAll('[data-toggle="typed"]');

  //
  // Functions
  //

  function init(el) {
    var elementOptions = el.dataset.options;
        elementOptions = elementOptions ? JSON.parse(elementOptions) : {};
    var defaultOptions = {
      typeSpeed: 40,
      backSpeed: 40,
      backDelay: 1000,
      loop: true
    }
    var options = Object.assign(defaultOptions, elementOptions);

    // Init
    new Typed(el, options);
  }

  //
  // Events
  //

  if (typeof Typed !== 'undefined' && toggle) {
    [].forEach.call(toggle, function(el) {
      init(el);
    });
  }
})();

In my Ruby on Rails application.js file, I then load the node_module class like so. Take note that the 'typed.js' file here is not my src/typed.js file -- two separate things:

File /app/javascript/packs/application.js

import Typed from 'typed.js';

document.addEventListener("turbolinks:load", () => {
    var inputTZ = document.getElementById("timezone");
    if(inputTZ) {
        inputTZ.value = jstz.determine().name();
    }
});

Now I need to load and execute the code from the src/typed.js file within the EventListener block.

document.addEventListener("turbolinks:load", () => { ... });

How do I correctly export the code from the src/typed.js file, import it to the application.js file and then execute it within the EventListener block? Do I even need an IIFE inside the src/typed.js file?

What I've tried: I copied all the code from the src/typed.js file and pasted that inside the EventListener block and it runs fine. But, I want to keep the src/typed.js file in place as I have a lot more of these types of files for other node_module features.

Body:
Ok, I am getting it working like this, but please let me know if there are better ways to do this.

I change the src/typed.js file to the below, getting rid of the IIFE and, importantly, I import the core class from within this file:

import Typed from 'typed.js';

export default function() {
  // ... same code as in the original file ...
}

Then, in the application.js file, I do:

import typed from '../src/typed.js';

document.addEventListener("turbolinks:load", () => {

    typed();

});


问:
Does holding a C++ reference prevents variable of being destroyed?
Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.

I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?

Code:

```<code>static const Color& noneColor = Color();

static bool isNoneColor(const Color& color) {
    return std::addressof(noneColor) == std::addressof(color);
}

MyShape:MyShape() {
    this->color = noneColor; // this->color is an object of Color
}

void MyShape::setColor(const Color& newColor)
{
    this->color= newColor;
}

void MyShape::draw()
{
    if(!isNoneColor(this->color))
        // Color shape
}

//different scope/class
void B::setColorForShape()
{
    Color color = Color(255,255,255);
    a->setColor(color);
    // Calling isNoneColor(a->color); should return false;
    // After this function ends does variable a->color have undefined behavior?
}

void B::setNoneColorForShape()
{
    a->setColor(noneColor);
    //Calling isNoneColor(a->color); should return true;
}
</code>```

Is it safe to call isNoneColor with a->color afterwards the method ends?

Edit:

MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.

答:
Does holding a C++ reference prevents variable of being destroyed?

In general no, not in the way Java references prevent variables from being destroyed.

The lifetime of an object is determined by their storage class: Lifetime of automatic object ends when executions goes out of the block where the variable was declared, lifetime of dynamic object ends when it is deleted, lifetime of static object ends when the process terminates. Lifetime of temporary object ends at the end of the full-expression where it was created, except in special case of binding temporary to a reference, in which case the lifetime of the temporary object ends when the lifetime of the reference ends. And only that one reference; No other reference affects the lifetime of the said temporary object. This is useful in generic programming because it allows certain objects to be treated as if they were references.

isNoneColor can never return true for a member of MyShape because such member will always have different address than noneColor.

Edit: Above was written with the reasonable assumption that the member is an object of type Color

Edit:

MyShape:color is declared has Color& color.

In this case, the member cannot refer to noneColor because a reference to non-const cannot be bound to the lvalue referred by a reference to const... Unless you use const_cast, but that would be naughty.

Body:
Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.

I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?

Code:

static const Color& noneColor = Color();

static bool isNoneColor(const Color& color) {
    return std::addressof(noneColor) == std::addressof(color);
}

MyShape:MyShape() {
    this->color = noneColor; // this->color is an object of Color
}

void MyShape::setColor(const Color& newColor)
{
    this->color= newColor;
}

void MyShape::draw()
{
    if(!isNoneColor(this->color))
        // Color shape
}

//different scope/class
void B::setColorForShape()
{
    Color color = Color(255,255,255);
    a->setColor(color);
    // Calling isNoneColor(a->color); should return false;
    // After this function ends does variable a->color have undefined behavior?
}

void B::setNoneColorForShape()
{
    a->setColor(noneColor);
    //Calling isNoneColor(a->color); should return true;
}

Is it safe to call isNoneColor with a->color afterwards the method ends?

Edit:

MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.


问:
Need help with validating a date
I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message "The Document Date is not a valid date". I would expect that it would say "The Document Date needs to be in the format MM/DD/YYYY".

Why does the line newDate = dateFormat.parse(date); not catch that?

```<code>// checks to see if the document date entered is valid
    private String isValidDate(String date) {

        // set the date format as mm/dd/yyyy
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date newDate = null;

        // make sure the date is in the correct format..
        if(!date.equals("mm/dd/yyyy")) {
            try {
                newDate = dateFormat.parse(date);
            } catch(ParseException e) {
                return "The Document Date needs to be in the format MM/DD/YYYY\n";
            }

            // make sure the date is a valid date..
            if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
                return "The Document Date is not a valid date\n";
            }

            return "true";
        } else {
            return "- Document Date\n";
        }
    }
</code>```

EDIT: I'm trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters "2/2/2011", it will display the message: "The Document Date needs to be in the format MM/DD/YYYY"?

答: The date is correct, but it will be formatted as 02/02/2002</p>

Title: Need help with validating a date

Body:
I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message "The Document Date is not a valid date". I would expect that it would say "The Document Date needs to be in the format MM/DD/YYYY".

Why does the line newDate = dateFormat.parse(date); not catch that?

// checks to see if the document date entered is valid
    private String isValidDate(String date) {

        // set the date format as mm/dd/yyyy
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date newDate = null;

        // make sure the date is in the correct format..
        if(!date.equals("mm/dd/yyyy")) {
            try {
                newDate = dateFormat.parse(date);
            } catch(ParseException e) {
                return "The Document Date needs to be in the format MM/DD/YYYY\n";
            }

            // make sure the date is a valid date..
            if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
                return "The Document Date is not a valid date\n";
            }

            return "true";
        } else {
            return "- Document Date\n";
        }
    }

EDIT: I'm trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters "2/2/2011", it will display the message: "The Document Date needs to be in the format MM/DD/YYYY"?


问:
Can AWS System Manager login as ec2-user
I have an EC2 instance that's typically used via manually sshing onto the box as ec2-user.  Over time the box has accrued various custom configurations such as docker config and git access to our private repositories.

Am trying to automate some commands on the box using AWS System Manager, but system manager logs in as root, which lacks the aforementioned configuration of ec2-user.  Is it possible to somehow login as ec2-user from system manager or change users while logged in?  Because the box has been customized over several months, its not obvious how to reconfigure from scratch (also don't have time to dive into).

Have tried changing user via su ec2-user to no avail.

As a workaround, I'm simply running SSH commands on the box directly eg

ssh -i ~/.ssh/MYPEM.pem ec2-user@MYINSTANCE.us-east-2.compute.amazonaws.com "touch FOOFILE && git clone REPO"

but this avoids system manager altogether and is undesirable.

答:
Thanks to @jordanm for pointing me in the right direction.  I was able to switch to ec2-user afterall using using runuser command (see more here)

```<code>runuser -l ec2-user -c {COMMAND}
</code>```

for example

```<code>runuser -l ec2-user -c 'whoami && git pull'
</code>```

I guess because AWS System Manger is already root, no additional password/auth requried to switch to ec2-user.

Body:
Thanks to @jordanm for pointing me in the right direction.  I was able to switch to ec2-user afterall using using runuser command (see more here)

runuser -l ec2-user -c {COMMAND}

for example

runuser -l ec2-user -c 'whoami && git pull'

I guess because AWS System Manger is already root, no additional password/auth requried to switch to ec2-user.


问:
Jodit: pasting text that calls the html paste pop up fails
I'm adding a Jodit editor to a webpage. I'd like to be able to paste formatted text from, say, MS Word, into the editor. I can paste text that does not call the little pop-up for pasting html text, but not text with formatting. The console logs a warning that addRange(): The given range isn't in document. Indeed, logging window.getSelection().rangeCount returns 0 (instead of 1 in other cases). I have no idea what is wrong as pasting from various programs, of course, works on the website. Am I missing an event?

答:
The problem was that the editor was in an ag-grid cell. The different selections in the dialog box when pasting from MS Word into the editor lay outside of the ag-grid cell, and therefore clicking in the dialog ended the ag-grid session mid-edit!
As the behavior I was looking for is to keep the formatting, I simply turned off the dialog box (askBeforePasteFromWord: false, askBeforePasteHTML: false). To still handle the pasting from MS Word (because MS Word), added in Jodit's author's code to auto-handle (https://github.com/xdan/jodit/issues/197):

              jodit_editor = new Jodit(text_area_element, {
              hotkeys: {
                  redo: 'ctrl+z',
                  undo: 'ctrl+y,ctrl+shift+z',
                  indent: 'ctrl+]',
                  outdent: 'ctrl+[',
                  bold: 'ctrl+b',
                  italic: 'ctrl+i',
                  removeFormat: 'ctrl+shift+m',
                  insertOrderedList: 'ctrl+shift+7',
                  insertUnorderedList: 'ctrl+shift+8',
                  openSearchDialog: 'ctrl+f',
                  openReplaceDialog: 'ctrl+r',
              },
              events: {
                  processPaste: function(event, html){
                      jodit_editor.selection.insertHTML(html);
                      jodit_editor.tempContent = jodit_editor.getEditorValue();
                  },
                  afterPaste: function(event){
                      let el = $('

');
                      el.html(jodit_editor.tempContent ? jodit_editor.tempContent : jodit_editor.getEditorValue());
                      jodit_editor.setEditorValue(el.html());
                      jodit_editor.tempContent = null;
                  },
              },
              askBeforePasteFromWord: false,
              askBeforePasteHTML: false

          });```

Body:
The problem was that the editor was in an ag-grid cell. The different selections in the dialog box when pasting from MS Word into the editor lay outside of the ag-grid cell, and therefore clicking in the dialog ended the ag-grid session mid-edit!
As the behavior I was looking for is to keep the formatting, I simply turned off the dialog box (askBeforePasteFromWord: false, askBeforePasteHTML: false). To still handle the pasting from MS Word (because MS Word), added in Jodit's author's code to auto-handle (https://github.com/xdan/jodit/issues/197):

              jodit_editor = new Jodit(text_area_element, {
              hotkeys: {
                  redo: 'ctrl+z',
                  undo: 'ctrl+y,ctrl+shift+z',
                  indent: 'ctrl+]',
                  outdent: 'ctrl+[',
                  bold: 'ctrl+b',
                  italic: 'ctrl+i',
                  removeFormat: 'ctrl+shift+m',
                  insertOrderedList: 'ctrl+shift+7',
                  insertUnorderedList: 'ctrl+shift+8',
                  openSearchDialog: 'ctrl+f',
                  openReplaceDialog: 'ctrl+r',
              },
              events: {
                  processPaste: function(event, html){
                      jodit_editor.selection.insertHTML(html);
                      jodit_editor.tempContent = jodit_editor.getEditorValue();
                  },
                  afterPaste: function(event){
                      let el = $('<div></div>');
                      el.html(jodit_editor.tempContent ? jodit_editor.tempContent : jodit_editor.getEditorValue());
                      jodit_editor.setEditorValue(el.html());
                      jodit_editor.tempContent = null;
                  },
              },
              askBeforePasteFromWord: false,
              askBeforePasteHTML: false

          });


问:
Poetry install packages asynchronously
I am using poetry with docker and it seems my deployment process is significantly slowed down by poetry downloading the packages synchronously. Is there a way to download the packages asynchronously?</p>

答:
Poetry is a young project with not much performance tuning done compared to pip. If performance is important to you, you can use something like:

```<code>poetry export --without-hashes -f requirements.txt | pip install -r /dev/stdin
</code>```

This will export the requirements from poetry and install them via pip. Note that you loose the security hash checks while keeping poetrys smart dependency resolution and version pinning. Note that not even pip can download packages in parallel (https://github.com/pypa/pip/issues/825), but still is significantly faster.

Title: Poetry install packages asynchronously

Body:
Poetry is a young project with not much performance tuning done compared to pip. If performance is important to you, you can use something like:

poetry export --without-hashes -f requirements.txt | pip install -r /dev/stdin

This will export the requirements from poetry and install them via pip. Note that you loose the security hash checks while keeping poetrys smart dependency resolution and version pinning. Note that not even pip can download packages in parallel (https://github.com/pypa/pip/issues/825), but still is significantly faster.


问:
Scope left Join Sub doesn't work - Laravel
I'm new to Laravel I'm making a clone of Twitter. I'm making a scope to get all the likes from the DB, but I get an error from Tinker

I know some basic SQL Queries, but this one is quite complicated, so I've got no idea what to do now.

Tweet model

```<code>public function scopeWithLikes(Builder $query)
    {
        $query->leftJoinSub(
            'select tweet_id, sum(liked) likes, sum(!liked) dislikes from likes group by tweet_id',
            'likes',
            'likes.tweet_id',
            'tweet.id'
        );
    }
</code>```

Tinker command

```<code>App\Tweet::withLikes()->first();
</code>```

Tinker error

TypeError: Argument 1 passed to App/Tweet::scopeWithLikes() must be an
  instance of Illuminate/Database/Query/Builder, instance of
  Illuminate/Database/Eloquent/Builder given, called in
  C:/wamp64/www/laravel/tweety/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
  on line 1164

I hope I explained it well, but if you need more information please ask me.

Thanks for your answer!

答:
i think that you are using the wrong class for your scope, scope use

Illuminate/Database/Query/Builder

as a parameter while you pass

Illuminate/Database/Eloquent/Builder

in your Twit model file, on the top ...

remove:

```<code>use  Illuminate/Database/Eloquent/Builder;
</code>```

and paste:

```<code>use Illuminate/Database/Query/Builder;
</code>```

Body:
I'm new to Laravel I'm making a clone of Twitter. I'm making a scope to get all the likes from the DB, but I get an error from Tinker

I know some basic SQL Queries, but this one is quite complicated, so I've got no idea what to do now.

Tweet model

public function scopeWithLikes(Builder $query)
    {
        $query->leftJoinSub(
            'select tweet_id, sum(liked) likes, sum(!liked) dislikes from likes group by tweet_id',
            'likes',
            'likes.tweet_id',
            'tweet.id'
        );
    }

Tinker command

App\Tweet::withLikes()->first();

Tinker error

TypeError: Argument 1 passed to App/Tweet::scopeWithLikes() must be an
  instance of Illuminate/Database/Query/Builder, instance of
  Illuminate/Database/Eloquent/Builder given, called in
  C:/wamp64/www/laravel/tweety/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
  on line 1164

I hope I explained it well, but if you need more information please ask me.

Thanks for your answer!

Body:
i think that you are using the wrong class for your scope, scope use

Illuminate/Database/Query/Builder

as a parameter while you pass

Illuminate/Database/Eloquent/Builder

in your Twit model file, on the top ...

remove:

use  Illuminate/Database/Eloquent/Builder;

and paste:

use Illuminate/Database/Query/Builder;


问:
subscribe a Variable you got from a socket
i try to update my token i get every 30 sec from my socket. But the code i found doesn#t work.
How do i subscribe to a varibale in this chase ?
And if i subscribe does the values always change or just the first time?

the socket

import * as io from 'socket.io-client';
import {Injectable} from '@angular/core';
import {Observable, Subject} from 'rxjs';

@Injectable()
export class SocketService {

  public token =new Observable<any>()
  second;
  socket  = io.connect('http://localhost:3333');
  msg: any;

  getToken() {
    console.log('newToken');
    this.socket.on('newToken', (data) => {
      console.log(data);
      this.token = data.token;
      this.second = data.second;
      console.log(this.token, this.second);
    });
  }```
</div>
</div>
</p>

<p><strong>the component</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import {SocketService} from '../../Service/socket.service';

@Component({
  selector: 'app-token',
  templateUrl: './token.component.html',
  styleUrls: ['./token.component.css']
})
export class TokenComponent implements OnInit {

  token;

constructor(
    private socket: SocketService,
  ) {
    this.socket.token.subscribe(res => {
      this.token = res;
    });
  }

  ngOnInit(): void {
     this.socket.getToken();
  }

}</code>```

答:
Are you assigning SocketService.token an Observable or just a token?

On this line
this.token = data.token; I expect you to be assigning an Observable. If data.token is an Observable, please let us know or type data appropriately.

You can try using a Subject instead.
Try changing your declaration in SocketService to
public token = new Subject<any>();

Then in the socket.on callback. Set the token value by this.token.next(data.token)

Body:
i try to update my token i get every 30 sec from my socket. But the code i found doesn#t work.
How do i subscribe to a varibale in this chase ?
And if i subscribe does the values always change or just the first time?

the socket

import * as io from 'socket.io-client';
import {Injectable} from '@angular/core';
import {Observable, Subject} from 'rxjs';

@Injectable()
export class SocketService {

  public token =new Observable<any>()
  second;
  socket  = io.connect('http://localhost:3333');
  msg: any;

  getToken() {
    console.log('newToken');
    this.socket.on('newToken', (data) => {
      console.log(data);
      this.token = data.token;
      this.second = data.second;
      console.log(this.token, this.second);
    });
  }

the component

import { Component, OnInit } from '@angular/core';
import {SocketService} from '../../Service/socket.service';

@Component({
  selector: 'app-token',
  templateUrl: './token.component.html',
  styleUrls: ['./token.component.css']
})
export class TokenComponent implements OnInit {

  token;

constructor(
    private socket: SocketService,
  ) {
    this.socket.token.subscribe(res => {
      this.token = res;
    });
  }

  ngOnInit(): void {
     this.socket.getToken();
  }

}


问:
How to fix "Error: Cannot call setTimeout from within a sync test." when testing for a service?
I'm trying to unit test a very basic service that uses ngx-socket-io using Jasmine + Karma.

I keep getting Error: Cannot call setTimeout from within a sync test.

Here's my service:

```<code>import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { Message } from 'src/app/models/message';

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  constructor(private socket: Socket) { };

  newMessages(){
    return this.socket.fromEvent<Message>('newMessage');
  }

  newMessage(message: String) {
    this.socket.emit('messageSent', message);
  }
}
</code>```

This is my unit test:

```<code>import { TestBed } from '@angular/core/testing';
import { MessageService } from './message.service';
import SocketMock from 'socket.io-mock';
import { WrappedSocket } from 'ngx-socket-io/src/socket-io.service';

describe('MessageService', () => {
  let service: MessageService;
  let socket: WrappedSocket = new WrappedSocket(new SocketMock());
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers :[
        MessageService,
        {provide: WrappedSocket, useValue: socket}
      ]
    });
    service = TestBed.get(MessageService);
  });

  it('should be created', async () => {
    expect(service).toBeTruthy();
  });
});

</code>```

Here is the full error output:

```<code>Error: Cannot call setTimeout from within a sync test.
    at SyncTestZoneSpec.onScheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:366:1)
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:404:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:238:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:261:1)
    at scheduleMacroTaskWithCurrentZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1245:1)
    at http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:2317:1
    at proto.<computed> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1569:1)
    at Request.create (http://localhost:9876/_karma_webpack_/webpack:/node_modules/engine.io-client/lib/transports/polling-xhr.js:268:1)
    at new Request (http://localhost:9876/_karma_webpack_/webpack:/node_modules/engine.io-client/lib/transports/polling-xhr.js:165:1)
    at XHR.request (http://localhost:9876/_karma_webpack_/webpack:/node_modules/engine.io-client/lib/transports/polling-xhr.js:92:1)
</code>```

I just want to test that the service is created for now. What's going on, and how can I get the test to pass?

答:
Check your test.ts file. Mainly the zone.js imports
Order should be

```<code>import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
</code>```

Reference - https://github.com/angular/zone.js/issues/1058

Body:
I'm trying to unit test a very basic service that uses ngx-socket-io using Jasmine + Karma.

I keep getting Error: Cannot call setTimeout from within a sync test.

Here's my service:

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { Message } from 'src/app/models/message';

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  constructor(private socket: Socket) { };

  newMessages(){
    return this.socket.fromEvent<Message>('newMessage');
  }

  newMessage(message: String) {
    this.socket.emit('messageSent', message);
  }
}

This is my unit test:

import { TestBed } from '@angular/core/testing';
import { MessageService } from './message.service';
import SocketMock from 'socket.io-mock';
import { WrappedSocket } from 'ngx-socket-io/src/socket-io.service';

describe('MessageService', () => {
  let service: MessageService;
  let socket: WrappedSocket = new WrappedSocket(new SocketMock());
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers :[
        MessageService,
        {provide: WrappedSocket, useValue: socket}
      ]
    });
    service = TestBed.get(MessageService);
  });

  it('should be created', async () => {
    expect(service).toBeTruthy();
  });
});

Here is the full error output:

Error: Cannot call setTimeout from within a sync test.
    at SyncTestZoneSpec.onScheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:366:1)
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:404:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:238:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:261:1)
    at scheduleMacroTaskWithCurrentZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1245:1)
    at http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:2317:1
    at proto.<computed> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1569:1)
    at Request.create (http://localhost:9876/_karma_webpack_/webpack:/node_modules/engine.io-client/lib/transports/polling-xhr.js:268:1)
    at new Request (http://localhost:9876/_karma_webpack_/webpack:/node_modules/engine.io-client/lib/transports/polling-xhr.js:165:1)
    at XHR.request (http://localhost:9876/_karma_webpack_/webpack:/node_modules/engine.io-client/lib/transports/polling-xhr.js:92:1)

I just want to test that the service is created for now. What's going on, and how can I get the test to pass?

Body:
Check your test.ts file. Mainly the zone.js imports
Order should be

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

Reference - https://github.com/angular/zone.js/issues/1058


问:
Using dplyr in order to create a new column
Hel lo
I have a df such as

```<code>Groups COL1 COL2
G1 1 A
G1 1 C
G1 2 A
G1 2 B
G1 5 C
G1 6 C
G2 7 B
G2 7 B
G2 8 C
G3 10 C
G3 10 A
G3 11 B
G4 12 C
G4 12 C
</code>```

and the idea is to add a new column COL3
and

```<code>group_by(Groups, COL1) %>%
  mutate(COL3 = COL1(A>B>C))
</code>```

the idea being that within groups and COL1, if two COL2 values are different, if A is present with A or C, all value become A, if A is not present but B is here, all value become B and if there is only C, all value become C (they already are).

so A > B and B > C
here is the expected output :

```<code>Groups COL1 COL2 COL3
G1 1 A A
G1 1 C A
G1 2 A A
G1 2 B A
G1 5 C C
G1 6 C C
G2 7 B B
G2 7 B B
G2 8 C C
G3 10 C A
G3 10 A A
G3 11 B B
G4 12 C C
G4 12 C C
</code>```

Does someone have an idea ?

答:
An option with ave

```<code>df1$COL3 <- with(df1, ave(COL1, Groups, FUN = min))
</code>```

Body:
Hel lo
I have a df such as

Groups COL1 COL2
G1 1 A
G1 1 C
G1 2 A
G1 2 B
G1 5 C
G1 6 C
G2 7 B
G2 7 B
G2 8 C
G3 10 C
G3 10 A
G3 11 B
G4 12 C
G4 12 C

and the idea is to add a new column COL3
and

group_by(Groups, COL1) %>%
  mutate(COL3 = COL1(A>B>C))

the idea being that within groups and COL1, if two COL2 values are different, if A is present with A or C, all value become A, if A is not present but B is here, all value become B and if there is only C, all value become C (they already are).

so A > B and B > C
here is the expected output :

Groups COL1 COL2 COL3
G1 1 A A
G1 1 C A
G1 2 A A
G1 2 B A
G1 5 C C
G1 6 C C
G2 7 B B
G2 7 B B
G2 8 C C
G3 10 C A
G3 10 A A
G3 11 B B
G4 12 C C
G4 12 C C

Does someone have an idea ?

Body:
An option with ave

df1$COL3 <- with(df1, ave(COL1, Groups, FUN = min))


问:
How do I customize Jenkins theme?
I want to change background images, logo ,headings and add some buttons.
I have the following UI related plugins installed

1) Simple Theme Plugin
A plugin for Jenkins that supports custom CSS & JavaScript. You can customize Jenkins's appearance (ex. his gentle face on the background).
version 0.3

2) UI Themes: Plugin
This plugin provides UI themes for Jenkins.
version 2.1.1

I have found some answer regarding the same but didn't find much help.

-->> Customising Jenkins' appearance to make it easier to tell instances apart

-->> http://isotope11.com/blog/styling-your-jenkins-continuous-integration-server

Please give steps or any links from which I can completely change the appearance of my Jenkins server.

答:
You can see an example of full theme in progress in jenkinsci/dark-theme.

It is not yet ready, but can illustrate how the CSS is setup with a Jenkins 2.220+ (May 2020)

Title: How do I customize Jenkins theme?


问:
Wicket.Ajax.Call.failure: Error while parsing response: Object required
I just spent several hours of my life debugging this problem. I'm documenting it here for others.

Question:

I'm getting the following error when I try to click on an AjaxLink in Internet Explorer:

Wicket: ERROR: Wicket.Ajax.Call.failure: Error while parsing response: Object required

It works fine in all other browsers; just IE is busted.

答:
Check to make sure that your HTML is 100% syntactically correct. Ajax responses are returned to the browser inside a CDATA section, and if the payload is not well-formed, IE will sometimes choke.

In my case I neglected to close a <link> tag in the  section. Simply closing that link tag made all the difference.

Aside: if you ever come across a tough-to-solve problem in Wicket, it's a good idea to create a quickstart project that reproduces your issue. It can be a lot of work to boil things down, but in doing so you often find the source of the problem.

Body:
Check to make sure that your HTML is 100% syntactically correct. Ajax responses are returned to the browser inside a CDATA section, and if the payload is not well-formed, IE will sometimes choke.

In my case I neglected to close a <link> tag in the <head> section. Simply closing that link tag made all the difference.

Aside: if you ever come across a tough-to-solve problem in Wicket, it's a good idea to create a quickstart project that reproduces your issue. It can be a lot of work to boil things down, but in doing so you often find the source of the problem.


问:
NotifyListeners() don' work appropriately in Flutter
In my splash screen, I am calling  a method from my model class (getting some data from API and putting them into a list). It works and generates the list. But I can't send this list to my listview widget. Here is the relevant code;

SplashScreen part which is calling model class method (getFixtures)

```<code> class _SplashScreenState extends State<SplashScreen> {
  List<Fixture> fixtureList = List<Fixture>();
  FixtureData callFixtureData = FixtureData();

  @override
  void initState() {
    super.initState();
    SplashScreen.fixtureData = getFixture();
    Timer(
      Duration(seconds: 5),
      () => Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (BuildContext context) => WelcomeScreen(),
        ),
      ),
    );
  }

  Future<List<Fixture>> getFixture() async {
    fixtureList = await callFixtureData.getFixtures();
    return fixtureList;
  }
</code>```

Model class part; I see the list is not null and correct

```<code>class FixtureData extends ChangeNotifier {

  List<Fixture> fixtures = List<Fixture>();
  List<Fixture> bets = List<Fixture>();

  //to show in FAB at HomeScreen
  int get betCount {
    return bets.length;
  }

  Future<List<Fixture>> getFixtures() async {
    fixtures = await FootballApi.getFixtureData();
    print(fixtures[0].homeTeam);
    notifyListeners();
    return fixtures;
  }
</code>```

ListView part. I'm calling the list with final fixture = fixtureData.fixtures[index]; But nothing happens. What am I missing?

```<code>class FixtureList extends StatelessWidget {
  final dateFormat = DateFormat('MMMd');
  final timeFormat = DateFormat('Hm');

  @override
  Widget build(BuildContext context) {
    return Consumer<FixtureData>(
      builder: (context, fixtureData, child) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final fixture = fixtureData.fixtures[index];
            return FixtureTile(
              date: dateFormat.format(fixture.dateTime),
              time: timeFormat.format(fixture.dateTime),
              homeTeam: fixture.homeTeam,
              awayTeam: fixture.awayTeam,
              homeOdds: fixture.homeOdds,
              drawOdds: fixture.drawOdds,
              awayOdds: fixture.awayOdds,
              isHomeSelected: fixture.homeSelected,
              isDrawSelected: fixture.drawSelected,
              isAwaySelected: fixture.awaySelected,
              homeCallBack: () => fixtureData.updateSelection(fixture, 'home'),
              drawCallBack: () => fixtureData.updateSelection(fixture, 'draw'),
              awayCallBack: () => fixtureData.updateSelection(fixture, 'away'),
            );
          },
          itemCount: fixtureData.fixtures.length,
        );
      },
    );
  }
}
</code>```

答:
you should read Provider documentation or sample first , this is so wrong , you've never set value to FixtureData.fixtures but in ListView you want to use this !!

```<code>class _SplashScreenState extends State<SplashScreen> {
  List<Fixture> fixtureList = List<Fixture>();
  //FixtureData callFixtureData = FixtureData();

  @override
  void initState() {
    super.initState();
   // SplashScreen.fixtureData = getFixture();
   Provider.of<FixtureData>(context, listen: false).getFixtures();

    Timer(
      Duration(seconds: 5),
      () => Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (BuildContext context) => WelcomeScreen(),
        ),
      ),
    );
  }

 // Future<List<Fixture>> getFixture() async {
 //   fixtureList = await callFixtureData.getFixtures();
 //   return fixtureList;
 // }

</code>```

after that you can use your Consumer ...

also make sure ChangeNotifierProvider is an ancestor to this SplashScreen Widget , like :

```<code>
 MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => FixtureData()),
      ],
      child: SplashScreen(),
    ),

</code>```

Body:
In my splash screen, I am calling  a method from my model class (getting some data from API and putting them into a list). It works and generates the list. But I can't send this list to my listview widget. Here is the relevant code;

SplashScreen part which is calling model class method (getFixtures)

 class _SplashScreenState extends State<SplashScreen> {
  List<Fixture> fixtureList = List<Fixture>();
  FixtureData callFixtureData = FixtureData();

  @override
  void initState() {
    super.initState();
    SplashScreen.fixtureData = getFixture();
    Timer(
      Duration(seconds: 5),
      () => Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (BuildContext context) => WelcomeScreen(),
        ),
      ),
    );
  }

  Future<List<Fixture>> getFixture() async {
    fixtureList = await callFixtureData.getFixtures();
    return fixtureList;
  }

Model class part; I see the list is not null and correct

class FixtureData extends ChangeNotifier {

  List<Fixture> fixtures = List<Fixture>();
  List<Fixture> bets = List<Fixture>();

  //to show in FAB at HomeScreen
  int get betCount {
    return bets.length;
  }

  Future<List<Fixture>> getFixtures() async {
    fixtures = await FootballApi.getFixtureData();
    print(fixtures[0].homeTeam);
    notifyListeners();
    return fixtures;
  }

ListView part. I'm calling the list with final fixture = fixtureData.fixtures[index]; But nothing happens. What am I missing?

class FixtureList extends StatelessWidget {
  final dateFormat = DateFormat('MMMd');
  final timeFormat = DateFormat('Hm');

  @override
  Widget build(BuildContext context) {
    return Consumer<FixtureData>(
      builder: (context, fixtureData, child) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final fixture = fixtureData.fixtures[index];
            return FixtureTile(
              date: dateFormat.format(fixture.dateTime),
              time: timeFormat.format(fixture.dateTime),
              homeTeam: fixture.homeTeam,
              awayTeam: fixture.awayTeam,
              homeOdds: fixture.homeOdds,
              drawOdds: fixture.drawOdds,
              awayOdds: fixture.awayOdds,
              isHomeSelected: fixture.homeSelected,
              isDrawSelected: fixture.drawSelected,
              isAwaySelected: fixture.awaySelected,
              homeCallBack: () => fixtureData.updateSelection(fixture, 'home'),
              drawCallBack: () => fixtureData.updateSelection(fixture, 'draw'),
              awayCallBack: () => fixtureData.updateSelection(fixture, 'away'),
            );
          },
          itemCount: fixtureData.fixtures.length,
        );
      },
    );
  }
}

Body:
you should read Provider documentation or sample first , this is so wrong , you've never set value to FixtureData.fixtures but in ListView you want to use this !!

class _SplashScreenState extends State<SplashScreen> {
  List<Fixture> fixtureList = List<Fixture>();
  //FixtureData callFixtureData = FixtureData();

  @override
  void initState() {
    super.initState();
   // SplashScreen.fixtureData = getFixture();
   Provider.of<FixtureData>(context, listen: false).getFixtures();

    Timer(
      Duration(seconds: 5),
      () => Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (BuildContext context) => WelcomeScreen(),
        ),
      ),
    );
  }

 // Future<List<Fixture>> getFixture() async {
 //   fixtureList = await callFixtureData.getFixtures();
 //   return fixtureList;
 // }

after that you can use your Consumer ...

also make sure ChangeNotifierProvider is an ancestor to this SplashScreen Widget , like :

 MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => FixtureData()),
      ],
      child: SplashScreen(),
    ),


问:
Laravel 7: How to prevent middleware Authenticate from redirecting when user is not authenticated?
I have implemented the middleware Authenticate with $this->middleware('auth:api');.

The application is a REST API so I don't need Laravel to redirect the client. I need it to return a JSON response.

There is a method redirectTo inside App\Http\Middleware\Authenticate.php;. This method only accepts a route, therefore I cannot add the JSON response to this method.

How can I use the middleware Authenticate (auth:api) and return a JSON Response when the user is not authenticated?

答: Laravel already does this when the request expects a JSON response. So, as long as you're either sending AJAX requests or you're sending requests with the Accept header set properly (application/json or *), Laravel will automatically respond with a 401 JSON response.


问:
Wikipedia Mediawiki API get Pageid from URL
I have a set of full urls like

```<code>http://en.wikipedia.org/wiki/Episkopi_Bay
http://en.wikipedia.org/wiki/Monte_Lauro
http://en.wikipedia.org/wiki/Lampedusa
http://en.wikipedia.org/wiki/Himera
http://en.wikipedia.org/wiki/Lago_Cecita
http://en.wikipedia.org/wiki/Aspromonte
</code>```

I want to find wikipedia pageids for these URLS. I have used the Mediawiki API before but I cant figure out how I may do this.

I have tried extracting the page title from the URLs by taking a substring of lastindexof("/") and the last character and then querying the API to get pageid.

```<code>http://en.wikipedia.org/wiki/Episkopi_Bay --> Episkopi_Bay
http://en.wikipedia.org/wiki/Monte_Lauro --> Monte_Lauro
http://en.wikipedia.org/wiki/Lampedusa -- > Lampedusa
http://en.wikipedia.org/wiki/Himera --> Himera
http://en.wikipedia.org/wiki/Lago_Cecita --> Lago_Cecita
http://en.wikipedia.org/wiki/Aspromonte --> Aspromonte
</code>```

But the problem is that some of my links might be redirects and hence the substring might not always be the title of the page.

TL;DR : How can I find the pageid of a wikipedia page from a URL ?

答:
You can add &indexpageids to your query.

For example

https://en.wikipedia.org/w/api.php?action=query&format=json&titles=Main%20Pages&indexpageids

or if you are looking for a summary at the same time, here's a more comprehensive example link:

https://en.wikipedia.org/w/api.php?action=query&format=json&titles=barberton%20daisy&prop=extracts&exintro&explaintext&redirects=1&indexpageids

Then if you parse the JSON you will see a property named pageids under query

Body:
I have a set of full urls like

http://en.wikipedia.org/wiki/Episkopi_Bay
http://en.wikipedia.org/wiki/Monte_Lauro
http://en.wikipedia.org/wiki/Lampedusa
http://en.wikipedia.org/wiki/Himera
http://en.wikipedia.org/wiki/Lago_Cecita
http://en.wikipedia.org/wiki/Aspromonte

I want to find wikipedia pageids for these URLS. I have used the Mediawiki API before but I cant figure out how I may do this.

I have tried extracting the page title from the URLs by taking a substring of lastindexof("/") and the last character and then querying the API to get pageid.

http://en.wikipedia.org/wiki/Episkopi_Bay --> Episkopi_Bay
http://en.wikipedia.org/wiki/Monte_Lauro --> Monte_Lauro
http://en.wikipedia.org/wiki/Lampedusa -- > Lampedusa
http://en.wikipedia.org/wiki/Himera --> Himera
http://en.wikipedia.org/wiki/Lago_Cecita --> Lago_Cecita
http://en.wikipedia.org/wiki/Aspromonte --> Aspromonte

But the problem is that some of my links might be redirects and hence the substring might not always be the title of the page.

TL;DR : How can I find the pageid of a wikipedia page from a URL ?


问:
Shouldn't this fail without the use of locking? Simple producer consumer
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

```<code>    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}
</code>```

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)

答:
Locking is to done to eliminate aberrant behavior of an application, most specifically in multithreading. The most common goal is the elimination of a "race condition" which causes non-deterministic program behavior.

This is the behavior you saw. In one run you get an error for the queue having no items, in another run you have no issues. This is a race condition. Proper usage of locking will eliminate this scenario.

Body:
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)


问:
Aframe Texture Change
I am working on the following script. To change the image of the .glb model. It producing only a white color. No proper texture change is happening. Please help me.

    const nextButtonComponent = () => ({
  init: function() {
    const model = document.getElementById('model')
    const nextButton = document.getElementById('nextbutton')
    const loader = new THREE.TextureLoader();

    var material = new THREE.MeshStandardMaterial({
      side: THREE.DoubleSide,
      flatShading: true,
    });
    const mesh = model.getObject3D('mesh');

    nextButton.style.display = 'block';

    const nextAnimation = () => {
      loader.load( './assets/img/1.jpg' ,
            function(texture){
            material.map = texture;
            material.needsUpdate = true;

            if(mesh){
                mesh.traverse((node) => {
                  if (node.isMesh) {
                    node.material = material;
                    node.material.map = texture;
                    node.material.needsUpdate = true;
                  }
                });
              }
            });
    }
    nextButton.onclick = nextAnimation // Switch to the next animation when the button is pressed.
  }
})
export {nextButtonComponent}
```

答:
Here is a part of a tutorial on how to make minecraft in a-frame:

We place  into our , place assets (e.g., images, videos, models, sounds) into , and point to them from our entities via a selector (e.g., #myTexture).

Let’s move our ground texture to  to be preloaded using an  element:

```

Title: Aframe Texture Change

Body:
Here is a part of a tutorial on how to make minecraft in a-frame:

We place  into our , place assets (e.g., images, videos, models, sounds) into , and point to them from our entities via a selector (e.g., #myTexture).

Let’s move our ground texture to  to be preloaded using an  element:

<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>

<a-scene>
  <a-assets>
    <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
  </a-assets>

  <a-cylinder id="ground" src="#groundTexture" radius="32" height="0.1"></a-cylinder>
</a-scene>


问:
CodeWars Javascript Challenge: Are they the "same"?
The Kata: link

My solution:

```<code>function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2) && array1.length && array2.length) {
        result = true;
        const squares = array2.map(e => Math.sqrt(e));
        squares.forEach((e) => {
            if (array1.includes(e)) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}
</code>```

I don't want another solution. I want to figure out why mine doesn't pass in all of the tests. (Fails on two tests but I can't see which)

I suspect the test expects true if both arrays are []. But the Kata's description says otherwise:

If a or b are nil (or null or None), the problem doesn't make sense so return false.

Help would be appreciated.

Working Solution Based off of the answers:

```<code>function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2)) {
        result = true;
        const sortedArray1 = array1.sort((a, b) => a - b);
        const squares = array2.map(e => Math.sqrt(e)).sort((a, b) => a - b);
        squares.forEach((e, i) => {
            if (sortedArray1[i] === e) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}
</code>```

答:
Okey, some cheating workarounds but your code fails here:

That's why after removing two .length you pass one more test.

Next one is

After .sqrt array2 you get 2, 3, 3 that's why you return true, but it's false. That answer will be enough to help you solve this kata.

Btw.

I suspect the test expects true if both arrays are []. But the Kata's
  description says otherwise:

Kata's description:

a or b might be [] (all languages except R, Shell).
  : - D

P.S. I know for some people checking arguments maybe treated as cheating, I just do it for educational purposes. Black boxes are not always enough to figure out what's wrong.

Body:
The Kata: link

My solution:

function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2) && array1.length && array2.length) {
        result = true;
        const squares = array2.map(e => Math.sqrt(e));
        squares.forEach((e) => {
            if (array1.includes(e)) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}

I don't want another solution. I want to figure out why mine doesn't pass in all of the tests. (Fails on two tests but I can't see which)

I suspect the test expects true if both arrays are []. But the Kata's description says otherwise:

If a or b are nil (or null or None), the problem doesn't make sense so return false.

Help would be appreciated.

Working Solution Based off of the answers:

function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2)) {
        result = true;
        const sortedArray1 = array1.sort((a, b) => a - b);
        const squares = array2.map(e => Math.sqrt(e)).sort((a, b) => a - b);
        squares.forEach((e, i) => {
            if (sortedArray1[i] === e) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}


问:
How do I get system boot time in batch?
I need the System Boot Time in a batch script, only the time, no date, no string.

I can't get it into a variable

```<code>set systime=systeminfo | find "System Boot Time"
echo %systime%
</code>```

The only thing, which is working, is:

```<code>systeminfo | find "System Boot Time">>c:\time.txt
</code>```

I need it as batch because I need to modify an already existing batchfile.

Edit:
Changed “System Boot Time” to "System Boot Time" dont know where these come from ^^

答:
Copy and paste the following lines in nodepad and save as .cmd extension.</p>

```<code>@ECHO OFF
systeminfo | find "System Boot Time"
PAUSE
</code>```

Title: How do I get system boot time in batch?

Body:
I need the System Boot Time in a batch script, only the time, no date, no string.

I can't get it into a variable

set systime=systeminfo | find "System Boot Time"
echo %systime%

The only thing, which is working, is:

systeminfo | find "System Boot Time">>c:\time.txt

I need it as batch because I need to modify an already existing batchfile.

Edit:
Changed “System Boot Time” to "System Boot Time" dont know where these come from ^^

Body:
Copy and paste the following lines in nodepad and save as .cmd extension.

@ECHO OFF
systeminfo | find "System Boot Time"
PAUSE