问:
EF 6 - Consume stored procedure and call ToListAsync()
I am trying to call a stored procedure via EF 6. Using ToList() works as expected and a list of entities is returned.  However, ToListAsync() does NOT seem to return data.  In sql Profiler, I can see the stored procedure being executed against the database.  However, the break point after the line for ToListAsync() does not get hit.  I never see data get returned.

code below

```<code>public async Task<List<MyEntityObject>> GetStoredProcedureData()        {

           List<MyEntityObject> MyEntityObjects;
           using (var dbContext = new DbContext())
           {
               var  MyEntityObjectsQry = dbContext.Database.SqlQuery<MyEntityObject>("dbo.GetStoredProcedureData");
               MyEntityObjects =await MyEntityObjectsQry.ToListAsync();
           }
           return MyEntityObjects;
       }
</code>```

答:
The get method will be like

```<code>var myEntityObjectsQry = await dbContext.Database.ToListAsync();
</code>```

More references here:
https://www.entityframeworktutorial.net/entityframework6/async-query-and-save.aspx

Body:
I am trying to call a stored procedure via EF 6. Using ToList() works as expected and a list of entities is returned.  However, ToListAsync() does NOT seem to return data.  In sql Profiler, I can see the stored procedure being executed against the database.  However, the break point after the line for ToListAsync() does not get hit.  I never see data get returned.

code below

public async Task<List<MyEntityObject>> GetStoredProcedureData()        {

           List<MyEntityObject> MyEntityObjects;
           using (var dbContext = new DbContext())
           {
               var  MyEntityObjectsQry = dbContext.Database.SqlQuery<MyEntityObject>("dbo.GetStoredProcedureData");
               MyEntityObjects =await MyEntityObjectsQry.ToListAsync();
           }
           return MyEntityObjects;
       }

Body:
The get method will be like

var myEntityObjectsQry = await dbContext.Database.ToListAsync();

More references here:
https://www.entityframeworktutorial.net/entityframework6/async-query-and-save.aspx


来源: stackexchange

问:
Whitespace but non-space
I have text type field in database. In this field I have text:

T: Text value

Problem is with sign between T: and Text. It is not space and I have problem with cut it. How can I check what character is it and cut it?

答:
How can I check what character is it?

```<code>python
Python 3.5.1 …
>>>
>>> import unicodedata
>>> astring='T: Text value'
>>> for x in astring: print( x, 'U\{:04x}'.format(ord(x)), unicodedata.name(x, '?'))
...
</code>```

```<code>T U\0054 LATIN CAPITAL LETTER T
: U\003a COLON
  U\00a0 NO-BREAK SPACE
T U\0054 LATIN CAPITAL LETTER T
e U\0065 LATIN SMALL LETTER E
x U\0078 LATIN SMALL LETTER X
t U\0074 LATIN SMALL LETTER T
  U\0020 SPACE
v U\0076 LATIN SMALL LETTER V
a U\0061 LATIN SMALL LETTER A
l U\006c LATIN SMALL LETTER L
u U\0075 LATIN SMALL LETTER U
e U\0065 LATIN SMALL LETTER E
</code>```

ContentLicense: CC BY-SA 3.0

Title: Whitespace but non-space

Body:
How can I check what character is it?

python
Python 3.5.1 …
>>>
>>> import unicodedata
>>> astring='T: Text value'
>>> for x in astring: print( x, 'U\{:04x}'.format(ord(x)), unicodedata.name(x, '?'))
...

T U\0054 LATIN CAPITAL LETTER T
: U\003a COLON
  U\00a0 NO-BREAK SPACE
T U\0054 LATIN CAPITAL LETTER T
e U\0065 LATIN SMALL LETTER E
x U\0078 LATIN SMALL LETTER X
t U\0074 LATIN SMALL LETTER T
  U\0020 SPACE
v U\0076 LATIN SMALL LETTER V
a U\0061 LATIN SMALL LETTER A
l U\006c LATIN SMALL LETTER L
u U\0075 LATIN SMALL LETTER U
e U\0065 LATIN SMALL LETTER E

ContentLicense: CC BY-SA 4.0


问:
How can I set an AWS lambda to be triggered 24hs after the beginning of a process?
I have the follow schema  (using AWS-IoTCore and AWS-Lambdas) that starts upon some MQTT event. At the end of the main process a flag success is saved in the database. This process takes around 5 min. I would like to call a Lambda function 24hs after the beginning of the process to check if the flag exists in the database. How can I set this timeout or delay in the Lambda function without stepfunctions?

答:
There are two possible paths to "wait 24 hours" until execution of an AWS Lambda function.

Using a 'wait' step in AWS Step Functions

AWS Step Functions is ideal for orchestrating multi-step Lambda functions. There is a Wait state that can be triggered, and the flow could then trigger another Lambda function. Step Functions will track each individual request and you can see each execution and their current state. Sounds good!

Schedule your own check

Use Amazon CloudWatch Events to trigger an AWS Lambda function at regular intervals. The Lambda function could query the database to locate records for processes that did not complete successfully. However, since your code needs to find "non-successful" processes, each process would first need to be added to the database (eg at the start of the 'Process' function).

Alternate approach: Only track failures

The architecture in the above diagram stores 'success' in the database, which is then checked 24 hours later. Based on this diagram, it appears as though the only purpose of the database is to track successful processes.

Instead, I would recommend:

Changing the top line to only store 'failed' processes, and the time of their failure (assuming failure can be detected)

Trigger an AWS Lambda function at regular intervals that will:

Check the database

Retrieve failed processes that are older that 24 hours

Submit them for re-processing

Delete the records from the database, or mark them as 'retried' to avoid future retrievals

Basically, the database is used to track failures, rather than successes. The "wait 24 hours" step is replaced with a regular database check for failed processes.

I'm not sure why the systems wants to wait 24 hours before sending a 'success' email, but I presume that is an intentional part of your design.


问:
Force ExpansionPanel to be expanded, when printing
I am using an ExpansionPanel,
where I control the expanded state based on some conditions.

Although, I want the ExpansionPanel to be always expanded, when I am printing (window.print()).

What I intuitively wanted to try was:

```<code>//...

const isPrinting = useMediaQuery("print")
const controlledExpanded = useSomeMethodToControlExpanded()
const expanded = isPrinting || controlledExpanded
return (
  <ExpansionPanel expanded={expanded}>
    {/*...*/}
  </ExpansionPanel>
)
</code>```

Although this won't work because of a bug in browsers:

Maybe somehow override the global styling would help, but I cannot figure out how.

Any ideas?

答:
You can use @media print in your css:

```<code>@media print {
    div.MuiCollapse-container.MuiCollapse-hidden {
        min-height: auto !important;
        height: auto !important;
        visibility: visible !important;
    }
}
</code>```

No need for anything in the react component

Body:
I am using an ExpansionPanel,
where I control the expanded state based on some conditions.

Although, I want the ExpansionPanel to be always expanded, when I am printing (window.print()).

What I intuitively wanted to try was:

//...

const isPrinting = useMediaQuery("print")
const controlledExpanded = useSomeMethodToControlExpanded()
const expanded = isPrinting || controlledExpanded
return (
  <ExpansionPanel expanded={expanded}>
    {/*...*/}
  </ExpansionPanel>
)

Although this won't work because of a bug in browsers:

Maybe somehow override the global styling would help, but I cannot figure out how.

Any ideas?

Body:
You can use @media print in your css:

@media print {
    div.MuiCollapse-container.MuiCollapse-hidden {
        min-height: auto !important;
        height: auto !important;
        visibility: visible !important;
    }
}

No need for anything in the react component


问:
Form for OTP entry with six single-character text fields
I am working on an app in which I have to pass 6 digits OTP through 6 textFields in which you to provide only one character and after that it automatically goes to another textField. I created 6 textFields outlets and used this code. The problem I have is that I want to change the specific textField OTP number but the problem is that if I want to change the OTP number of textfield 4 after tapping cross button it automatically goes to the textfield 3. How can I fix this issue?

The code I used:

```<code>import UIKit

class OneTimePasswordViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var txtOTP1: UITextField!
    @IBOutlet weak var txtOTP2: UITextField!
    @IBOutlet weak var txtOTP3: UITextField!
    @IBOutlet weak var txtOTP4: UITextField!
    @IBOutlet weak var txtOTP5: UITextField!
    @IBOutlet weak var txtOTP6: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        txtOTP1.delegate = self
        txtOTP2.delegate = self
        txtOTP3.delegate = self
        txtOTP4.delegate = self
        txtOTP5.delegate = self
        txtOTP6.delegate = self

       self.txtOTP1.becomeFirstResponder()
    }
}
</code>```

And here is the code for creating logic:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {

    if (range.length == 0){
        if textField == txtOTP1 {txtOTP2?.becomeFirstResponder()}
        if textField == txtOTP2 {txtOTP3?.becomeFirstResponder()}
        if textField == txtOTP3 {txtOTP4?.becomeFirstResponder()}
        if textField == txtOTP4 {txtOTP5?.becomeFirstResponder()}
        if textField == txtOTP5 {txtOTP6?.becomeFirstResponder()}
        if textField == txtOTP6 {txtOTP6?.resignFirstResponder()}
        textField.text? = string
        return false
    }
    else if (range.length == 1) {

        if textField == txtOTP6 {txtOTP5?.becomeFirstResponder()}
        if textField == txtOTP5 {txtOTP4?.becomeFirstResponder()}
        if textField == txtOTP4 {txtOTP3?.becomeFirstResponder()}
        if textField == txtOTP3 {txtOTP2?.becomeFirstResponder()}
        if textField == txtOTP2 {txtOTP1?.becomeFirstResponder()}
        if textField == txtOTP1 {txtOTP1?.resignFirstResponder()}

        textField.text? = ""
        return false
    }
    return true
}
</code>```

答:
You can try My 3rd party library:-
https://github.com/Datt1994/DPOTPView

For Solution:-

In viewDidLoad add tag & delegate to all textfield

```<code>import UIKit

class OneTimePasswordViewController: UIViewController, UITextFieldDelegate {

     @IBOutlet weak var txtOTP1: UITextField!
     @IBOutlet weak var txtOTP2: UITextField!
     @IBOutlet weak var txtOTP3: UITextField!
     @IBOutlet weak var txtOTP4: UITextField!
     @IBOutlet weak var txtOTP5: UITextField!
     @IBOutlet weak var txtOTP6: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        txtOTP1.delegate = self
        txtOTP1.tag = 1000
        txtOTP2.delegate = self
        txtOTP2.tag = 2000
        txtOTP3.delegate = self
        txtOTP3.tag = 3000
        txtOTP4.delegate = self
        txtOTP4.tag = 4000
        txtOTP5.delegate = self
        txtOTP5.tag = 5000
        txtOTP6.delegate = self
        txtOTP6.tag = 6000

       self.txtOTP1.becomeFirstResponder()
   }
}
</code>```

In UITextFieldDelegate extension implement shouldChangeCharactersIn function like below, It will also work with textField.textContentType = .oneTimeCode

```<code>extension OneTimePasswordViewController : UITextFieldDelegate  {

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.trimmingCharacters(in: CharacterSet.whitespaces).count != 0 {
        textField.text = string
        if textField.tag < count*1000 {
            let next = textField.superview?.viewWithTag((textField.tag/1000 + 1)*1000)
            next?.becomeFirstResponder()
        } else if textField.tag == count*1000 {
            textField.resignFirstResponder()
        }
    } else if string.count == 0 { // is backspace
        textField.text = ""
    }

    return false
}

}
</code>```

Body:
I am working on an app in which I have to pass 6 digits OTP through 6 textFields in which you to provide only one character and after that it automatically goes to another textField. I created 6 textFields outlets and used this code. The problem I have is that I want to change the specific textField OTP number but the problem is that if I want to change the OTP number of textfield 4 after tapping cross button it automatically goes to the textfield 3. How can I fix this issue?

The code I used:

import UIKit

class OneTimePasswordViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var txtOTP1: UITextField!
    @IBOutlet weak var txtOTP2: UITextField!
    @IBOutlet weak var txtOTP3: UITextField!
    @IBOutlet weak var txtOTP4: UITextField!
    @IBOutlet weak var txtOTP5: UITextField!
    @IBOutlet weak var txtOTP6: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        txtOTP1.delegate = self
        txtOTP2.delegate = self
        txtOTP3.delegate = self
        txtOTP4.delegate = self
        txtOTP5.delegate = self
        txtOTP6.delegate = self

       self.txtOTP1.becomeFirstResponder()
    }
}

And here is the code for creating logic:

func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {

    if (range.length == 0){
        if textField == txtOTP1 {txtOTP2?.becomeFirstResponder()}
        if textField == txtOTP2 {txtOTP3?.becomeFirstResponder()}
        if textField == txtOTP3 {txtOTP4?.becomeFirstResponder()}
        if textField == txtOTP4 {txtOTP5?.becomeFirstResponder()}
        if textField == txtOTP5 {txtOTP6?.becomeFirstResponder()}
        if textField == txtOTP6 {txtOTP6?.resignFirstResponder()}
        textField.text? = string
        return false
    }
    else if (range.length == 1) {

        if textField == txtOTP6 {txtOTP5?.becomeFirstResponder()}
        if textField == txtOTP5 {txtOTP4?.becomeFirstResponder()}
        if textField == txtOTP4 {txtOTP3?.becomeFirstResponder()}
        if textField == txtOTP3 {txtOTP2?.becomeFirstResponder()}
        if textField == txtOTP2 {txtOTP1?.becomeFirstResponder()}
        if textField == txtOTP1 {txtOTP1?.resignFirstResponder()}

        textField.text? = ""
        return false
    }
    return true
}

Body:
You can try My 3rd party library:-
https://github.com/Datt1994/DPOTPView

For Solution:-

In viewDidLoad add tag & delegate to all textfield

import UIKit

class OneTimePasswordViewController: UIViewController, UITextFieldDelegate {

     @IBOutlet weak var txtOTP1: UITextField!
     @IBOutlet weak var txtOTP2: UITextField!
     @IBOutlet weak var txtOTP3: UITextField!
     @IBOutlet weak var txtOTP4: UITextField!
     @IBOutlet weak var txtOTP5: UITextField!
     @IBOutlet weak var txtOTP6: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        txtOTP1.delegate = self
        txtOTP1.tag = 1000
        txtOTP2.delegate = self
        txtOTP2.tag = 2000
        txtOTP3.delegate = self
        txtOTP3.tag = 3000
        txtOTP4.delegate = self
        txtOTP4.tag = 4000
        txtOTP5.delegate = self
        txtOTP5.tag = 5000
        txtOTP6.delegate = self
        txtOTP6.tag = 6000

       self.txtOTP1.becomeFirstResponder()
   }
}

In UITextFieldDelegate extension implement shouldChangeCharactersIn function like below, It will also work with textField.textContentType = .oneTimeCode

extension OneTimePasswordViewController : UITextFieldDelegate  {

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.trimmingCharacters(in: CharacterSet.whitespaces).count != 0 {
        textField.text = string
        if textField.tag < count*1000 {
            let next = textField.superview?.viewWithTag((textField.tag/1000 + 1)*1000)
            next?.becomeFirstResponder()
        } else if textField.tag == count*1000 {
            textField.resignFirstResponder()
        }
    } else if string.count == 0 { // is backspace
        textField.text = ""
    }

    return false
}

}


问:
Query to extract only records which have failed
I need a help in writing a SQL for the below table. I have a table with two columns (Name and Status). </p>

```<code>Name    Status
Kevin   success
Mark    fail
Mark    success
Mike    success
Yann    fail
Yann    success
George  fail
Boi     Fail
</code>```

<p>From the above table, I would like to extract only records which have failed and also which are failed then succeeded. Basically I would like to exclude the records which are just succeeded. </p>

答:
Just another option is using WITH TIES

Not clear if you want ALL records or just distinct Names

Example

```<code>Declare @YourTable Table ([Name] varchar(50),[Status] varchar(50))
Insert Into @YourTable Values
 ('Kevin','success')
,('Mark','fail')
,('Mark','success')
,('Mike','success')
,('Yann','fail')
,('Yann','success')
,('George','fail')
,('Boi','Fail')

Select top 1 with ties *
 From @YourTable
 Order By min(case when status='Fail' then 0 else 1 end) over (partition by [Name] )
</code>```

Returns

```<code>Name    Status
Boi     Fail
George  fail
Mark    fail
Mark    success
Yann    fail
Yann    success
</code>```

Kevin and Mike are excluded

Body:
I need a help in writing a SQL for the below table. I have a table with two columns (Name and Status).

Name    Status
Kevin   success
Mark    fail
Mark    success
Mike    success
Yann    fail
Yann    success
George  fail
Boi     Fail

From the above table, I would like to extract only records which have failed and also which are failed then succeeded. Basically I would like to exclude the records which are just succeeded.

Body:
Just another option is using WITH TIES

Not clear if you want ALL records or just distinct Names

Example

Declare @YourTable Table ([Name] varchar(50),[Status] varchar(50))
Insert Into @YourTable Values
 ('Kevin','success')
,('Mark','fail')
,('Mark','success')
,('Mike','success')
,('Yann','fail')
,('Yann','success')
,('George','fail')
,('Boi','Fail')

Select top 1 with ties *
 From @YourTable
 Order By min(case when status='Fail' then 0 else 1 end) over (partition by [Name] )

Returns

Name    Status
Boi     Fail
George  fail
Mark    fail
Mark    success
Yann    fail
Yann    success

Kevin and Mike are excluded


问:
How to handle large file uploads in Quarkus
My question is two fold:

I'm looking for a way to implement multipart file uploads on a quarkus application server that allows the programmer access to the uploaded file.
Going through the documentation it seems there is https://quarkus.io/guides/rest-client-multipart, but this doesn't tell me where on the server, the file is stored (if it is at all).

I'd also like to know what's going on under the hood. For large files (>100MB) what would the memory footprint look like?

答:
Quarkus uses the combination of the following properties to manage multipart payloads:

quarkus.http.body.handle-file-uploads=true to determine whether or not to accept multipart requests. According to the docs though, your app will still accept multipart requests regardless of what this is set to.

quarkus.http.body.uploads-directory the relative or absolute path where the uploads should be held

quarkus.http.body.delete-uploaded-files-on-end to control whether uploaded files are cleared at the end of the request.

quarkus.http.body.preallocate-body-buffer =true to set a buffer size to hold the request body, based on the number in Content-Length HTTP header.

I'd also like to know what's going on under the hood. For large files (>100MB) what would the memory footprint look like?

That's an open-ended question that no one can safely prognosticate. You won't know until you try. Your deployment mode (native or JVM) also matters - native mode does serial garbage collection and can cause longer waits while GC happens.


问:
Efficient way of labelling based on start and end position
I have 2 dataframes

```<code>das <- data.frame(val=1:20,
              type =c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C"),
              weigh=c(20,22,23,32,34,54,19,22,24,26,31,34,36,37,51,54,31,35,43,45))

mapper <- data.frame(type=c("A","A","A","A","B","B","B","B","C","C","C","C"),start = c(19,23,27,37   ,17,25,39,50, 17,23,33,39),end = c(23,27,37,55  ,25,39,50,60, 23,33,39,48))
</code>```

The expected output is

```<code>val type weigh labelweight
1    1    A    20    A_19
2    2    A    22    A_19
3    3    A    23    A_23
4    4    A    32    A_27
5    5    A    34    A_27
6    6    A    54    A_37
7    7    B    19    B_17
8    8    B    22    B_17
9    9    B    24    B_17
10  10    B    26    B_25
11  11    B    31    B_25
12  12    B    34    B_25
13  13    B    36    B_25
14  14    B    37    B_25
15  15    B    51    B_50
16  16    B    54    B_50
17  17    C    31    C_23
18  18    C    35    C_33
19  19    C    43    C_39
20  20    C    45    C_39
</code>```

I am able to get the expected output with following code

```<code>p <- left_join(das,mapper)
q <- p%>%filter(weigh>=start & weigh<end)%>%mutate(labelweight= paste0(type,"_",start))
</code>```

The code whatever I came up with is throwing "Error: vector memory exhausted (limit reached?)" when dealing with large datasets.

I am thinking if there is any more efficient way of getting the desired output without doing a join.

答:
The intervals appears to be contiguous. Here is a fast option using rolling join in data.table:

```<code>library(data.table)
setDT(das)[, weight :=
    setDT(mapper)[.SD, on=.(type, start=weigh), roll=Inf, paste(type, x.start, sep="_")]
]
</code>```

If the intervals are not contiguous, you can use a non-equi join:

```<code>setDT(das)[, weight :=
    setDT(mapper)[setDT(das), on=.(type, start<=weigh, end>weigh), paste(type, x.start, sep="_")]
]
</code>```

output:

```<code>    val type weigh weight
 1:   1    A    20   A_19
 2:   2    A    22   A_19
 3:   3    A    23   A_23
 4:   4    A    32   A_27
 5:   5    A    34   A_27
 6:   6    A    54   A_37
 7:   7    B    19   B_17
 8:   8    B    22   B_17
 9:   9    B    24   B_17
10:  10    B    26   B_25
11:  11    B    31   B_25
12:  12    B    34   B_25
13:  13    B    36   B_25
14:  14    B    37   B_25
15:  15    B    51   B_50
16:  16    B    54   B_50
17:  17    C    31   C_23
18:  18    C    35   C_33
19:  19    C    43   C_39
20:  20    C    45   C_39
</code>```

Body:
I have 2 dataframes

das <- data.frame(val=1:20,
              type =c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C"),
              weigh=c(20,22,23,32,34,54,19,22,24,26,31,34,36,37,51,54,31,35,43,45))

mapper <- data.frame(type=c("A","A","A","A","B","B","B","B","C","C","C","C"),start = c(19,23,27,37   ,17,25,39,50, 17,23,33,39),end = c(23,27,37,55  ,25,39,50,60, 23,33,39,48))

The expected output is

val type weigh labelweight
1    1    A    20    A_19
2    2    A    22    A_19
3    3    A    23    A_23
4    4    A    32    A_27
5    5    A    34    A_27
6    6    A    54    A_37
7    7    B    19    B_17
8    8    B    22    B_17
9    9    B    24    B_17
10  10    B    26    B_25
11  11    B    31    B_25
12  12    B    34    B_25
13  13    B    36    B_25
14  14    B    37    B_25
15  15    B    51    B_50
16  16    B    54    B_50
17  17    C    31    C_23
18  18    C    35    C_33
19  19    C    43    C_39
20  20    C    45    C_39

I am able to get the expected output with following code

p <- left_join(das,mapper)
q <- p%>%filter(weigh>=start & weigh<end)%>%mutate(labelweight= paste0(type,"_",start))

The code whatever I came up with is throwing "Error: vector memory exhausted (limit reached?)" when dealing with large datasets.

I am thinking if there is any more efficient way of getting the desired output without doing a join.

Body:
The intervals appears to be contiguous. Here is a fast option using rolling join in data.table:

library(data.table)
setDT(das)[, weight :=
    setDT(mapper)[.SD, on=.(type, start=weigh), roll=Inf, paste(type, x.start, sep="_")]
]

If the intervals are not contiguous, you can use a non-equi join:

setDT(das)[, weight :=
    setDT(mapper)[setDT(das), on=.(type, start<=weigh, end>weigh), paste(type, x.start, sep="_")]
]

output:

    val type weigh weight
 1:   1    A    20   A_19
 2:   2    A    22   A_19
 3:   3    A    23   A_23
 4:   4    A    32   A_27
 5:   5    A    34   A_27
 6:   6    A    54   A_37
 7:   7    B    19   B_17
 8:   8    B    22   B_17
 9:   9    B    24   B_17
10:  10    B    26   B_25
11:  11    B    31   B_25
12:  12    B    34   B_25
13:  13    B    36   B_25
14:  14    B    37   B_25
15:  15    B    51   B_50
16:  16    B    54   B_50
17:  17    C    31   C_23
18:  18    C    35   C_33
19:  19    C    43   C_39
20:  20    C    45   C_39


问:
Mongoose Queries Find
I have table like this:

```<code>"products": [
        {
            "reviews": [],
            "_id": "5ece6d09cab302507c5d147e",
            "category": {
                "_id": "5ece6c07cab302507c5d1478",
                "type": "Marketing",
=
</code>```

And I want to get all products, with 'category.type' == 'Marketing'.

This is working in that way:

```<code>let products = await Product.find({ 'category': '5ece6c07cab302507c5d1478' })
</code>```

But I don't want to use ID for search, but instead word "Marketing".

This returns nothing...

```<code>let products = await Product.find({ 'category.type': 'Marketing' })
</code>```

Pls help

答:
try this out:</p>

```<code>let products = await Product.find({ "category.type": {$eq: "Marketing"} });
</code>```

Title: Mongoose Queries Find

Body:
I have table like this:

"products": [
        {
            "reviews": [],
            "_id": "5ece6d09cab302507c5d147e",
            "category": {
                "_id": "5ece6c07cab302507c5d1478",
                "type": "Marketing",
=

And I want to get all products, with 'category.type' == 'Marketing'.

This is working in that way:

let products = await Product.find({ 'category': '5ece6c07cab302507c5d1478' })

But I don't want to use ID for search, but instead word "Marketing".

This returns nothing...

let products = await Product.find({ 'category.type': 'Marketing' })

Pls help

Body:
try this out:

let products = await Product.find({ "category.type": {$eq: "Marketing"} });


问:
R CMD check doesn't detect my documentation
When I run

```<code>R CMD build mypackage
R CMD check mypackage_1.0.tar.gz
</code>```

I'm getting this warning:

```<code>Undocumented code objects:
  ‘func1’ ‘func2’
</code>```

However, my package structure has these functions documented in the man folder:

```<code>$ ls mypackage
DESCRIPTION  man  NAMESPACE  R  README.md  tests
</code>```

And these functions specifically have documentation:

```<code>$ ll mypackage/man
-rw-r--r-- 1 user user  307 May 24 14:38 func1.Rd
-rw-r--r-- 1 user user  307 May 29 15:38 func2.Rd
</code>```

Which looks like so:

```<code>$ cat mypackage/man/func1.R
\name{ func1 }
\title{ Do func1}
\description{
  This is well documented
  }
</code>```

What am I missing to tell R this is where my documentation is?

答:
You forgot to add an alias.

```<code>$ cat mypackage/man/func1.R
\name{ func1 }
\alias{ func1 }
\title{ Do func1}
\description{
  This is well documented
  }
</code>```

This should do it.

Body:
When I run

R CMD build mypackage
R CMD check mypackage_1.0.tar.gz

I'm getting this warning:

Undocumented code objects:
  ‘func1’ ‘func2’

However, my package structure has these functions documented in the man folder:

$ ls mypackage
DESCRIPTION  man  NAMESPACE  R  README.md  tests

And these functions specifically have documentation:

$ ll mypackage/man
-rw-r--r-- 1 user user  307 May 24 14:38 func1.Rd
-rw-r--r-- 1 user user  307 May 29 15:38 func2.Rd

Which looks like so:

$ cat mypackage/man/func1.R
\name{ func1 }
\title{ Do func1}
\description{
  This is well documented
  }

What am I missing to tell R this is where my documentation is?

Body:
You forgot to add an alias.

$ cat mypackage/man/func1.R
\name{ func1 }
\alias{ func1 }
\title{ Do func1}
\description{
  This is well documented
  }

This should do it.


问:
Laravel multi condition query
I want to search for users previous relations but not sure how to make this logic happen.

Logic

My table has 2 columns from_id to_id (both will get users ids)

I am sending 2 ids to back-end (one as input, another one in request header)

I want to say: whereinput id is from_id and header id is to_idORwhere input id is to_id and header id is from_id` return the result otherwise is null obviously.

Note:
The part that I'm stuck in is and in conditions input id is from_id and header id is to_id OR where input id is to_id and header id is from_id

Code

currently I have half way code which is this:

```<code>public function check(Request $request) {
  // user id from header request (request sender) e.g `1`
  $user = $request->user();
  // second user id (not sure where to use it yet) e.g `4`
  $request->input('receiverId');

  $chat = PrivateChat::where('from_id', $user->id)->orWhere('to_id', $user->id)->first();
}
</code>```

To make it simple

Basically I want return old chat between the 2 ids regardless of who was sender (from_id) and who was receiver (to_id).

Any idea how to make my logic happen?

Update

this is my full code and it always return false while i do have previous chat between users with id 1 and 4.

```<code>public function check(Request $request) {
    $user = $request->user();

    $chat = PrivateChat::where([['from_id', $user->id],['to_id',$request->input('receiverId')]])
    ->orWhere([['from_id', $request->input('receiverId')],['to_id',$user->id]])->first();

    $receiver = User::where('id', $request->input('receiverId'))->first();

    if($chat) {
        return response()->json([
            'data' => new PrivateChatResource($chat),
            'exist' => true,
            'receiver' => new UserResource($receiver),
            'message' => 'Chat data retrieved successfully.'
        ]);
    } else {
        return response()->json([
            'exist' => false,
            'receiver' => new UserResource($receiver),
            'message' => 'Chat data retrieved successfully.'
        ]);
    }
}
</code>```

答:
If i understand correctly your where logic looks like this:

```<code>('from_id' = $user->id  &  'to_id' = $request->input('receiverId'))
|| ('from_id' = $request->input('receiverId')  &  'to_id' = $user->id)
</code>```

You can define multiple conditions in a single where:

```<code>PrivateChat::where([['from_id', $user->id],['to_id',$request->input('receiverId')]])
->orWhere([['from_id', $request->input('receiverId')],['to_id',$user->id]])->first();
</code>```

->first() will return the first record that meets one of the conditions, but if you want  all results you can use ->get().

Title: Laravel multi condition query

Body:
I want to search for users previous relations but not sure how to make this logic happen.

Logic

My table has 2 columns from_id to_id (both will get users ids)

I am sending 2 ids to back-end (one as input, another one in request header)

I want to say: whereinput id is from_id and header id is to_idORwhere input id is to_id and header id is from_id` return the result otherwise is null obviously.

Note:
The part that I'm stuck in is and in conditions input id is from_id and header id is to_id OR where input id is to_id and header id is from_id

Code

currently I have half way code which is this:

public function check(Request $request) {
  // user id from header request (request sender) e.g `1`
  $user = $request->user();
  // second user id (not sure where to use it yet) e.g `4`
  $request->input('receiverId');

  $chat = PrivateChat::where('from_id', $user->id)->orWhere('to_id', $user->id)->first();
}

To make it simple

Basically I want return old chat between the 2 ids regardless of who was sender (from_id) and who was receiver (to_id).

Any idea how to make my logic happen?

Update

this is my full code and it always return false while i do have previous chat between users with id 1 and 4.

public function check(Request $request) {
    $user = $request->user();

    $chat = PrivateChat::where([['from_id', $user->id],['to_id',$request->input('receiverId')]])
    ->orWhere([['from_id', $request->input('receiverId')],['to_id',$user->id]])->first();

    $receiver = User::where('id', $request->input('receiverId'))->first();

    if($chat) {
        return response()->json([
            'data' => new PrivateChatResource($chat),
            'exist' => true,
            'receiver' => new UserResource($receiver),
            'message' => 'Chat data retrieved successfully.'
        ]);
    } else {
        return response()->json([
            'exist' => false,
            'receiver' => new UserResource($receiver),
            'message' => 'Chat data retrieved successfully.'
        ]);
    }
}

Body:
If i understand correctly your where logic looks like this:

('from_id' = $user->id  &  'to_id' = $request->input('receiverId'))
|| ('from_id' = $request->input('receiverId')  &  'to_id' = $user->id)

You can define multiple conditions in a single where:

PrivateChat::where([['from_id', $user->id],['to_id',$request->input('receiverId')]])
->orWhere([['from_id', $request->input('receiverId')],['to_id',$user->id]])->first();

->first() will return the first record that meets one of the conditions, but if you want  all results you can use ->get().


问:
Fatal error: Allowed memory
I tried to activate W3 Total Cache wordpres plugin and got some blank screen with memory error message. After I deactivated all plugins and set the default WP theme, my front page still says :

« Fatal error: Allowed memory size of 262144 bytes exhausted », although my wp-config contains the line : define('WP_MEMORY_LIMIT', '96M');

How is that possible ?

答:
add this in top of wp-config </p>

```<code>ini_set('memory_limit', '-1');
</code>```

Title: Fatal error: Allowed memory

Body:
add this in top of wp-config

ini_set('memory_limit', '-1');


问:
TypeError: This'VARIABLE_NAME' is not a function
I wanna define  to null. Why won't it let me do this? I'm getting a TypeError error. I think there was no such problem with older versions?I want to treat this variable like typescript?</p>

```<code>unsubscribe: null ;

componentDidMount() {
    const user = this.props.uid || Fire.shared.uid;

    this.unsubscribe = Fire.shared.firestore
        .collection("users")
        .doc(user)
        .onSnapshot(doc => {
            this.setState({ user: doc.data() });
        })

}

componentWillUnMount() {   // EDITED
    this.unsubscribe();
}
</code>```

答: componentWillMount gets called before componentDidMount - this is a typo. You meant to write unsubscribe in componentWillUnmount, not componentWillMount

Body:
I wanna define  to null. Why won't it let me do this? I'm getting a TypeError error. I think there was no such problem with older versions?I want to treat this variable like typescript?

unsubscribe: null ;

componentDidMount() {
    const user = this.props.uid || Fire.shared.uid;

    this.unsubscribe = Fire.shared.firestore
        .collection("users")
        .doc(user)
        .onSnapshot(doc => {
            this.setState({ user: doc.data() });
        })

}

componentWillUnMount() {   // EDITED
    this.unsubscribe();
}


问:
How run a script with variable in the name under PowerShell in GitHub workflow / actions
I'm implementing a GitHub workflow and I need to run a batch (*.bat) script under PowerShell with a variable part. This doesn't seem to work. A simple batch script is running fine. But when I try to insert a variable into its name it doesn't

I've tried these  with no success:

```<code>run: |
  $i=2
  call "myscript_$i.bat"
</code>```

```<code>run: |
  $i=2
  .\myscript_$i.bat
</code>```

```<code>run: |
  $i=2
  .\myscript_${env:i}.bat
</code>```

Is there any Obi-Wan who can help on this? )

答:
While your own solution works, Invoke-Expression should generally be avoided.

To invoke a command by a name / path based on a quoted string and/or containing a variable reference or expression, use &, the call operator:

```<code>run |
  $i=2
  & ".\myscript_$i.bat"
</code>```

(In this particular case, you could even omit the enclosing ".)

Body:
I'm implementing a GitHub workflow and I need to run a batch (*.bat) script under PowerShell with a variable part. This doesn't seem to work. A simple batch script is running fine. But when I try to insert a variable into its name it doesn't

I've tried these  with no success:

run: |
  $i=2
  call "myscript_$i.bat"

run: |
  $i=2
  .\myscript_$i.bat

run: |
  $i=2
  .\myscript_${env:i}.bat

Is there any Obi-Wan who can help on this? )

Body:
While your own solution works, Invoke-Expression should generally be avoided.

To invoke a command by a name / path based on a quoted string and/or containing a variable reference or expression, use &, the call operator:

run |
  $i=2
  & ".\myscript_$i.bat"

(In this particular case, you could even omit the enclosing ".)


问:
Kotlin exchange variables in a function "pass by value"
I often have the situation, that I want to change variables var1 to var2 .

But in a function, I cannot change the input parameters. How could i do it with a "function-call"
The variables are sometimes strings, integers oder objects from Android Studio GUI

I do it like this:

```<code>tmp = var1
var1 = var2
var2 = tmp
</code>```

or

```<code>tmp = name1.text.toStirng()
name1.text.toString() = name2.text.toString()
name2.text.toString() = tmp
</code>```

as a  function I think it is not possible

```<code>fun switch_vars(var1:String, var2:String)
</code>```

it does not work.

How can is do it, because i have plenty of such situations

答:
Even for data types that are passed by reference in Kotlin (most everything not primitive), this cannot be achieved by a function of your creation because all parameters are treated as vals, ie they cannot be reassigned.

The options in the thread provided in denvercoder's comment are your best bet.

Body:
I often have the situation, that I want to change variables var1 to var2 .

But in a function, I cannot change the input parameters. How could i do it with a "function-call"
The variables are sometimes strings, integers oder objects from Android Studio GUI

I do it like this:

tmp = var1
var1 = var2
var2 = tmp

or

tmp = name1.text.toStirng()
name1.text.toString() = name2.text.toString()
name2.text.toString() = tmp

as a  function I think it is not possible

fun switch_vars(var1:String, var2:String)

it does not work.

How can is do it, because i have plenty of such situations


问:
Getting error in DBeaver mysql when try to import large sql database file
```<code>    C:\Program Files\MySQL\MySQL Server 5.7\bin\mysql.exe --host=localhost --port=3306 -u root nd7b265_rahetbally
Task 'MySQL script' started at Sun May 31 09:53:09 MST 2020
ERROR 2013 (HY000) at line 118827: Lost connection to MySQL server during query
Task 'MySQL script' finished at Sun May 31 09:53:13 MST 2020
2020-05-31 09:53:13.363 - IO error: Process failed (exit code = 1). See error log.
2020-05-31 09:53:13.363 - java.io.IOException: Process failed (exit code = 1). See error log.
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.executeProcess(AbstractNativeToolHandler.java:182)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.doExecute(AbstractNativeToolHandler.java:237)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.lambda$0(AbstractNativeToolHandler.java:52)
    at org.jkiss.dbeaver.runtime.RunnableContextDelegate.lambda$0(RunnableContextDelegate.java:39)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
</code>```

答:
I solved it by adding these lines

wait_timeout = 28800
interactive_timeout = 28800
max_allowed_packet=100M

under [mysql] section


问:
Angular 8 replacing tags in dynamically inserted content
Is it possible to replace dynamically inserted angular component tags?

I have text like the following which I am getting from an api :

```<code>Testing <app-test></app-test> for <app-test></app-test> dynamically inserting another <app-test></app-test>
</code>```

I have a test component and all I am trying to achieve is for the output from the text component to replace the <app-test></app-test> tags.

In my ts file, I am using DomSanitizer so my tags are not striped out, shown below:

```<code>this.text = this.sanitizer.bypassSecurityTrustHtml("Testing <app-test></app-test> for <app-test></app-test> dynamically inserting another <app-test></app-test>");
</code>```

And in my html I am using one-way binding to display the text, like below:

```<code><div [innerHTML]='text'></div>
</code>```

But the output is just the text without the tags.

答:
You can create a dynamic components by a component ref
In this link you can read about it: https://medium.com/@lukaonik/how-to-create-dynamic-components-in-angular-a2f449acb987

Other solution but not the best is call different components by an ng-swich

Body:
Is it possible to replace dynamically inserted angular component tags?

I have text like the following which I am getting from an api :

Testing <app-test></app-test> for <app-test></app-test> dynamically inserting another <app-test></app-test>

I have a test component and all I am trying to achieve is for the output from the text component to replace the <app-test></app-test> tags.

In my ts file, I am using DomSanitizer so my tags are not striped out, shown below:

this.text = this.sanitizer.bypassSecurityTrustHtml("Testing <app-test></app-test> for <app-test></app-test> dynamically inserting another <app-test></app-test>");

And in my html I am using one-way binding to display the text, like below:

But the output is just the text without the tags.


问:
How to get the length of map of Json in flutter
I'm working on improving a quiz app.
I get the data from Json file into my project as mydata.

```<code>class quizpage extends StatefulWidget {
  var mydata;

  quizpage({Key key, @required this.mydata}) : super(key: key);
  @override
  _quizpageState createState() => _quizpageState(mydata);
}

class _quizpageState extends State<quizpage> {
  final mydata;
  _quizpageState(this.mydata);
</code>```

I want to find the length of the elements inside my son file.
This is the demo data inside Json file.

```<code>[
    {
        "1": "What's your name?",
        "2": "Which function finds out the Variable type in Python ?",
        "3": "Which of the following keyword is used to define a function ",

    },
    {
        "1": {
            "a": "mon",
            "b": "monmon",
            "c": "monmonmon",
            "d": "monmonmon"
        },
        "2": {
            "a": "monmon",
            "b": "mon",
            "c": "monmonmon",
            "d": "monmonmon"
        },
        "3": {
            "a": "monmonmon",
            "b": "monmon",
            "c": "mon",
            "d": "monmonmon"
        },

    },
    {
        "1": "mon",
        "2": "mon",
        "3": "mon",

    }

]
</code>```

I want to check the length of the Json map
When I press. after mydata[0].   it doesn't show me length.

```<code>void nextquestion() {
    setState(() {
      if (i < mydata[0].length) {

        i++;
      }
</code>```

Here it throws an error (i < mydata[0].length)
What should I do?

答:
You have to assign your variable to the type you want to use.</p>

```<code>(mydata[0] as Map<String, dynamic>).length
</code>```

Body:
I'm working on improving a quiz app.
I get the data from Json file into my project as mydata.

class quizpage extends StatefulWidget {
  var mydata;

  quizpage({Key key, @required this.mydata}) : super(key: key);
  @override
  _quizpageState createState() => _quizpageState(mydata);
}

class _quizpageState extends State<quizpage> {
  final mydata;
  _quizpageState(this.mydata);

I want to find the length of the elements inside my son file.
This is the demo data inside Json file.

[
    {
        "1": "What's your name?",
        "2": "Which function finds out the Variable type in Python ?",
        "3": "Which of the following keyword is used to define a function ",

    },
    {
        "1": {
            "a": "mon",
            "b": "monmon",
            "c": "monmonmon",
            "d": "monmonmon"
        },
        "2": {
            "a": "monmon",
            "b": "mon",
            "c": "monmonmon",
            "d": "monmonmon"
        },
        "3": {
            "a": "monmonmon",
            "b": "monmon",
            "c": "mon",
            "d": "monmonmon"
        },

    },
    {
        "1": "mon",
        "2": "mon",
        "3": "mon",

    }

]

I want to check the length of the Json map
When I press. after mydata[0].   it doesn't show me length.

void nextquestion() {
    setState(() {
      if (i < mydata[0].length) {

        i++;
      }

Here it throws an error (i < mydata[0].length)
What should I do?

Body:
You have to assign your variable to the type you want to use.

(mydata[0] as Map<String, dynamic>).length


问:
AWS SSH access key generation procedure and putting on EC2
I wonder how does AWS EC2 puts the SSH public key on the instance and provides private key to end user. I mean to know how this process of creating an SSH key and putting it on EC2 instance is automated.

答:
The keypair is passed to the instance via the EC2 Metadata Service.

From Amazon EC2 key pairs and Linux instances - Amazon Elastic Compute Cloud:

The public key that you specified when you launched an instance is also available to you through its instance metadata. To view the public key that you specified when launching the instance, use the following command from your instance:

curl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key

An 'on first boot' script pre-installed on the AMI uses the above method to retrieve the public key and then inserts into the /home/ec2-user/.ssh/authorized_keys file.

Please note this method is slightly different if using Instance Metadata v2, as specified on the linked page.


问:
Tagging and Analysing a Search Query
I'm developing a search engine which functions taking the semantics of data into account, unlike the usual keyword based index. I managed to develop a reasonable index for the search using metadata extraction methods and RDF, but I have difficulty in using such methods on the search query itself since the search query is very much shorter that the actual data. any idea how to perform a successful tagging of a search query, using similar methods, natural language processing, etc. ?

Thank You!

答:
You need to build semantic tree. It will based on the combination of keywords.

For example, automobile -->vehicle --> car this relation technical aspect of car.  travel --

hire/rent-->vehicle-->car this is something related to travel and rent a car.
  In this case MongoDB will help you a lot.

Title: Tagging and Analysing a Search Query


问:
Find element index with AVX2 - code optimization
I am fiddling with AVX2 to write some code able to search for 32 bits hash in an array with 14 entries and return the index of the found entry.

Because most likely the vast majority of the hits will be within the first 8 entries of the array this code can already be improved adding the usage of __builtin_expect this is not my priority right now.

While the array of hashes (in the code represented by the variable hashes) will always be 14 entries long, it's contained in a struct of this kind

```<code>typedef struct chain_ring chain_ring_t;
struct chain_ring {
    uint32_t hashes[14];
    chain_ring_t* next;
    ...other stuff...
} __attribute__((aligned(16)))
</code>```

Here the code

```<code>int8_t hash32_find_14_avx2(uint32_t hash, volatile uint32_t* hashes) {
    uint32_t compacted_result_mask, leading_zeroes;
    __m256i cmp_vector, ring_vector, result_mask_vector;
    int8_t found_index = -1;

    if (hashes[0] == hash) {
        return 0;
    }

    for(uint8_t base_index = 0; base_index < 14; base_index += 8) {
        cmp_vector = _mm256_set1_epi32(hash);
        ring_vector = _mm256_stream_load_si256((__m256i*) (hashes + base_index));

        result_mask_vector = _mm256_cmpeq_epi32(ring_vector, cmp_vector);
        compacted_result_mask = _mm256_movemask_epi8(result_mask_vector);

        if (compacted_result_mask != 0) {
            leading_zeroes = 32 - __builtin_clz(compacted_result_mask);
            found_index = base_index + (leading_zeroes >> 2u) - 1;
            break;
        }
    }

    return found_index > 13 ? -1 : found_index;
}
</code>```

The logic, briefly explained, it searches on the first 8 entries and then on the second 8 entries. If the found index is greater than 13 it means that it found a match with some stuff that wasn't part of the array and therefore has to be considered not-matching.

Notes:

to speedup the load (from aligned memory) I am using _mm256_stream_load_si256

because of the above mentioned, I need to check if by any chance the returned value is greater than 13 and I don't really like this specific part too much, should I use _mm256_maskload_epi32?

I am using a for-loop to avoid repeating the code, gcc of course will unroll the loop

I am using __builtin_clz but I am compiling the code with -mlzcnt because AMD cpus, as far I have read, are way slower to run the bsr instruction, gcc is using lzcnt instead of bsr with the flag

the very first IF introduced a delay of about 0.30 ns in average but in average it reduce by 0.6ns the time for the first match

the code is only for 64bit machines

at some point I will need to optimize this code for aarch64

Here a nice link to godbolt for the produced assembly
https://godbolt.org/z/5bxbN6

I implemented the SSE version as well (it's in the gist) but the logic is the same, although I am not really sure it's performance worth

For reference, I built a simple linear search function and compared the performances with it using the google-benchmark lib

```<code>int8_t hash32_find_14_loop(uint32_t hash, volatile uint32_t* hashes) {
    for(uint8_t index = 0; index <= 14; index++) {
        if (hashes[index] == hash) {
            return index;
        }
    }

    return -1;
}
</code>```

The full code is available at this url https://gist.github.com/danielealbano/9fcbc1ff0a42cc9ad61be205366bdb5f

Apart from the necessary flags for the google-benchmark library, I am compiling it using -avx2 -avx -msse4 -O3 -mbmi -mlzcnt

A bench for each element is performed (I wanted to compare the loop vs the alternatives)

```<code>----------------------------------------------------------------------------------------------------
Benchmark                                                          Time             CPU   Iterations
----------------------------------------------------------------------------------------------------
bench_template_hash32_find_14_loop/0/iterations:100000000       0.610 ns        0.610 ns    100000000
bench_template_hash32_find_14_loop/1/iterations:100000000        1.16 ns         1.16 ns    100000000
bench_template_hash32_find_14_loop/2/iterations:100000000        1.18 ns         1.18 ns    100000000
bench_template_hash32_find_14_loop/3/iterations:100000000        1.19 ns         1.19 ns    100000000
bench_template_hash32_find_14_loop/4/iterations:100000000        1.28 ns         1.28 ns    100000000
bench_template_hash32_find_14_loop/5/iterations:100000000        1.26 ns         1.26 ns    100000000
bench_template_hash32_find_14_loop/6/iterations:100000000        1.52 ns         1.52 ns    100000000
bench_template_hash32_find_14_loop/7/iterations:100000000        2.15 ns         2.15 ns    100000000
bench_template_hash32_find_14_loop/8/iterations:100000000        1.66 ns         1.66 ns    100000000
bench_template_hash32_find_14_loop/9/iterations:100000000        1.67 ns         1.67 ns    100000000
bench_template_hash32_find_14_loop/10/iterations:100000000       1.90 ns         1.90 ns    100000000
bench_template_hash32_find_14_loop/11/iterations:100000000       1.89 ns         1.89 ns    100000000
bench_template_hash32_find_14_loop/12/iterations:100000000       2.13 ns         2.13 ns    100000000
bench_template_hash32_find_14_loop/13/iterations:100000000       2.20 ns         2.20 ns    100000000
bench_template_hash32_find_14_loop/14/iterations:100000000       2.32 ns         2.32 ns    100000000
bench_template_hash32_find_14_loop/15/iterations:100000000       2.53 ns         2.53 ns    100000000
bench_template_hash32_find_14_sse/0/iterations:100000000        0.531 ns        0.531 ns    100000000
bench_template_hash32_find_14_sse/1/iterations:100000000         1.42 ns         1.42 ns    100000000
bench_template_hash32_find_14_sse/2/iterations:100000000         2.53 ns         2.53 ns    100000000
bench_template_hash32_find_14_sse/3/iterations:100000000         1.45 ns         1.45 ns    100000000
bench_template_hash32_find_14_sse/4/iterations:100000000         2.26 ns         2.26 ns    100000000
bench_template_hash32_find_14_sse/5/iterations:100000000         1.90 ns         1.90 ns    100000000
bench_template_hash32_find_14_sse/6/iterations:100000000         1.90 ns         1.90 ns    100000000
bench_template_hash32_find_14_sse/7/iterations:100000000         1.93 ns         1.93 ns    100000000
bench_template_hash32_find_14_sse/8/iterations:100000000         2.07 ns         2.07 ns    100000000
bench_template_hash32_find_14_sse/9/iterations:100000000         2.05 ns         2.05 ns    100000000
bench_template_hash32_find_14_sse/10/iterations:100000000        2.08 ns         2.08 ns    100000000
bench_template_hash32_find_14_sse/11/iterations:100000000        2.08 ns         2.08 ns    100000000
bench_template_hash32_find_14_sse/12/iterations:100000000        2.55 ns         2.55 ns    100000000
bench_template_hash32_find_14_sse/13/iterations:100000000        2.53 ns         2.53 ns    100000000
bench_template_hash32_find_14_sse/14/iterations:100000000        2.37 ns         2.37 ns    100000000
bench_template_hash32_find_14_sse/15/iterations:100000000        2.59 ns         2.59 ns    100000000
bench_template_hash32_find_14_avx2/0/iterations:100000000       0.537 ns        0.537 ns    100000000
bench_template_hash32_find_14_avx2/1/iterations:100000000        1.37 ns         1.37 ns    100000000
bench_template_hash32_find_14_avx2/2/iterations:100000000        1.38 ns         1.38 ns    100000000
bench_template_hash32_find_14_avx2/3/iterations:100000000        1.36 ns         1.36 ns    100000000
bench_template_hash32_find_14_avx2/4/iterations:100000000        1.37 ns         1.37 ns    100000000
bench_template_hash32_find_14_avx2/5/iterations:100000000        1.38 ns         1.38 ns    100000000
bench_template_hash32_find_14_avx2/6/iterations:100000000        1.40 ns         1.40 ns    100000000
bench_template_hash32_find_14_avx2/7/iterations:100000000        1.39 ns         1.39 ns    100000000
bench_template_hash32_find_14_avx2/8/iterations:100000000        1.99 ns         1.99 ns    100000000
bench_template_hash32_find_14_avx2/9/iterations:100000000        2.02 ns         2.02 ns    100000000
bench_template_hash32_find_14_avx2/10/iterations:100000000       1.98 ns         1.98 ns    100000000
bench_template_hash32_find_14_avx2/11/iterations:100000000       1.98 ns         1.98 ns    100000000
bench_template_hash32_find_14_avx2/12/iterations:100000000       2.03 ns         2.03 ns    100000000
bench_template_hash32_find_14_avx2/13/iterations:100000000       1.98 ns         1.98 ns    100000000
bench_template_hash32_find_14_avx2/14/iterations:100000000       1.96 ns         1.96 ns    100000000
bench_template_hash32_find_14_avx2/15/iterations:100000000       1.97 ns         1.97 ns    100000000
</code>```

Thanks for any suggestion!

--- UPDATE

I have updated the gist with the branchless implementation made by @chtz and replaced __lzcnt32 with _tzcnt_u32, I had to slightly change the behaviour to consider not-found when 32 is returned instead of -1 but doesn't really matter.

The CPU on which they ran is an Intel Core i7 8700 (6c/12t, 3.20GHZ).

The bench uses cpu-pinning, uses more thread than physical or logical cpu cores and performs some additional operations, specifically a for loop, so there is overhead but it's the same between the two tests so it should impact them in the same way.

If you want to run the test you need to tune the CPU_CORE_LOGICAL_COUNT to manually match the number of the logical cpu cores of your cpu.

It's interesting to see how the performance improvement jumps from +17% to +41% when there is more contention (from single thread to 64 threads).
I have ran a few more tests with 128 and 256 threads seeing up to a +60% speed improvement when using AVX2, but I haven't included the numbers below.

(bench_template_hash32_find_14_avx2 is benching the branchless version, I have shortened the name to make the post more readable)

```<code>------------------------------------------------------------------------------------------
Benchmark                                                                 CPU   Iterations
------------------------------------------------------------------------------------------
bench_template_hash32_find_14_loop/iterations:10000000/threads:1      45.2 ns     10000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:2      50.4 ns     20000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:4      52.1 ns     40000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:8      70.9 ns     80000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:16     86.8 ns    160000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:32     87.3 ns    320000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:64     92.9 ns    640000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:1      38.4 ns     10000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:2      42.1 ns     20000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:4      46.5 ns     40000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:8      52.6 ns     80000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:16     60.0 ns    160000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:32     62.1 ns    320000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:64     65.8 ns    640000000
</code>```

答:
You can implement this completely without branches, by comparing two overlapping parts of your array, bit-OR them together and get the last bit position with a single lzcnt. Also, using vmovmskps instead of vpmovmskb saves dividing the result by 4 (I'm not sure if this causes any domain-crossing latency, though).

```<code>int8_t hash32_find_14_avx2(uint32_t hash, volatile uint32_t* hashes) {
    uint32_t compacted_result_mask = 0;
    __m256i cmp_vector = _mm256_set1_epi32(hash);
    for(uint8_t base_index = 0; base_index < 12; base_index += 6) {
        __m256i ring_vector = _mm256_loadu_si256((__m256i*) (hashes + base_index));

        __m256i result_mask_vector = _mm256_cmpeq_epi32(ring_vector, cmp_vector);
        compacted_result_mask |= _mm256_movemask_ps(_mm256_castsi256_ps(result_mask_vector)) << (base_index);
    }
    int32_t leading_zeros = __lzcnt32(compacted_result_mask);
    return (31 - leading_zeros);
}
</code>```

As Peter already pointed out in the comments, in most cases _mm256_stream_load_si256 is worse than normal loads. Also, be aware that when using unaligned loads with gcc you must compile with -mno-avx256-split-unaligned-load (or in fact just with -march=native) -- see this post for details.

Godbolt-Link with simple test code (note that the behavior would be different for the loop- and the avx2-version, if multiple matching values are in the array):
https://godbolt.org/z/2jNWqK

Body:
I am fiddling with AVX2 to write some code able to search for 32 bits hash in an array with 14 entries and return the index of the found entry.

Because most likely the vast majority of the hits will be within the first 8 entries of the array this code can already be improved adding the usage of __builtin_expect this is not my priority right now.

While the array of hashes (in the code represented by the variable hashes) will always be 14 entries long, it's contained in a struct of this kind

typedef struct chain_ring chain_ring_t;
struct chain_ring {
    uint32_t hashes[14];
    chain_ring_t* next;
    ...other stuff...
} __attribute__((aligned(16)))

Here the code

int8_t hash32_find_14_avx2(uint32_t hash, volatile uint32_t* hashes) {
    uint32_t compacted_result_mask, leading_zeroes;
    __m256i cmp_vector, ring_vector, result_mask_vector;
    int8_t found_index = -1;

    if (hashes[0] == hash) {
        return 0;
    }

    for(uint8_t base_index = 0; base_index < 14; base_index += 8) {
        cmp_vector = _mm256_set1_epi32(hash);
        ring_vector = _mm256_stream_load_si256((__m256i*) (hashes + base_index));

        result_mask_vector = _mm256_cmpeq_epi32(ring_vector, cmp_vector);
        compacted_result_mask = _mm256_movemask_epi8(result_mask_vector);

        if (compacted_result_mask != 0) {
            leading_zeroes = 32 - __builtin_clz(compacted_result_mask);
            found_index = base_index + (leading_zeroes >> 2u) - 1;
            break;
        }
    }

    return found_index > 13 ? -1 : found_index;
}

The logic, briefly explained, it searches on the first 8 entries and then on the second 8 entries. If the found index is greater than 13 it means that it found a match with some stuff that wasn't part of the array and therefore has to be considered not-matching.

Notes:

to speedup the load (from aligned memory) I am using _mm256_stream_load_si256

because of the above mentioned, I need to check if by any chance the returned value is greater than 13 and I don't really like this specific part too much, should I use _mm256_maskload_epi32?

I am using a for-loop to avoid repeating the code, gcc of course will unroll the loop

I am using __builtin_clz but I am compiling the code with -mlzcnt because AMD cpus, as far I have read, are way slower to run the bsr instruction, gcc is using lzcnt instead of bsr with the flag

the very first IF introduced a delay of about 0.30 ns in average but in average it reduce by 0.6ns the time for the first match

the code is only for 64bit machines

at some point I will need to optimize this code for aarch64

Here a nice link to godbolt for the produced assembly
https://godbolt.org/z/5bxbN6

I implemented the SSE version as well (it's in the gist) but the logic is the same, although I am not really sure it's performance worth

For reference, I built a simple linear search function and compared the performances with it using the google-benchmark lib

int8_t hash32_find_14_loop(uint32_t hash, volatile uint32_t* hashes) {
    for(uint8_t index = 0; index <= 14; index++) {
        if (hashes[index] == hash) {
            return index;
        }
    }

    return -1;
}

The full code is available at this url https://gist.github.com/danielealbano/9fcbc1ff0a42cc9ad61be205366bdb5f

Apart from the necessary flags for the google-benchmark library, I am compiling it using -avx2 -avx -msse4 -O3 -mbmi -mlzcnt

A bench for each element is performed (I wanted to compare the loop vs the alternatives)

----------------------------------------------------------------------------------------------------
Benchmark                                                          Time             CPU   Iterations
----------------------------------------------------------------------------------------------------
bench_template_hash32_find_14_loop/0/iterations:100000000       0.610 ns        0.610 ns    100000000
bench_template_hash32_find_14_loop/1/iterations:100000000        1.16 ns         1.16 ns    100000000
bench_template_hash32_find_14_loop/2/iterations:100000000        1.18 ns         1.18 ns    100000000
bench_template_hash32_find_14_loop/3/iterations:100000000        1.19 ns         1.19 ns    100000000
bench_template_hash32_find_14_loop/4/iterations:100000000        1.28 ns         1.28 ns    100000000
bench_template_hash32_find_14_loop/5/iterations:100000000        1.26 ns         1.26 ns    100000000
bench_template_hash32_find_14_loop/6/iterations:100000000        1.52 ns         1.52 ns    100000000
bench_template_hash32_find_14_loop/7/iterations:100000000        2.15 ns         2.15 ns    100000000
bench_template_hash32_find_14_loop/8/iterations:100000000        1.66 ns         1.66 ns    100000000
bench_template_hash32_find_14_loop/9/iterations:100000000        1.67 ns         1.67 ns    100000000
bench_template_hash32_find_14_loop/10/iterations:100000000       1.90 ns         1.90 ns    100000000
bench_template_hash32_find_14_loop/11/iterations:100000000       1.89 ns         1.89 ns    100000000
bench_template_hash32_find_14_loop/12/iterations:100000000       2.13 ns         2.13 ns    100000000
bench_template_hash32_find_14_loop/13/iterations:100000000       2.20 ns         2.20 ns    100000000
bench_template_hash32_find_14_loop/14/iterations:100000000       2.32 ns         2.32 ns    100000000
bench_template_hash32_find_14_loop/15/iterations:100000000       2.53 ns         2.53 ns    100000000
bench_template_hash32_find_14_sse/0/iterations:100000000        0.531 ns        0.531 ns    100000000
bench_template_hash32_find_14_sse/1/iterations:100000000         1.42 ns         1.42 ns    100000000
bench_template_hash32_find_14_sse/2/iterations:100000000         2.53 ns         2.53 ns    100000000
bench_template_hash32_find_14_sse/3/iterations:100000000         1.45 ns         1.45 ns    100000000
bench_template_hash32_find_14_sse/4/iterations:100000000         2.26 ns         2.26 ns    100000000
bench_template_hash32_find_14_sse/5/iterations:100000000         1.90 ns         1.90 ns    100000000
bench_template_hash32_find_14_sse/6/iterations:100000000         1.90 ns         1.90 ns    100000000
bench_template_hash32_find_14_sse/7/iterations:100000000         1.93 ns         1.93 ns    100000000
bench_template_hash32_find_14_sse/8/iterations:100000000         2.07 ns         2.07 ns    100000000
bench_template_hash32_find_14_sse/9/iterations:100000000         2.05 ns         2.05 ns    100000000
bench_template_hash32_find_14_sse/10/iterations:100000000        2.08 ns         2.08 ns    100000000
bench_template_hash32_find_14_sse/11/iterations:100000000        2.08 ns         2.08 ns    100000000
bench_template_hash32_find_14_sse/12/iterations:100000000        2.55 ns         2.55 ns    100000000
bench_template_hash32_find_14_sse/13/iterations:100000000        2.53 ns         2.53 ns    100000000
bench_template_hash32_find_14_sse/14/iterations:100000000        2.37 ns         2.37 ns    100000000
bench_template_hash32_find_14_sse/15/iterations:100000000        2.59 ns         2.59 ns    100000000
bench_template_hash32_find_14_avx2/0/iterations:100000000       0.537 ns        0.537 ns    100000000
bench_template_hash32_find_14_avx2/1/iterations:100000000        1.37 ns         1.37 ns    100000000
bench_template_hash32_find_14_avx2/2/iterations:100000000        1.38 ns         1.38 ns    100000000
bench_template_hash32_find_14_avx2/3/iterations:100000000        1.36 ns         1.36 ns    100000000
bench_template_hash32_find_14_avx2/4/iterations:100000000        1.37 ns         1.37 ns    100000000
bench_template_hash32_find_14_avx2/5/iterations:100000000        1.38 ns         1.38 ns    100000000
bench_template_hash32_find_14_avx2/6/iterations:100000000        1.40 ns         1.40 ns    100000000
bench_template_hash32_find_14_avx2/7/iterations:100000000        1.39 ns         1.39 ns    100000000
bench_template_hash32_find_14_avx2/8/iterations:100000000        1.99 ns         1.99 ns    100000000
bench_template_hash32_find_14_avx2/9/iterations:100000000        2.02 ns         2.02 ns    100000000
bench_template_hash32_find_14_avx2/10/iterations:100000000       1.98 ns         1.98 ns    100000000
bench_template_hash32_find_14_avx2/11/iterations:100000000       1.98 ns         1.98 ns    100000000
bench_template_hash32_find_14_avx2/12/iterations:100000000       2.03 ns         2.03 ns    100000000
bench_template_hash32_find_14_avx2/13/iterations:100000000       1.98 ns         1.98 ns    100000000
bench_template_hash32_find_14_avx2/14/iterations:100000000       1.96 ns         1.96 ns    100000000
bench_template_hash32_find_14_avx2/15/iterations:100000000       1.97 ns         1.97 ns    100000000

Thanks for any suggestion!

--- UPDATE

I have updated the gist with the branchless implementation made by @chtz and replaced __lzcnt32 with _tzcnt_u32, I had to slightly change the behaviour to consider not-found when 32 is returned instead of -1 but doesn't really matter.

The CPU on which they ran is an Intel Core i7 8700 (6c/12t, 3.20GHZ).

The bench uses cpu-pinning, uses more thread than physical or logical cpu cores and performs some additional operations, specifically a for loop, so there is overhead but it's the same between the two tests so it should impact them in the same way.

If you want to run the test you need to tune the CPU_CORE_LOGICAL_COUNT to manually match the number of the logical cpu cores of your cpu.

It's interesting to see how the performance improvement jumps from +17% to +41% when there is more contention (from single thread to 64 threads).
I have ran a few more tests with 128 and 256 threads seeing up to a +60% speed improvement when using AVX2, but I haven't included the numbers below.

(bench_template_hash32_find_14_avx2 is benching the branchless version, I have shortened the name to make the post more readable)

------------------------------------------------------------------------------------------
Benchmark                                                                 CPU   Iterations
------------------------------------------------------------------------------------------
bench_template_hash32_find_14_loop/iterations:10000000/threads:1      45.2 ns     10000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:2      50.4 ns     20000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:4      52.1 ns     40000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:8      70.9 ns     80000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:16     86.8 ns    160000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:32     87.3 ns    320000000
bench_template_hash32_find_14_loop/iterations:10000000/threads:64     92.9 ns    640000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:1      38.4 ns     10000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:2      42.1 ns     20000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:4      46.5 ns     40000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:8      52.6 ns     80000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:16     60.0 ns    160000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:32     62.1 ns    320000000
bench_template_hash32_find_14_avx2/iterations:10000000/threads:64     65.8 ns    640000000

Body:
You can implement this completely without branches, by comparing two overlapping parts of your array, bit-OR them together and get the last bit position with a single lzcnt. Also, using vmovmskps instead of vpmovmskb saves dividing the result by 4 (I'm not sure if this causes any domain-crossing latency, though).

int8_t hash32_find_14_avx2(uint32_t hash, volatile uint32_t* hashes) {
    uint32_t compacted_result_mask = 0;
    __m256i cmp_vector = _mm256_set1_epi32(hash);
    for(uint8_t base_index = 0; base_index < 12; base_index += 6) {
        __m256i ring_vector = _mm256_loadu_si256((__m256i*) (hashes + base_index));

        __m256i result_mask_vector = _mm256_cmpeq_epi32(ring_vector, cmp_vector);
        compacted_result_mask |= _mm256_movemask_ps(_mm256_castsi256_ps(result_mask_vector)) << (base_index);
    }
    int32_t leading_zeros = __lzcnt32(compacted_result_mask);
    return (31 - leading_zeros);
}

As Peter already pointed out in the comments, in most cases _mm256_stream_load_si256 is worse than normal loads. Also, be aware that when using unaligned loads with gcc you must compile with -mno-avx256-split-unaligned-load (or in fact just with -march=native) -- see this post for details.

Godbolt-Link with simple test code (note that the behavior would be different for the loop- and the avx2-version, if multiple matching values are in the array):
https://godbolt.org/z/2jNWqK


问:
Generate sequence of 1 11 111 1111 for every n iterations
I am trying to achieve this

```<code>1*1 = 1
11*11 = 121
111 * 111 = 12321
</code>```

for every n input given by the user. (n=3) in the case of this example.

This is what I have so far:

```<code>i_times = int(input('Enter number of times: '))
i = 1
values = []

while (i <= i_times):
    a = (([1] * i))
    b = (([1] * i))
    value = a * b
    values.append(values)

    i = +1

for a in values:
    print(a)
</code>```

Any insights? as I get this error:

```<code>value = a * b
TypeError: can't multiply sequence by non-int of type 'list'
</code>```

答:
Example of Producing

```<code>def times(n):
  " Produces ['1', '11', ...] "
  return ['1'*k for k in range(1, n+1)]

i_times = int(input('Enter number of times: '))

for x in times(i_times):
  print(f'{x} x {x} = {int(x)**2}')
</code>```

Output

```<code>Enter number of times: 5
1 x 1 = 1
11 x 11 = 121
111 x 111 = 12321
1111 x 1111 = 1234321
11111 x 11111 = 123454321
</code>```

Body:
I am trying to achieve this

1*1 = 1
11*11 = 121
111 * 111 = 12321

for every n input given by the user. (n=3) in the case of this example.

This is what I have so far:

i_times = int(input('Enter number of times: '))
i = 1
values = []

while (i <= i_times):
    a = (([1] * i))
    b = (([1] * i))
    value = a * b
    values.append(values)

    i = +1

for a in values:
    print(a)

Any insights? as I get this error:

value = a * b
TypeError: can't multiply sequence by non-int of type 'list'

Body:
Example of Producing

def times(n):
  " Produces ['1', '11', ...] "
  return ['1'*k for k in range(1, n+1)]

i_times = int(input('Enter number of times: '))

for x in times(i_times):
  print(f'{x} x {x} = {int(x)**2}')

Output

Enter number of times: 5
1 x 1 = 1
11 x 11 = 121
111 x 111 = 12321
1111 x 1111 = 1234321
11111 x 11111 = 123454321


问:
adding and substracting time in Javascript
I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;
```

<p>Respectively give:</p>

```"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207
```

Why does subtraction work, but not addition? How can I add time?

Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)

答:
Why does subtraction work, but not addition? How can I add time?

As user120242 says in the first comment, the addition operator (+) is overloaded and does either arithmetic addition or string addition (concatenation) depending on the types of values used (see Runtime Semantics: ApplyStringOrNumericBinaryOperator).

So in the case of:

```<code>new Date() + 300000;
</code>```

the Date is first converted to a primitive, which returns a string. If either the left or right operands are stings, they're both converted to string and then the two strings are concatenated.

In the case of:

```<code>new Date() - 300000;
</code>```

the subtraction operator (-) coerces values to number, so the Date is converted to its time value and the right hand value is subtracted.

If you want to add 300 seconds to a Date, you can use one of the following:

let d = new Date();
let ms = 300000;

// Add 3 seconds to the time value, creates a new Date
let e = new Date(d.getTime() + ms)
console.log(e.toString());

// As above but use unary operator + to coerce Date to number
let f = new Date(+d + ms)
console.log(f.toString());

// Use get/setMilliseconds, modifies the Date
d.setMilliseconds(d.getMilliseconds() + ms)
console.log(d.toString());

// Use Date.now
let g = new Date(Date.now() + ms);
console.log(g.toString());```

Body:
I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

Respectively give:

"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207

Why does subtraction work, but not addition? How can I add time?

Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)

Body:
Why does subtraction work, but not addition? How can I add time?

As user120242 says in the first comment, the addition operator (+) is overloaded and does either arithmetic addition or string addition (concatenation) depending on the types of values used (see Runtime Semantics: ApplyStringOrNumericBinaryOperator).

So in the case of:

new Date() + 300000;

the Date is first converted to a primitive, which returns a string. If either the left or right operands are stings, they're both converted to string and then the two strings are concatenated.

In the case of:

new Date() - 300000;

the subtraction operator (-) coerces values to number, so the Date is converted to its time value and the right hand value is subtracted.

If you want to add 300 seconds to a Date, you can use one of the following:

let d = new Date();
let ms = 300000;

// Add 3 seconds to the time value, creates a new Date
let e = new Date(d.getTime() + ms)
console.log(e.toString());

// As above but use unary operator + to coerce Date to number
let f = new Date(+d + ms)
console.log(f.toString());

// Use get/setMilliseconds, modifies the Date
d.setMilliseconds(d.getMilliseconds() + ms)
console.log(d.toString());

// Use Date.now
let g = new Date(Date.now() + ms);
console.log(g.toString());


问:
Write down user input in a text file
i tryed it with a basic html code like :

```<code>  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" value="Submit">
</form>
</code>```

but then the input is saved like fname=John&lname=Doe

I wrote a script in python that gets the file xxx/xxx/display.txt
when i use the basic html input function, the text will get saved as fname =john & sname=rober
what i woud need is the string to get saved as john rober

how can i write the input down in the txt file without = and & , and how do i save it in the file, while overwriting everything previus in the txt file?

答:
For that you need your js-code to be server side. I'd reccoment Node.js for that.

Than we need to format the input with js:

```<code>// Requiring fs module in which writeFile function is defined:
const fs = require('fs');

var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var fullname = fname + lname;

// data which will write in a file
let data = fullname;

// Write "data" in "file.txt":
fs.writeFile('file.txt', data, (err) => {
    // In case of an error trhow err:
    if (err) throw err;
})
</code>```

Title: Write down user input in a text file

Body:
i tryed it with a basic html code like :

  First name:

  <input type="text" id="fname" name="fname" value="John">

  Last name:

  <input type="text" id="lname" name="lname" value="Doe">

  <input type="submit" value="Submit">
</form>

but then the input is saved like fname=John&lname=Doe

I wrote a script in python that gets the file xxx/xxx/display.txt
when i use the basic html input function, the text will get saved as fname =john & sname=rober
what i woud need is the string to get saved as john rober

how can i write the input down in the txt file without = and & , and how do i save it in the file, while overwriting everything previus in the txt file?

Body:
For that you need your js-code to be server side. I'd reccoment Node.js for that.

Than we need to format the input with js:

// Requiring fs module in which writeFile function is defined:
const fs = require('fs');

var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var fullname = fname + lname;

// data which will write in a file
let data = fullname;

// Write "data" in "file.txt":
fs.writeFile('file.txt', data, (err) => {
    // In case of an error trhow err:
    if (err) throw err;
})


问:
Implementation onClick in FirestoreRecyclerAdapter to open a new Activity
In my app I have a recyclerView with elements from a Firestore database. I want by clicking on an element in the recyclerView (which is inside a fragment) to pass the data of the element to another activity. I've tried several solutions but none seem to work and I'm stuck. Please help me.

Adapter Class

```<code>public class InfoElementAdapter extends FirestoreRecyclerAdapter<InfoElement, InfoElementAdapter.InfoElementHolder> {

String urlImg;
public InfoElementAdapter(@NonNull FirestoreRecyclerOptions<InfoElement> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull InfoElementHolder holder, int position, @NonNull InfoElement model) {
    holder.textViewNomeRest.setText(model.getNome());
    holder.textViewDescrRest.setText(model.getDescrizione());
    urlImg = model.getUrlImg();
    Glide.with(holder.itemView.getContext()).load(urlImg).into(holder.imageView);
}

@NonNull
@Override
public InfoElementHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_single, parent, false );
    return new InfoElementHolder(v) ;
}

class InfoElementHolder extends RecyclerView.ViewHolder {

    TextView textViewNomeRest;
    TextView textViewDescrRest;
    ImageView imageView;
    public InfoElementHolder(@NonNull View itemView) {
        super(itemView);
        textViewNomeRest = itemView.findViewById(R.id.txt_v_nome);
        textViewDescrRest = itemView.findViewById(R.id.txt_v_descrizione);
        imageView = itemView.findViewById(R.id.imageV);
    }
}
</code>```

}

Fragment with the recyclerView

```<code>public class RestaurantFragment extends Fragment {

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference restaurantRef = db.collection("restaurant_db");

private InfoElementAdapter adapter;

private View view;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_restaurant, container, false);

    setUpRecyclerView();

    return view;
}

private void setUpRecyclerView() {
    Query query = restaurantRef.orderBy("nome", Query.Direction.ASCENDING);

    FirestoreRecyclerOptions<InfoElement> options = new FirestoreRecyclerOptions.Builder<InfoElement>()
            .setQuery(query, InfoElement.class)
            .build();

    adapter = new InfoElementAdapter(options);

    RecyclerView recyclerView = view.findViewById(R.id.firestore_list1);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(Tools.getGridSpanCount(getActivity()), StaggeredGridLayoutManager.VERTICAL));
    recyclerView.addItemDecoration(new Tools.SpacingItemDecoration(Tools.getGridSpanCount(getActivity()), Tools.dpToPx(getActivity(), 4),true));
    recyclerView.setAdapter(adapter);
}

@Override
public void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
public void onStop() {
    super.onStop();
    if (adapter != null) {
        adapter.stopListening();
    }
}
</code>```

}

InfoElement Class

```<code>public class InfoElement {

private String nome;
private String descrizione;
private String urlImg;

public InfoElement() {
}

public InfoElement(String nome, String descrizione, String urlImg) {
    this.nome = nome;
    this.descrizione = descrizione;
    this.urlImg =  urlImg;
}

public void setNome(String nome) {
    this.nome = nome;
}

public void setDescrizione(String descrizione) {
    this.descrizione = descrizione;
}

public String getUrlImg() {
    return urlImg;
}

public void setUrlImg(String urlImg) {
    this.urlImg = urlImg;
}

public String getNome() {
    return nome;
}

public String getDescrizione() {
    return descrizione;
}
</code>```

}

答:
You can change onBindViewHolder by setting up a click listener for the ViewHolder itemView, and add your data object with putExtra, and retrieve it with getIntent().getSerializableExtra at the target activity.

```<code>@Override
protected void onBindViewHolder(@NonNull InfoElementHolder holder, int position, @NonNull InfoElement model) {
    holder.textViewNomeRest.setText(model.getNome());
    holder.textViewDescrRest.setText(model.getDescrizione());
    urlImg = model.getUrlImg();
    Glide.with(holder.itemView.getContext()).load(urlImg).into(holder.imageView);

    holder.itemView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent (v.getContext(), ActivityB.class);
            intent.putExtra("MyData", myData);
            startActivity(intent);
        }
    });
}
</code>```

To retrieve the data at the target Activity

```<code>getIntent().getSerializableExtra("MyData");
</code>```

Body:
In my app I have a recyclerView with elements from a Firestore database. I want by clicking on an element in the recyclerView (which is inside a fragment) to pass the data of the element to another activity. I've tried several solutions but none seem to work and I'm stuck. Please help me.

Adapter Class

public class InfoElementAdapter extends FirestoreRecyclerAdapter<InfoElement, InfoElementAdapter.InfoElementHolder> {

String urlImg;
public InfoElementAdapter(@NonNull FirestoreRecyclerOptions<InfoElement> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull InfoElementHolder holder, int position, @NonNull InfoElement model) {
    holder.textViewNomeRest.setText(model.getNome());
    holder.textViewDescrRest.setText(model.getDescrizione());
    urlImg = model.getUrlImg();
    Glide.with(holder.itemView.getContext()).load(urlImg).into(holder.imageView);
}

@NonNull
@Override
public InfoElementHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_single, parent, false );
    return new InfoElementHolder(v) ;
}

class InfoElementHolder extends RecyclerView.ViewHolder {

    TextView textViewNomeRest;
    TextView textViewDescrRest;
    ImageView imageView;
    public InfoElementHolder(@NonNull View itemView) {
        super(itemView);
        textViewNomeRest = itemView.findViewById(R.id.txt_v_nome);
        textViewDescrRest = itemView.findViewById(R.id.txt_v_descrizione);
        imageView = itemView.findViewById(R.id.imageV);
    }
}

}

Fragment with the recyclerView

public class RestaurantFragment extends Fragment {

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference restaurantRef = db.collection("restaurant_db");

private InfoElementAdapter adapter;

private View view;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_restaurant, container, false);

    setUpRecyclerView();

    return view;
}

private void setUpRecyclerView() {
    Query query = restaurantRef.orderBy("nome", Query.Direction.ASCENDING);

    FirestoreRecyclerOptions<InfoElement> options = new FirestoreRecyclerOptions.Builder<InfoElement>()
            .setQuery(query, InfoElement.class)
            .build();

    adapter = new InfoElementAdapter(options);

    RecyclerView recyclerView = view.findViewById(R.id.firestore_list1);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(Tools.getGridSpanCount(getActivity()), StaggeredGridLayoutManager.VERTICAL));
    recyclerView.addItemDecoration(new Tools.SpacingItemDecoration(Tools.getGridSpanCount(getActivity()), Tools.dpToPx(getActivity(), 4),true));
    recyclerView.setAdapter(adapter);
}

@Override
public void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
public void onStop() {
    super.onStop();
    if (adapter != null) {
        adapter.stopListening();
    }
}

}

InfoElement Class

public class InfoElement {

private String nome;
private String descrizione;
private String urlImg;

public InfoElement() {
}

public InfoElement(String nome, String descrizione, String urlImg) {
    this.nome = nome;
    this.descrizione = descrizione;
    this.urlImg =  urlImg;
}

public void setNome(String nome) {
    this.nome = nome;
}

public void setDescrizione(String descrizione) {
    this.descrizione = descrizione;
}

public String getUrlImg() {
    return urlImg;
}

public void setUrlImg(String urlImg) {
    this.urlImg = urlImg;
}

public String getNome() {
    return nome;
}

public String getDescrizione() {
    return descrizione;
}

}

Body:
You can change onBindViewHolder by setting up a click listener for the ViewHolder itemView, and add your data object with putExtra, and retrieve it with getIntent().getSerializableExtra at the target activity.

@Override
protected void onBindViewHolder(@NonNull InfoElementHolder holder, int position, @NonNull InfoElement model) {
    holder.textViewNomeRest.setText(model.getNome());
    holder.textViewDescrRest.setText(model.getDescrizione());
    urlImg = model.getUrlImg();
    Glide.with(holder.itemView.getContext()).load(urlImg).into(holder.imageView);

    holder.itemView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent (v.getContext(), ActivityB.class);
            intent.putExtra("MyData", myData);
            startActivity(intent);
        }
    });
}

To retrieve the data at the target Activity

getIntent().getSerializableExtra("MyData");


问:
Contour in Python
How Z is calcutalted in

```<code>from matplotlib.pyplot import contour

contour([X, Y,] Z, [levels], **kwargs)
</code>```

to draw a contour?

I know that Z means: The height values over which the contour is drawn.

But is it drawn by calculating a standard deviation or something like that?

An average between each point I have?

答:
Z represents a quantity dependent on both X and Y axes. If X and Y represent a plane, Z can be thought of as a surface, whose point height depends on the X and Y coordinates of that given point. The contour is a "top view" of that surface, a projection. An example are the contour lines which report the heights of the mountains (Z) as longitude (X) and latitude (Y) change.

The contour function of matplotlib, as you wrote it, plots the values expressed in the Z variable (two-dimensional numpy.ndarray, as X and Y) as they are, without further processing. The relationship between Z and X and Y is defined outside the plot function.

I report an example below which, perhaps it may be useful:

```<code># IMPORT
import numpy as np
import matplotlib.pyplot as pl

# INPUT
N = 100
x_min = 0
x_max = 10
y_min = 0
y_max = 10
z_min = 0
z_max = 50
z_step = 1
red = '#de7677'

# DEFINE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)

# CALCULATE ZZ AS A FUNCTION OF XX AND YY, FOR ESAMPLE, THEIR SUM
ZZ = YY + XX

# PLOT THE CONTOUR
fig, ax = pl.subplots(figsize = (10, 10))

cont = ax.contour(XX,
                  YY,
                  ZZ,
                  levels = np.arange(z_min, z_max + z_step, z_step),
                  colors = red)

# SET THE CONTOUR LABELS
pl.clabel(cont, fmt = '%d')

# SET THE X AND Y LABEL
ax.set_xlabel('X')
ax.set_ylabel('Y')

pl.show()
</code>```

Title: Contour in Python

Body:
How Z is calcutalted in

from matplotlib.pyplot import contour

contour([X, Y,] Z, [levels], **kwargs)

to draw a contour?

I know that Z means: The height values over which the contour is drawn.

But is it drawn by calculating a standard deviation or something like that?

An average between each point I have?

Body:
Z represents a quantity dependent on both X and Y axes. If X and Y represent a plane, Z can be thought of as a surface, whose point height depends on the X and Y coordinates of that given point. The contour is a "top view" of that surface, a projection. An example are the contour lines which report the heights of the mountains (Z) as longitude (X) and latitude (Y) change.

The contour function of matplotlib, as you wrote it, plots the values expressed in the Z variable (two-dimensional numpy.ndarray, as X and Y) as they are, without further processing. The relationship between Z and X and Y is defined outside the plot function.

I report an example below which, perhaps it may be useful:

# IMPORT
import numpy as np
import matplotlib.pyplot as pl

# INPUT
N = 100
x_min = 0
x_max = 10
y_min = 0
y_max = 10
z_min = 0
z_max = 50
z_step = 1
red = '#de7677'

# DEFINE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)

# CALCULATE ZZ AS A FUNCTION OF XX AND YY, FOR ESAMPLE, THEIR SUM
ZZ = YY + XX

# PLOT THE CONTOUR
fig, ax = pl.subplots(figsize = (10, 10))

cont = ax.contour(XX,
                  YY,
                  ZZ,
                  levels = np.arange(z_min, z_max + z_step, z_step),
                  colors = red)

# SET THE CONTOUR LABELS
pl.clabel(cont, fmt = '%d')

# SET THE X AND Y LABEL
ax.set_xlabel('X')
ax.set_ylabel('Y')

pl.show()


问:
android wallpaper changed
Hi I set a android wallpaper through bitmap.
But Now I want to remove this .How can I remove this??
Can anyone have better Idea.I try wallpaper.clear(); but it is not working .

SO please Help me .

Thanks and Regards,
Md Maidul Islam

答:
wallpaperManager = WallpaperManager.getInstance(this);
                wallpaperManager.clear();

this will return the android default image

Title: android wallpaper changed


问:
Packages imported in Jupyter Notebook not working in Anaconda Prompt
I am importing libraries which I installed using pip install .. to Jupyter Notebook using the anaconda distribution, which is working.
Next I am tryin to import the same libraries in VS Code and running it using Anaconda prompt. I am getting error messages like: ModuleNotFoundError: No module named 'spacy'

I don't understand why it would work in Jupyter notebook but not using VS Code, aren't they both using the Anaconda distribution?

EDIT:
I tried using Sublime text editor and got the same error. When using the Anaconda Prompt and running 'pip list' I get a list of all packages including spacy, but when running the code I get an error "No module named 'spacy'"

答: Usually, this mistake happens if you didn't select the appropriate environment. To switch to anaconda environment in VSCode. Use the "Python: Select Interpreter" command from the Command Palette (Ctrl+Shift+P) then Select the specific environment. You can find more detail in VSCode documentation</p>


问:
standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker
When I am running my docker image on windows 10. I am getting this error:

```<code>standard_init_linux.go:190: exec user process caused "no such file or directory"
</code>```

my docker file is:

```<code>FROM openjdk:8

EXPOSE 8080

VOLUME /tmp

ADD appagent.tar.gz /opt/app-agent
ADD services.jar app.jar
ADD run.sh /run.sh

# Install compiler and perl stuff
RUN apt-get update
RUN apt-get install -y build-essential
RUN apt-get install -y gcc-multilib
RUN apt-get install -y perl

# Install Percona Toolkit
RUN apt-get install --yes percona-toolkit
RUN ["chmod", "+x", "/run.sh"]
ENTRYPOINT ["/run.sh"]
</code>```

and the script is start with #!/bin/sh

```<code>#!/bin/sh
set -e

JAVA_OPTS="-Dfile.encoding=UTF-8 -Djava.security.egd=file:/dev/urandom"

if [ "${APPD_APP_NAME}" != "" ]; then
JAVA_AGENT="-javaagent:/opt/app-agent/javaagent.jar
fi

exec java ${JVM_OPTS} ${JAVA_OPTS} ${JAVA_AGENT} -jar /app.jar
</code>```

Tried method1:
Tried changing #!/bin/sh to #!/bin/bash but getting same error.

Tried method2:
added dos2unix in docker file

```<code>RUN apt-get install -y dos2unix
RUN dos2unix /run.sh
</code>```

答:
Suppose you face this issue while running your go binary with in alpine container.  Export the following variable before building your bin

```<code># CGO has to be disabled for alpine
export CGO_ENABLED=0
</code>```

Then go build

Body:
When I am running my docker image on windows 10. I am getting this error:

standard_init_linux.go:190: exec user process caused "no such file or directory"

my docker file is:

FROM openjdk:8

EXPOSE 8080

VOLUME /tmp

ADD appagent.tar.gz /opt/app-agent
ADD services.jar app.jar
ADD run.sh /run.sh

# Install compiler and perl stuff
RUN apt-get update
RUN apt-get install -y build-essential
RUN apt-get install -y gcc-multilib
RUN apt-get install -y perl

# Install Percona Toolkit
RUN apt-get install --yes percona-toolkit
RUN ["chmod", "+x", "/run.sh"]
ENTRYPOINT ["/run.sh"]

and the script is start with #!/bin/sh

#!/bin/sh
set -e

JAVA_OPTS="-Dfile.encoding=UTF-8 -Djava.security.egd=file:/dev/urandom"

if [ "${APPD_APP_NAME}" != "" ]; then
JAVA_AGENT="-javaagent:/opt/app-agent/javaagent.jar
fi

exec java ${JVM_OPTS} ${JAVA_OPTS} ${JAVA_AGENT} -jar /app.jar

Tried method1:
Tried changing #!/bin/sh to #!/bin/bash but getting same error.

Tried method2:
added dos2unix in docker file

RUN apt-get install -y dos2unix
RUN dos2unix /run.sh

Body:
Suppose you face this issue while running your go binary with in alpine container.  Export the following variable before building your bin

# CGO has to be disabled for alpine
export CGO_ENABLED=0

Then go build