问:
How to get err, stderr from execSync()?
In node 12, execSync can return stdout, e.g.

```<code>const execSync = require('child_process').execSync;

const stdout = execSync('ls');
console.log(`stdout: ${stdout}`);
</code>```

But how to get err and stderr ?
In the callback of child_process.exec, you have all 3.

I can use async way, but prefer to use execSync() if it's easier.

答:
Nodejs docs says:

The child_process.execSync() method is generally identical to
child_process.exec() with the exception that the method will not
return until the child process has fully closed. When a timeout has
been encountered and killSignal is sent, the method won't return until
the process has completely exited. If the child process intercepts and
handles the SIGTERM signal and doesn't exit, the parent process will
wait until the child process has exited.

If the process times out or has a non-zero exit code, this method will
throw. The Error object will contain the entire result from
child_process.spawnSync() as below

```<code>Returns: <Object>

pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.
</code>```

When method throw, the above object will be available in catch block as error object. For example:

```<code>const { execSync }=  require('child_process');

try {
  let res= execSync('ps')
   console.log("NO ERROR")
   console.log(res.toString())

}
catch (err){
  console.log("output", err)
  console.log("sdterr",err.stderr.toString())
}
</code>```

Unlike the spawn method, it does not return the child process instance but the stdout result as a buffer. Also, check stdio option param to the method.

stdio  |  Child's stdio configuration. stderr by
default will be output to the parent process' stderr unless stdio is
specified. Default: 'pipe'.

```<code>const { execSync }  = require('child_process');

try {
const result = execSync('ls . *.blah', {
  // stdio: [
  //   0, // Use parent's stdin for child.
  //   0, // use parent's stdout for child.
  //   0, // use parent's stderr for child .
  // ],
});
} catch(err){

}

process.stderr.on('data',()=>{
  console.log("stderr",data);
})
</code>```

Title: How to get err, stderr from execSync()?

Body:
In node 12, execSync can return stdout, e.g.

const execSync = require('child_process').execSync;

const stdout = execSync('ls');
console.log(`stdout: ${stdout}`);

But how to get err and stderr ?
In the callback of child_process.exec, you have all 3.

I can use async way, but prefer to use execSync() if it's easier.

Body:
Nodejs docs says:

The child_process.execSync() method is generally identical to
child_process.exec() with the exception that the method will not
return until the child process has fully closed. When a timeout has
been encountered and killSignal is sent, the method won't return until
the process has completely exited. If the child process intercepts and
handles the SIGTERM signal and doesn't exit, the parent process will
wait until the child process has exited.

If the process times out or has a non-zero exit code, this method will
throw. The Error object will contain the entire result from
child_process.spawnSync() as below

Returns: <Object>

pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.

When method throw, the above object will be available in catch block as error object. For example:

const { execSync }=  require('child_process');

try {
  let res= execSync('ps')
   console.log("NO ERROR")
   console.log(res.toString())

}
catch (err){
  console.log("output", err)
  console.log("sdterr",err.stderr.toString())
}

Unlike the spawn method, it does not return the child process instance but the stdout result as a buffer. Also, check stdio option param to the method.

stdio  |  Child's stdio configuration. stderr by
default will be output to the parent process' stderr unless stdio is
specified. Default: 'pipe'.

const { execSync }  = require('child_process');

try {
const result = execSync('ls . *.blah', {
  // stdio: [
  //   0, // Use parent's stdin for child.
  //   0, // use parent's stdout for child.
  //   0, // use parent's stderr for child .
  // ],
});
} catch(err){

}

process.stderr.on('data',()=>{
  console.log("stderr",data);
})


来源: stackexchange

问:
How to open .ipynb files in IntelliJ?
I have IntelliJ IDEA 2019.2.4 Community edition. I want to open existing .ipynb files however IntlliJ failes to open them as .ipynb but only as txt. </p>

答:
The Intellij documentation has a page on Jupyter notebook support.
On this page you'll find that this is only available when you have the Python plugin installed, which is only supported in IntelliJ Ultimate (and thus not in the community edition).

The same goes for PyCharm (docs), where notebooks are only supported in the professional edition.

ContentLicense: CC BY-SA 4.0

Title: How to open .ipynb files in IntelliJ?


问:
Connect Four game - understanding how array keeps always the same length
I'm a self learner, please bear with me.
So I'm following this tutorial on how to code a connect4 game and there's two things I'm definitely not getting

1 - every time I click on a cell I call the changeColor() and push to an empty array that specific cell. I dont get how the array always keeps only one cell.. it always has same length. Shouldn't it be adding each cell I click on to the array?

2 - in the stylesheet I defined that every cell would have the background color of white and when applying a if/ else condition as "if the cell is white then do something" the person in the tutorial defined in the js file once again that each cell has to have the background color of white in order for this condition to work
This does not make much sense to me because if its already defined in the stylesheet why does it not work unless I define it again in the js file?

Any help is much appreciated :)
codepen : https://codepen.io/mullerz/pen/WNremXo?editors=1111

tableCell.forEach(el => {
    el.addEventListener("click", changeColor);

    el.style.backgroundColor = 'white'
})

function changeColor(e){
    let column = e.target.cellIndex;
    let row = [];
    for(let i = tableRow.length-1 ; i > -1; i--){

        if (tableRow[i].children[column].style.backgroundColor == 'white'){
          row.push(tableRow[i].children[column])

          console.log(row)

            if (currentPlayer === 1){
                row[0].style.backgroundColor = 'red';
                playerTurn.style.color = player1Color;
                return currentPlayer = 2;
            }
            else{
                row[0].style.backgroundColor = 'yellow';
                playerTurn.style.color = player2Color;
                return currentPlayer = 1;
            }
        }

    }

}

```

答:
Starting with 2.

A cell has the class slot, which sets the background colour to white, but the element itself also has a style object as a property, but this object has nothing set.

When rendering the style, the browser does so from broadest to narrowest (then !important things). Style classes are broader than style applied directly to an element. For example if you have this css:

.notred
{
  color: black;
}
```

<p>And this element:</p>

<pre class="lang-html prettyprint-override"><code><p style="color:red" class="notred">this text would be red</p>
</code>```

The element's text will be red, despite the class saying it should be black.

Your code is using a check on the element's style property to make sure the cell is empty, so it has to set the style property otherwise the value is an empty string. In fact, you could change the code so that it checks for an empty string in the property rather than setting each background.

Back to 1:

The row is in fact a column. The code looks at each row in the table, checking the column number for the cell that was clicked. If the background colour of the cell in that row & column is white then it's added to the row array. This way the last cell that's added to row is the first available cell in that column.

The row variable is redeclared each time the function is called, so it is empty each time the function is called. When a function is called all variables that are declared in it are set back to their initial values. Beware global variables, because that doesn't happen with them.

If you fill up a column with red and yellow, then click on the column again, you should get an index out of range error, because the row will be empty.

Body:
Starting with 2.

A cell has the class slot, which sets the background colour to white, but the element itself also has a style object as a property, but this object has nothing set.

When rendering the style, the browser does so from broadest to narrowest (then !important things). Style classes are broader than style applied directly to an element. For example if you have this css:

.notred
{
  color: black;
}

And this element:

<p style="color:red" class="notred">this text would be red</p>

The element's text will be red, despite the class saying it should be black.

Your code is using a check on the element's style property to make sure the cell is empty, so it has to set the style property otherwise the value is an empty string. In fact, you could change the code so that it checks for an empty string in the property rather than setting each background.

Back to 1:

The row is in fact a column. The code looks at each row in the table, checking the column number for the cell that was clicked. If the background colour of the cell in that row & column is white then it's added to the row array. This way the last cell that's added to row is the first available cell in that column.

The row variable is redeclared each time the function is called, so it is empty each time the function is called. When a function is called all variables that are declared in it are set back to their initial values. Beware global variables, because that doesn't happen with them.

If you fill up a column with red and yellow, then click on the column again, you should get an index out of range error, because the row will be empty.


问:
How to check particular file is exist in our cellphone's "Download" Directory
I have created one android app in which I have provided features of download attachment and I want to change the text of the download button from Download to View once the file is downloaded or already present in the Downloads directory of my mobile. For this, I need code in Kotlin to check whether a particular file is present in the Download directory or not.

答:
```<code>If you want to look the file which you have already saved.
</code>```

create a variable and save the file Path at the time of Saving file.
When tried to save another file, get the previous one name and compare in this case if same name it will provde an error.

File is already saved in the internal storage.

```<code>    if (PdfForSmartCartridges.sFilePAATh != "") {

if(PdfForSmartCartridges.sFilePAATh!="NewPath"){
                        val myFile = File(PdfForSmartCartridges.sFilePAATh)
                        val intent = Intent(Intent.ACTION_VIEW)
                        intent.setDataAndType(
                            Uri.fromFile(myFile),
                            context.getString(R.string.application_pdf)
                        )
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        context.startActivity(intent)
}
                    }
</code>```

Body:
If you want to look the file which you have already saved.

create a variable and save the file Path at the time of Saving file.
When tried to save another file, get the previous one name and compare in this case if same name it will provde an error.

File is already saved in the internal storage.

    if (PdfForSmartCartridges.sFilePAATh != "") {

if(PdfForSmartCartridges.sFilePAATh!="NewPath"){
                        val myFile = File(PdfForSmartCartridges.sFilePAATh)
                        val intent = Intent(Intent.ACTION_VIEW)
                        intent.setDataAndType(
                            Uri.fromFile(myFile),
                            context.getString(R.string.application_pdf)
                        )
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        context.startActivity(intent)
}
                    }


问:
Why does this code rewrite the dictionaries in a list every time a loop happens? (I end up with a list of the same dictionaries)
I'm creating a very simple program as a learning experience. I'm going to try to explain what I expect from the program. First I generate 5 dictionaries, that have random values assigned to each key.

This works just fine, I can print the created random dictionary after each loop. Now my problem is, that I want to be able to access each one of the 5 random dictionaries later, so I want to create a new indexed dictionary for each loop (fox1, fox2, fox3,...etc.) This is my attempt of the code:

```<code>from random import random, uniform

foxlist = list()

fox = {
    "tame": 0,
    "int": 0,
    "gen": 0,
}

txt = "Fox {}: "

for i in range(5):

    foxlist.append("fox" + format(i+1))
    foxlist[i] = {}

    for x in fox:
        att = uniform(0.0, 0.3)
        fox[x] = round(att, 2)

    foxlist[i] = fox

    print(txt.format(i+1))
    print(fox)

print(foxlist)
</code>```

Now if you run the program, you notice that the final foxlist is indeed a list of dictionaries, however each item in the list is the same dictionary - it rewrites all the previous items each loop. It also doesn't include the indexed fox1,fox2,... Any tips on how I could save each dictionary for a later access?

答:
fox is a variable defined outside the loop, and so is the same object on every iteration of the loop. On each iteration, you change the value of some fields in fox, but always in that same object.

To resolve this, make a different object on each iteration, perhaps by copying a single initial object.

Also, foxlist.append("fox" + format(i+1)) and foxlist[i] = {} have no effect and should be removed. In each of these, the value in the list is immediately overwritten.

```<code>...
foxbase = {
    "tame": 0,
    "int": 0,
    "gen": 0,
}
...
for i in range(5):
    fox=dict(foxbase)
    foxlist.append("fox" + format(i+1)) # This has no effect, delete
    ...
    foxlist[i] = {}  # This has no effect, delete
    ...
    foxlist[i] = fox
    ...
</code>```

Body:
I'm creating a very simple program as a learning experience. I'm going to try to explain what I expect from the program. First I generate 5 dictionaries, that have random values assigned to each key.

This works just fine, I can print the created random dictionary after each loop. Now my problem is, that I want to be able to access each one of the 5 random dictionaries later, so I want to create a new indexed dictionary for each loop (fox1, fox2, fox3,...etc.) This is my attempt of the code:

from random import random, uniform

foxlist = list()

fox = {
    "tame": 0,
    "int": 0,
    "gen": 0,
}

txt = "Fox {}: "

for i in range(5):

    foxlist.append("fox" + format(i+1))
    foxlist[i] = {}

    for x in fox:
        att = uniform(0.0, 0.3)
        fox[x] = round(att, 2)

    foxlist[i] = fox

    print(txt.format(i+1))
    print(fox)

print(foxlist)

Now if you run the program, you notice that the final foxlist is indeed a list of dictionaries, however each item in the list is the same dictionary - it rewrites all the previous items each loop. It also doesn't include the indexed fox1,fox2,... Any tips on how I could save each dictionary for a later access?

Body:
fox is a variable defined outside the loop, and so is the same object on every iteration of the loop. On each iteration, you change the value of some fields in fox, but always in that same object.

To resolve this, make a different object on each iteration, perhaps by copying a single initial object.

Also, foxlist.append("fox" + format(i+1)) and foxlist[i] = {} have no effect and should be removed. In each of these, the value in the list is immediately overwritten.

...
foxbase = {
    "tame": 0,
    "int": 0,
    "gen": 0,
}
...
for i in range(5):
    fox=dict(foxbase)
    foxlist.append("fox" + format(i+1)) # This has no effect, delete
    ...
    foxlist[i] = {}  # This has no effect, delete
    ...
    foxlist[i] = fox
    ...


问:
Is there anyway in python to retrieve a line from a .txt file randomly, then print it and do this multiple times without repeating the same one?
currently, I can only randomly select a line. but I don't know how to prevent it from being repeated. how would I do this?</p>

```<code>  Proxy = None
  for line in fileinput.input("file.path"):
      if random.randrange(fileinput.lineno()) == 0:
        Proxy = line
</code>```

答:
I would consider selecting the line number and then removing it from the source, which would work until you run out of samples.
Either that or memoization can help you ignore already selected samples.</p>

Body:
currently, I can only randomly select a line. but I don't know how to prevent it from being repeated. how would I do this?

  Proxy = None
  for line in fileinput.input("file.path"):
      if random.randrange(fileinput.lineno()) == 0:
        Proxy = line


问:
Maintaining medium-sized to large JS-heavy web apps
What's the best way to deal with lots of JS in a web front end? Google's Closure compiler can compile and minify JS, which is good for production -- but annoying to have to recompile every time I make a change, and annoying to debug.

What's the best way to be able to organise my JS into many files?

答:
Maybe this one will help

How to automate JavaScript files compression with YUI Compressor?

ContentLicense: CC BY-SA 3.0


问:
This application failed to start because no Qt platform plugin could be initialized
I am stuck trying to run a very simple Python script, getting this error:

```<code>qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py
</code>```

The script code is:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()
</code>```

However this Notebook code works in JupyterLab:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()
</code>```

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!

答: Through many trial and error, for me it works for uninstalling and installing numpy and opencv.

Body:
I am stuck trying to run a very simple Python script, getting this error:

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py

The script code is:

import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()

However this Notebook code works in JupyterLab:

import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!


问:
Could Not Connect strophe js connection after DISCONNECTED status
Currently I have integrating strophe in my chat application.Its working fine until user is online
But, when i try to switch the another wifi connection in my system, strophe sends the DISCONNECTED
I don't have any idea to make it to reconnect automatically in such situation. Please help me to fix this issue.

答:
If you are using BOSH to connect to your server then you can add keepalive to your connection string

```<code>new Strophe.Connection(this._xmppConnectionsString, { 'keepalive': true })
</code>```

If you are using Web Sockets to connect then you need to write a setInterval after the initial connection success.

```<code>    setInterval(function(){
                    this._xmppConnection.send($pres().tree());
                }, 12000);
</code>```

This should solve your problem.

Body:
If you are using BOSH to connect to your server then you can add keepalive to your connection string

new Strophe.Connection(this._xmppConnectionsString, { 'keepalive': true })

If you are using Web Sockets to connect then you need to write a setInterval after the initial connection success.

    setInterval(function(){
                    this._xmppConnection.send($pres().tree());
                }, 12000);

This should solve your problem.


问:
Android: what is the simplest way to mask a shape onto a View?
I would like to create a circular map fragment view

```<code>    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:transitionName="@string/map"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="200dp"
        android:layout_height="200dp"
        tools:context="com.example.gyang.android.MapActivity"
        class="com.google.android.gms.maps.SupportMapFragment"/>
</code>```

Currently my fragment is a big square. What is the easiest way to turn this into a circle?

答:
For me simplest to make middle transparent shape was by constructing outside part with views: topBox, rightBox, bottomBox, leftBox and leaving middle as blank.
I also needed to have rounded corners, for this I used SVG images to simulate corners of transparent middle shape.

Body:
I would like to create a circular map fragment view

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:transitionName="@string/map"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="200dp"
        android:layout_height="200dp"
        tools:context="com.example.gyang.android.MapActivity"
        class="com.google.android.gms.maps.SupportMapFragment"/>

Currently my fragment is a big square. What is the easiest way to turn this into a circle?


问:
Bootstrap 4 - Flex wrap after 5th item
I'm trying to achieve quite a specific layout using the newest Bootstrap 4. How it should work/look:
- first element/child should be a kind of 'hero', visible on 100% of container width
- all other items should be as thumbs
- the 'thumbs' row should include 4 items, next one should break/wrap to another row

So in theory new row should appear after 5th element (hero + 4 thumbs), but I have no clue how to approach that. My current code looks as follows:

HTML

```<code><section id="videos">
  <div class="row gallery">
    <div class="col-lg-12">
      <dl class="d-flex justify-content-between flex-wrap thumbs">
        <dt class="p-2 main-frame">
          <a href="#" title="test it">
            <img src="https://picsum.photos/seed/picsum/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/seed/111/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/seed/354/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/1920/1080" class="img-fluid" />
          </a>
        </dt>
        <dt class="p-2">
          <a href="#" title="test it">
            <img src="https://picsum.photos/1920/1080" class="img-fluid" />
          </a>
        </dt>
      </dl>
    </div>
  </div>
</section>
</code>```

CSS

```<code>.thumbs dt:not(:first-child) {
  flex: 1;
}

.thumbs dt:nth-child(1) {
  width: 100%;
}
</code>```

Jsfiddle

What I'm doing wrong? Is it doable without additional js?

答:
Your approach with flex-wrap is quite good.

But instead of flex: 1; which will enlarge your items to equal size, you can set a width of one fourth width: calc(100% / 4); to have four items in a row.

So you can leave your HTML and just change your CSS to

.thumbs dt:not(:first-child) {
  width: calc(100% / 4);
}

.thumbs dt:nth-child(1) {
  width: 100%;
}
```

JSFiddle

Title: Bootstrap 4 - Flex wrap after 5th item

Body:
I'm trying to achieve quite a specific layout using the newest Bootstrap 4. How it should work/look:
- first element/child should be a kind of 'hero', visible on 100% of container width
- all other items should be as thumbs
- the 'thumbs' row should include 4 items, next one should break/wrap to another row

So in theory new row should appear after 5th element (hero + 4 thumbs), but I have no clue how to approach that. My current code looks as follows:

HTML

CSS

.thumbs dt:not(:first-child) {
  flex: 1;
}

.thumbs dt:nth-child(1) {
  width: 100%;
}

Jsfiddle

What I'm doing wrong? Is it doable without additional js?

Body:
Your approach with flex-wrap is quite good.

But instead of flex: 1; which will enlarge your items to equal size, you can set a width of one fourth width: calc(100% / 4); to have four items in a row.

So you can leave your HTML and just change your CSS to

.thumbs dt:not(:first-child) {
  width: calc(100% / 4);
}

.thumbs dt:nth-child(1) {
  width: 100%;
}

JSFiddle


问:
Mailkit SMTP - StartTLS & TLS flags
I am trying to connect to iCloud via SmtpClient

The settings I am using are as follows:

Server name: smtp.mail.me.com

SSL Required: Yes

If you see an error message when using SSL, try using TLS or STARTTLS instead.

Port: 587

SMTP Authentication Required: Yes - with relevant username and password

If I use SSL I get "Handshake failed due to unexpected packet format"

If I don't use SSL visual studio debugger hangs on connect.

I think the problem is I am not telling the SmtpClient to use tls but I cant find documentation on how to do this.

The code is as follows:

```<code>using (var client = new SmtpClient()) {
    client.Timeout = 1000 * 20;
    //client.Capabilities.
    client.AuthenticationMechanisms.Remove ("XOAUTH2");

    client.Connect("SMTP.mail.me.com", 587, false); //dies here
    //client.Connect(servername, port, useSsl);
    //can I set tls or starttls here??
    client.Authenticate(username, password);
    client.Send(FormatOptions.Default, message);
}
</code>```

Am I able to set TLS or StartTLS manually. One thing I did try is the following but it did not seem to work

```<code>client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true"));
</code>```

Thanks for any help with this.

答:
This worked for me over the SecureSocketOptions.Auto option mentioned previously:</p>

```<code>    client.Connect(host, port, SecureSocketOptions.None);
</code>```

Title: Mailkit SMTP - StartTLS & TLS flags

Body:
I am trying to connect to iCloud via SmtpClient

The settings I am using are as follows:

Server name: smtp.mail.me.com

SSL Required: Yes

If you see an error message when using SSL, try using TLS or STARTTLS instead.

Port: 587

SMTP Authentication Required: Yes - with relevant username and password

If I use SSL I get "Handshake failed due to unexpected packet format"

If I don't use SSL visual studio debugger hangs on connect.

I think the problem is I am not telling the SmtpClient to use tls but I cant find documentation on how to do this.

The code is as follows:

using (var client = new SmtpClient()) {
    client.Timeout = 1000 * 20;
    //client.Capabilities.
    client.AuthenticationMechanisms.Remove ("XOAUTH2");

    client.Connect("SMTP.mail.me.com", 587, false); //dies here
    //client.Connect(servername, port, useSsl);
    //can I set tls or starttls here??
    client.Authenticate(username, password);
    client.Send(FormatOptions.Default, message);
}

Am I able to set TLS or StartTLS manually. One thing I did try is the following but it did not seem to work

client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true"));

Thanks for any help with this.

Body:
This worked for me over the SecureSocketOptions.Auto option mentioned previously:

    client.Connect(host, port, SecureSocketOptions.None);


问:
fetch source values from jenkins extended choice parameter

I have added an extended choice paramter. Now the source values are lin1, lin2, lin3 as listed in screenshot

now when I run,
If I select lin1 then I get param3 = lin1,

If I select lin1 and lin2 then I get param2 - lin1,lin2    ( delimiter is comma )

The question here is, inside jenkins pipeline how can get what all source values were set when the param was created. In short, without selecting any of the checkboxes, want to get the list of the possible values probably in a list

Eg:
list1 = some_method(param3)
// expected output >>  list1 = [lin,lin2,lin3]

Let me know if this description is not clear.

The user who runs this does not have configure access ( we dont want to give configure access to anonynmous user ) Hence the job/config.xml idea will not work here

答:
I couldn't find any variable or method to get the parameter list. I guess it's somehow possible through a undocumented method on the param or currentBuild maps.

A possible solution to your problem could be defining the map outside of the pipeline and then just use that variables like this:

```<code>def param3Choices = ['lin1', 'lin2', 'lin3']

pipeline {
   parameters {
       choice(name: 'PARAM3', choices: param3Choices, description: '')
   }

   stage('Debug') {
       steps {
          echo param.PARAM3
          print param3Choices
       }
   }
}
</code>```

Body:
I couldn't find any variable or method to get the parameter list. I guess it's somehow possible through a undocumented method on the param or currentBuild maps.

A possible solution to your problem could be defining the map outside of the pipeline and then just use that variables like this:

def param3Choices = ['lin1', 'lin2', 'lin3']

pipeline {
   parameters {
       choice(name: 'PARAM3', choices: param3Choices, description: '')
   }

   stage('Debug') {
       steps {
          echo param.PARAM3
          print param3Choices
       }
   }
}


问:
Sorting an array of objects based on string property in Typescript
I have an array of objects like so:

```<code>0: {id: "743", name: "F"}
1: {id: "786", name: "S"}
2: {id: "903", name: "B"}
3: {id: "988", name: "L"}
4: {id: "1202", name: "S"}
5: {id: "1355", name: "H"}
6: {id: "1374", name: "R"}
</code>```

And I need to sort the array of objects based on the 'name' property.

I have searched around for the answer and have tried each of them out but with no joy.
The two main answers I came across were:

```<code>Array.sort((leftSide, rightSide): number => {
            if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
            if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
            return 0;
        });
</code>```

and

```<code>Array.sort((a, b) => a.name.localeCompare(b.name))
</code>```

both of these just give me the same unsorted array output. Is there any other way to do this? I am using Angular 7.

Full code:

```<code>getDeviceBrands(): void {
        this.deviceBrands = new Array<DeviceBrand>();
        const parentNodeId = 0;

        this.chartsService.getCatalogNodes(parentNodeId, this.catalogName).subscribe(catalogNodes => {
            catalogNodes.forEach(n => {
                this.deviceBrands.push({
                    id: n.CatalogNodeId.toString(),
                    name: n.Name
                });
            });
        });

        console.log(this.deviceBrands);

        const sorted = this.deviceBrands.sort((a, b) => a.name < b.name ? -1 : 1);

        console.log(sorted);
    }
</code>```

答:
The issue was that I was doing the sort too late! If you need to edit a collection in anyway and you are using a subscribe to fill your collection then add the code within the subscribe!

I did not include my full code at first which is what caused confusion as the answers supplied all worked. This is a good example of why you should include full code.

Body:
I have an array of objects like so:

0: {id: "743", name: "F"}
1: {id: "786", name: "S"}
2: {id: "903", name: "B"}
3: {id: "988", name: "L"}
4: {id: "1202", name: "S"}
5: {id: "1355", name: "H"}
6: {id: "1374", name: "R"}

And I need to sort the array of objects based on the 'name' property.

I have searched around for the answer and have tried each of them out but with no joy.
The two main answers I came across were:

Array.sort((leftSide, rightSide): number => {
            if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
            if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
            return 0;
        });

and

Array.sort((a, b) => a.name.localeCompare(b.name))

both of these just give me the same unsorted array output. Is there any other way to do this? I am using Angular 7.

Full code:

getDeviceBrands(): void {
        this.deviceBrands = new Array<DeviceBrand>();
        const parentNodeId = 0;

        this.chartsService.getCatalogNodes(parentNodeId, this.catalogName).subscribe(catalogNodes => {
            catalogNodes.forEach(n => {
                this.deviceBrands.push({
                    id: n.CatalogNodeId.toString(),
                    name: n.Name
                });
            });
        });

        console.log(this.deviceBrands);

        const sorted = this.deviceBrands.sort((a, b) => a.name < b.name ? -1 : 1);

        console.log(sorted);
    }


答:
As Jan Christoph Terasa comments, the precision in your x values is almost certainly the problem.   When doing fits, the underlying algorithms need to make small relative changes to the parameter values to see how that affects the fit.  The changes are typically at the 1.e-7 level.  This means that when working with values at the 1e.-9 level, the changes will approach machine precision and may have no effect on the result (and, yes, this can depend on machine details).

The solution is to change the scale of your x and or y data so that it is in the range of say 1.e-6 to 1.e6.   Fortunately for your situation, it looks like you can just change x by multiplying by 1e9 and working in units of "nano-x".

Title: Trouble fitting Gaussian fit using lmfit due to data values appearing to be too small

Body:
I am trying to fit a Gaussian fit around the following data using the lmfit module:

x = np.array([-1.36534351e-09, -1.29984067e-09, -1.23433782e-09, -1.16883498e-09,
-1.10333214e-09, -1.03782929e-09, -9.72326447e-10, -9.06823602e-10,
-8.41320758e-10, -7.75817913e-10, -7.10315069e-10, -6.44812224e-10,
-5.79309380e-10, -5.13806535e-10, -4.48303691e-10, -3.82800846e-10,
-3.17298002e-10, -2.51795157e-10, -1.86292313e-10, -1.20789468e-10,
-5.52866238e-11,  1.02162207e-11,  7.57190652e-11,  1.41221910e-10,
 2.06724754e-10,  2.72227599e-10,  3.37730443e-10,  4.03233288e-10,
 4.68736132e-10,  5.34238977e-10,  5.99741821e-10,  6.65244666e-10,
 7.30747510e-10,  7.96250355e-10,  8.61753199e-10,  9.27256043e-10,
 9.92758888e-10,  1.05826173e-09,  1.12376458e-09,  1.18926742e-09,
 1.25477027e-09,  1.32027311e-09,  1.38577595e-09,  1.45127880e-09,
 1.51678164e-09,  1.58228449e-09,  1.64778733e-09,  1.71329018e-09,
 1.77879302e-09,  1.84429587e-09])

y = np.array([  2,   0,   0,   0,   1,   0,   0,   1,   0,   1,   2,   4,   7,   8,  17,  13,  45,
77, 182, 346, 494, 512, 443, 327, 192, 115,  62,  28,  20,  16,  13,   5,   6,   2,   1,   0,
0,   2,   4,   1,   2,   2,   1,   2,   2,   1,   2,   2,   0,   1])

When I fit the data and plot it however, I get the following result:

Interestingly, if I multiply the x data array by say, 100, the fit seems to work fine:

I suspect that it might be due to the initial guess to be inaccurate, but I'm still not quite sure why this is happening and how I can fix this. I've included the entire code below:

import matplotlib.pyplot as plt
from lmfit.models import GaussianModel
import numpy as np

x = np.array([-1.36534351e-09, -1.29984067e-09, -1.23433782e-09, -1.16883498e-09,
 -1.10333214e-09, -1.03782929e-09, -9.72326447e-10, -9.06823602e-10,
 -8.41320758e-10, -7.75817913e-10, -7.10315069e-10, -6.44812224e-10,
 -5.79309380e-10, -5.13806535e-10, -4.48303691e-10, -3.82800846e-10,
 -3.17298002e-10, -2.51795157e-10, -1.86292313e-10, -1.20789468e-10,
 -5.52866238e-11,  1.02162207e-11,  7.57190652e-11,  1.41221910e-10,
  2.06724754e-10,  2.72227599e-10,  3.37730443e-10,  4.03233288e-10,
  4.68736132e-10,  5.34238977e-10,  5.99741821e-10,  6.65244666e-10,
  7.30747510e-10,  7.96250355e-10,  8.61753199e-10,  9.27256043e-10,
  9.92758888e-10,  1.05826173e-09,  1.12376458e-09,  1.18926742e-09,
  1.25477027e-09,  1.32027311e-09,  1.38577595e-09,  1.45127880e-09,
  1.51678164e-09,  1.58228449e-09,  1.64778733e-09,  1.71329018e-09,
  1.77879302e-09,  1.84429587e-09])
y = np.array([  2,   0,   0,   0,   1,   0,   0,   1,   0,   1,   2,   4,   7,   8,  17,  13,  45,
77, 182, 346, 494, 512, 443, 327, 192, 115,  62,  28,  20,  16,  13,   5,   6,   2,   1,   0, 0,   2,
4,   1,   2,   2,   1,   2,   2,   1,   2,   2,   0,   1])

mod = GaussianModel()
pars = mod.guess(y, x=x)
final_fit = mod.fit(y, pars, x=x)

plt.plot(x, final_fit.init_fit, label='Initial fit')
plt.plot(x, final_fit.best_fit, label='Gaussian fit')
plt.scatter(x, y, label='data points')
plt.show()

Update:
I have tested the exactly the same program on another computer and turns out it works perfectly there. Now, I'm not so sure.


问:
Group array objects by two elements and sum values (Javascript)
I have the following case:

I have an array consisting of all the appointments of the currently logged in user, like this:

```<code> this.appointments = [
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 88,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
},
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-08T10:30:00.000Z",
 EndTimezone: null,
 Id: 4,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: null,
 StartTime: "2020-06-08T10:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng"  ,
 km: 88,
 week: 24,
 _id: "5ed450d299d5303bd0338a7f"
}
  ]
</code>```

What I ultimately want to do is group the array by Client per Week. So accumulate all the time and km of the appointments (using dayjs library) of one week per client. This is the .reduce function I have now which groups the array only by Client but not yet per week:

```<code>this.appointments.reduce(function (res, value) {
  let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "hour",true) % 60;
  let count;

  if(value.RecurrenceRule != null) {
    count =  parseInt(value.RecurrenceRule.split("COUNT=")[1]);
    if(value.RecurrenceException){
    if(value.RecurrenceException.match(/,/g) ) {
      if(value.RecurrenceException.match(/,/g).length == 0) {
        console.log(value.RecurrenceException.match(/,/g).length);
        count = count -1;
      }
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 1) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -2;
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 2) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -3;
    } else
    if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 3) {
       count = count -4;
    };
  }
  }
  else if(value.RecurrenceRule == null) {
       count = 1;
  }
  if (!res[value.Client]) {
    res[value.Client] = {

      week: value.week,
      km: value.km * count,
      Client: value.Client,
      count: count,
      difference: diff * count
    };
    result.push(res[value.Client]);

  } else {
    res[value.Client].km += value.km * count;
    res[value.Client].difference += diff * count;
  }

  return res;
}, {});
</code>```

How do I go about this situation?
the output now is that instead of creating two rows (week 23 & 24), it sums all the appointments of Steven in week 23 which is incorrect because 0.5 hour took place in another week.

```<code>{Client: "Steven"
count: 5
difference: 40.5
km: 528
week: 23}
</code>```

So the ideal output is:

```<code>{
Client: "Steven"
count: 5
difference: 40
km: 440
week: 23
},

{
Client: "Steven"
count: 1
difference: 0.5
km: 88
week: 24
}
</code>```

You can have rows with the same week number as long as the Client differs.

I hope i made it clear and if you need more context, please mention

答:
I'm not sure this is what your expectation
and I'm not sure what to do with difference just explain me if this is not satisfied.

var data = [
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 88,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
},
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-08T10:30:00.000Z",
 EndTimezone: null,
 Id: 4,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: null,
 StartTime: "2020-06-08T10:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng"  ,
 km: 88,
 week: 24,
 _id: "5ed450d299d5303bd0338a7f"
},
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 40,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
},
{
 CreatedBy: "bob",
 Description: "smtng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "ajai",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 88,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
}
  ]
let result = []
for(var i=0;i<=data.length-1;i++){
   let pos = result.findIndex(el=> `${el.Client}-${el.week}`==`${data[i].Client}-${data[i].week}`)
   if(pos==-1){
     result.push({Client: data[i]['Client'],count: 1,difference: 0,km: data[i]['km'],week: data[i]['week']})
   }else{
     result[pos]['count'] = result[pos]['count'] + 1;
     result[pos]['km'] = result[pos]['km'] + data[i]['km'];
   }
}
console.log(result)

 ```

Body:
I have the following case:

I have an array consisting of all the appointments of the currently logged in user, like this:

 this.appointments = [
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-01T17:00:00.000Z",
 EndTimezone: null,
 Id: 3,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: "FREQ=DAILY;INTERVAL=1;COUNT=5;",
 StartTime: "2020-06-01T09:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng",
 km: 88,
 week: 23,
 _id: "5ecc6f4a08c79c6328974699"
},
{
 CreatedBy: "bob",
 Description: "smthng",
 EndTime: "2020-06-08T10:30:00.000Z",
 EndTimezone: null,
 Id: 4,
 IsAllDay: false,
 Client: "Steven",
 Location: "smthng",
 RecurrenceRule: null,
 StartTime: "2020-06-08T10:00:00.000Z",
 StartTimezone: null,
 Subject: "smthng"  ,
 km: 88,
 week: 24,
 _id: "5ed450d299d5303bd0338a7f"
}
  ]

What I ultimately want to do is group the array by Client per Week. So accumulate all the time and km of the appointments (using dayjs library) of one week per client. This is the .reduce function I have now which groups the array only by Client but not yet per week:

this.appointments.reduce(function (res, value) {
  let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "hour",true) % 60;
  let count;

  if(value.RecurrenceRule != null) {
    count =  parseInt(value.RecurrenceRule.split("COUNT=")[1]);
    if(value.RecurrenceException){
    if(value.RecurrenceException.match(/,/g) ) {
      if(value.RecurrenceException.match(/,/g).length == 0) {
        console.log(value.RecurrenceException.match(/,/g).length);
        count = count -1;
      }
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 1) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -2;
    } else if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 2) {
      console.log(value.RecurrenceException.match(/,/g).length);
      count = count -3;
    } else
    if(value.RecurrenceException && value.RecurrenceException.match(/,/g).length == 3) {
       count = count -4;
    };
  }
  }
  else if(value.RecurrenceRule == null) {
       count = 1;
  }
  if (!res[value.Client]) {
    res[value.Client] = {

      week: value.week,
      km: value.km * count,
      Client: value.Client,
      count: count,
      difference: diff * count
    };
    result.push(res[value.Client]);

  } else {
    res[value.Client].km += value.km * count;
    res[value.Client].difference += diff * count;
  }

  return res;
}, {});

How do I go about this situation?
the output now is that instead of creating two rows (week 23 & 24), it sums all the appointments of Steven in week 23 which is incorrect because 0.5 hour took place in another week.

{Client: "Steven"
count: 5
difference: 40.5
km: 528
week: 23}

So the ideal output is:

{
Client: "Steven"
count: 5
difference: 40
km: 440
week: 23
},

{
Client: "Steven"
count: 1
difference: 0.5
km: 88
week: 24
}

You can have rows with the same week number as long as the Client differs.

I hope i made it clear and if you need more context, please mention


问:
Can Maven generate exe files and mac os x apps?
Lets say you created a little Java Desktop app with a jar and some dependencies and possibly a license text file. I know there are plenty of Ant tasks that can generate installers, executables and proper Mac OS X applications including packaging them as ".dmg" files. Examples would be JarBundler and Launch4j

Does similar things exist for Maven?

Thanks

答:
To generate a windows executable in a maven build, you can use the launch4j-maven-plugin. I just answered a related question, Trying to integrate Launch4j in a Maven project using Alakai plugin, showing how to accomplish that. It's very easy, more than JSmooth, which always had a maven plugin.

Hope it helps!

ContentLicense: CC BY-SA 2.5


问:
AWS Elasticsearch synonyms using file
I am trying to add synonyms to elastic search as show in this link using a file but it gives me the following error https://www.elastic.co/guide/en/elasticsearch/reference/5.2/analysis-synonym-tokenfilter.html

```<code>error":{"root_cause":[{"type":"illegal_argument_exception","reason":"IOException while reading synonyms_path_path: ],"type":"illegal_argument_exception","reason":"IOException while reading synonyms_path_path:  (No such file or directory)"}},"status":400}
</code>```

My mapping code looks like this and synonyms.txt is within the same folder (same level):

```<code>'settings': {
            'analysis': {
                'filter': {
                    'english_stemmer': {
                        'type': 'stemmer',
                        'language': 'english'
                    },
                    'english_possessive_stemmer': {
                        'type': 'stemmer',
                        'language': 'possessive_english'
                    },
                    'my_synonyms': {
                        'type': 'synonym',
                        'synonyms_path' : 'synonyms.txt'
                    }
                },
                'analyzer': {
                    'my_analyzer': {
                        'tokenizer': 'standard',
                        'filter': [
                            'english_possessive_stemmer',
                            'lowercase',
                            'my_synonyms',
                            'english_stemmer'
                        ]
                    }
                }
            }
        },
        'mappings' : ...
</code>```

答:
With support for custom dictionaries, Amazon Elasticsearch Service can now import your dictionary files from Amazon S3 and make them available to be associated with your Amazon Elasticsearch Service domain(s) as needed. Custom dictionary support is available for all versions of Elasticsearch on Amazon Elasticsearch Service. To learn more, see the documentation

documentation link

Title: AWS Elasticsearch synonyms using file

Body:
I am trying to add synonyms to elastic search as show in this link using a file but it gives me the following error https://www.elastic.co/guide/en/elasticsearch/reference/5.2/analysis-synonym-tokenfilter.html

error":{"root_cause":[{"type":"illegal_argument_exception","reason":"IOException while reading synonyms_path_path: ],"type":"illegal_argument_exception","reason":"IOException while reading synonyms_path_path:  (No such file or directory)"}},"status":400}

My mapping code looks like this and synonyms.txt is within the same folder (same level):

'settings': {
            'analysis': {
                'filter': {
                    'english_stemmer': {
                        'type': 'stemmer',
                        'language': 'english'
                    },
                    'english_possessive_stemmer': {
                        'type': 'stemmer',
                        'language': 'possessive_english'
                    },
                    'my_synonyms': {
                        'type': 'synonym',
                        'synonyms_path' : 'synonyms.txt'
                    }
                },
                'analyzer': {
                    'my_analyzer': {
                        'tokenizer': 'standard',
                        'filter': [
                            'english_possessive_stemmer',
                            'lowercase',
                            'my_synonyms',
                            'english_stemmer'
                        ]
                    }
                }
            }
        },
        'mappings' : ...


问:
Which profile does sh loads
I am trying to load a specific tool ( nvm ) from within sh.

Installing it as explained in the page for bash it works perfectly and testing it returns the following.

$ bash
$ nvm --version
+ X.XX.X
```

<p>but if I type </p>

<pre class="lang-sh prettyprint-override"><code>$ sh
$ nvm --version
+ sh: 1: nvm: not found
</code>```

but still its expected as the default installation modifies the .bashrc.

now i have included the same .bashrc code in my /etc/profile

export NVM_DIR="/opt/nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
```

<p>and tried again.</p>

<pre class="lang-sh prettyprint-override"><code>$ sh
$ nvm --version
+ sh: 1: nvm: not found
$ echo $NVM_DIR
+ /dir/to/nvm
$ [ -s "$NVM_DIR/nvm.sh" ] && echo "it works?"
+ it works?
$ [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
$ nvm --version
X.XX.X
</code>```

which got me extremely confused. What exactly is happening ? Isn't sh loading the /etc/profile or am I doing something really wrong?

--edit after comments--

also tried to include it in the local profile

$ cat ~/.profile
+ export NVM_DIR="/opt/nvm"
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
$ sh
$ nvm --version
+ sh: 1: nvm: not found
```

答:
The problem was described in this article with the sh blue line.
The solution to the problem was to set the /etc/profile/ in the ENV variable.

for example ENV=/etc/profile sh would load the profile when the sh opens. That solved the problem

Title: Which profile does sh loads

Body:
I am trying to load a specific tool ( nvm ) from within sh.

Installing it as explained in the page for bash it works perfectly and testing it returns the following.

$ bash
$ nvm --version
+ X.XX.X

but if I type

$ sh
$ nvm --version
+ sh: 1: nvm: not found

but still its expected as the default installation modifies the .bashrc.

now i have included the same .bashrc code in my /etc/profile

export NVM_DIR="/opt/nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

and tried again.

$ sh
$ nvm --version
+ sh: 1: nvm: not found
$ echo $NVM_DIR
+ /dir/to/nvm
$ [ -s "$NVM_DIR/nvm.sh" ] && echo "it works?"
+ it works?
$ [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
$ nvm --version
X.XX.X

which got me extremely confused. What exactly is happening ? Isn't sh loading the /etc/profile or am I doing something really wrong?

--edit after comments--

also tried to include it in the local profile

$ cat ~/.profile
+ export NVM_DIR="/opt/nvm"
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
$ sh
$ nvm --version
+ sh: 1: nvm: not found


问:
Does the lifetime of an array object end when its' element storage is reused?
In the subsequent quotes, I'm referring to the ISO standard draft N4713.

§ 6.6.3, paragraph 1 says:

...The lifetime of an object o of type T ends when:

  ...

  — the storage which the object occupies is released, or is reused
  by an object that is not nested within o (6.6.2).

Please answer the questions in the code comments:

```<code>#include <new>

int main() {
    int x[2] = {0, 1};
    char* p = new (x + 1) char{0}; // Has x ended its' lifetime?
    int z = x[0];                  // Is this UB?
}
</code>```

If I used unsigned char as array element type, the array object x would have provided storage for the *p, according to § 6.6.2, paragraph 3:

If a complete object is created (8.5.2.4) in storage associated with
  another object e of type “array of N unsigned char” or of type “array
  of N std::byte” (21.2.1), that array provides storage for the created
  object if:

  — the lifetime of e has begun and not ended, and

  — the
  storage for the new object fits entirely within e, and

  — there is no
  smaller array object that satisfies these constraints.

Please, validate my statements in the code comments:

```<code>#include <new>

int main() {
    unsigned char x[2] = {0, 1};
    char* p = new (x + 1) char{0}; // Only x[1] have ended its' lifetime.
    int z = x[0];                  // This is OK.
}
</code>```

Although I do not understand the last rule in the previous quote, please give an example?

there is no smaller array object that satisfies these constraints.

答:
According to the following reading of the standard, the array lifetime is not ended by the placement new expression:

[basic.life]/1.5:

The lifetime of an object o of type T ends when:

[...]

the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).

According to this rule, if the new object created within the array is not nested within the array, the array life time end. Otherwise it is not ended.

[intro.object]/2

If an object is created in storage associated with a member subobject or array element e (which may or may not be within its lifetime), the created object is a subobject of e's containing object if:

the lifetime of e's containing object has begun and not ended, and

the storage for the new object exactly overlays the storage location associated with e, and

the new object is of the same type as e (ignoring cv-qualification).

The two last bullets are not full-filled, so obviously, the new char object is not a suboject of the array.

Then [intro.object]/3:

If a complete object is created ([expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std::byte” ([cstddef.syn]), that array provides storage for the created object if:

the lifetime of e has begun and not ended, and

the storage for the new object fits entirely within e, and

there is no smaller array object that satisfies these constraints.

So the array of unsigned char provides storage for the new char object.

[intro.object]/4:

An object a is nested within another object b if:

a is a subobject of b, or

b provides storage for a, or

there exists an object c where a is nested within c, and c is nested within b.

As we mentioned above, the first bullet is not full-filled. The second one is full-filled. So according to [basic.life]/1.5, the lifetime of the array is not ended because the new char object is nested within the array:

```<code>int main() {
    unsigned char x[2] = {0, 1};
    char* p = new (x + 1) char{0}; // x provides storage for the char object
    int z = x[0];                  // OK The first element is within its lifetime.
}
</code>```

If it were not the case, probably that most of the low-level code would not be standard compliant!

Body:
In the subsequent quotes, I'm referring to the ISO standard draft N4713.

§ 6.6.3, paragraph 1 says:

...The lifetime of an object o of type T ends when:

  ...

  — the storage which the object occupies is released, or is reused
  by an object that is not nested within o (6.6.2).

Please answer the questions in the code comments:

#include <new>

int main() {
    int x[2] = {0, 1};
    char* p = new (x + 1) char{0}; // Has x ended its' lifetime?
    int z = x[0];                  // Is this UB?
}

If I used unsigned char as array element type, the array object x would have provided storage for the *p, according to § 6.6.2, paragraph 3:

If a complete object is created (8.5.2.4) in storage associated with
  another object e of type “array of N unsigned char” or of type “array
  of N std::byte” (21.2.1), that array provides storage for the created
  object if:

  — the lifetime of e has begun and not ended, and

  — the
  storage for the new object fits entirely within e, and

  — there is no
  smaller array object that satisfies these constraints.

Please, validate my statements in the code comments:

#include <new>

int main() {
    unsigned char x[2] = {0, 1};
    char* p = new (x + 1) char{0}; // Only x[1] have ended its' lifetime.
    int z = x[0];                  // This is OK.
}

Although I do not understand the last rule in the previous quote, please give an example?

there is no smaller array object that satisfies these constraints.

Body:
According to the following reading of the standard, the array lifetime is not ended by the placement new expression:

[basic.life]/1.5:

The lifetime of an object o of type T ends when:

[...]

the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).

According to this rule, if the new object created within the array is not nested within the array, the array life time end. Otherwise it is not ended.

[intro.object]/2

If an object is created in storage associated with a member subobject or array element e (which may or may not be within its lifetime), the created object is a subobject of e's containing object if:

the lifetime of e's containing object has begun and not ended, and

the storage for the new object exactly overlays the storage location associated with e, and

the new object is of the same type as e (ignoring cv-qualification).

The two last bullets are not full-filled, so obviously, the new char object is not a suboject of the array.

Then [intro.object]/3:

If a complete object is created ([expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std::byte” ([cstddef.syn]), that array provides storage for the created object if:

the lifetime of e has begun and not ended, and

the storage for the new object fits entirely within e, and

there is no smaller array object that satisfies these constraints.

So the array of unsigned char provides storage for the new char object.

[intro.object]/4:

An object a is nested within another object b if:

a is a subobject of b, or

b provides storage for a, or

there exists an object c where a is nested within c, and c is nested within b.

As we mentioned above, the first bullet is not full-filled. The second one is full-filled. So according to [basic.life]/1.5, the lifetime of the array is not ended because the new char object is nested within the array:

int main() {
    unsigned char x[2] = {0, 1};
    char* p = new (x + 1) char{0}; // x provides storage for the char object
    int z = x[0];                  // OK The first element is within its lifetime.
}

If it were not the case, probably that most of the low-level code would not be standard compliant!


问:
Laravel validation messages array indices starting from 0
If in a form request I have rules

```<code>[
    'items' => ['required', 'array'],
    'items.*' => ['required', 'numeric'],
]
</code>```

Then error message returns like this:

```<code>"items.0" => array:1 [
  0 => "The selected items.0 is invalid."
]
</code>```

Is there any way to have the message look like "The selected items #1 is invalid" or something similar, that is actually human readable?

Please note, I need this for the whole system globally, there's already >500 form request classes, although not that many are using array validation, so changing extended class or adding a trait wouldn't be too horrible

答:
If you are using custom Request then You can do like this:

```<code>
public function rules()
    {
        $rules = [];
        foreach ($this->request->get('items') as $key => $value) {
            $rules[$key] = 'required';
        }
        return $rules;
    }
</code>```

Hope This Help you

Body:
If in a form request I have rules

[
    'items' => ['required', 'array'],
    'items.*' => ['required', 'numeric'],
]

Then error message returns like this:

"items.0" => array:1 [
  0 => "The selected items.0 is invalid."
]

Is there any way to have the message look like "The selected items #1 is invalid" or something similar, that is actually human readable?

Please note, I need this for the whole system globally, there's already >500 form request classes, although not that many are using array validation, so changing extended class or adding a trait wouldn't be too horrible

Body:
If you are using custom Request then You can do like this:

public function rules()
    {
        $rules = [];
        foreach ($this->request->get('items') as $key => $value) {
            $rules[$key] = 'required';
        }
        return $rules;
    }

Hope This Help you


问:
Why won't my server connect to a remote MSSQL server using PHP mssql_connect?
I've had to move an app we wrote for a client to a new server and a remote connection I was initiating with PHP mssql_connect has ceased to work. I noticed that PHP wasn't compiled with mssql so I asked the server admin to install it. I can verify that it's now installed via PHP info but I now get a consistent "Unable to connect to server" error from mssql_connect.

Here's the very simple PHP script I'm running:

```<code>$myServer = "myserver.com:5000";
$myUser = "myusername";
$myPass = "mypassword";

$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer. Error: " . mssql_get_last_message());
</code>```

I've confirmed that the credentials are still correct but for whatever reason it seems that mssql_connect just isn't doing it's thing. I'm wondering if there's something that the admin has forgotton to do having installed the extension and FreeTDS. Any pointers greatly appreciated! :)

PROBLEM SOLVED!!!

After all that it turned out to be the FreeTDS protocol version number as specified in /usr/local/freetds/etc/freetds.conf, line number 13 had to be uncommented. That was it! :)

答: There's a good chance that remote connections are disabled on the server where the server is installed. Have you checked whether you are actually able to connect to the DB server remotely, from the IP address of the webserver that attempts to connect to it? Usually, at least in most shared hosting schemes, the database server only accepts connections from localhost. You'd need to add the IP address of the webserver to a whitelist (usually in the server's configuration) to allow connections from the outside.</p>

Body:
I've had to move an app we wrote for a client to a new server and a remote connection I was initiating with PHP mssql_connect has ceased to work. I noticed that PHP wasn't compiled with mssql so I asked the server admin to install it. I can verify that it's now installed via PHP info but I now get a consistent "Unable to connect to server" error from mssql_connect.

Here's the very simple PHP script I'm running:

$myServer = "myserver.com:5000";
$myUser = "myusername";
$myPass = "mypassword";

$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer. Error: " . mssql_get_last_message());

I've confirmed that the credentials are still correct but for whatever reason it seems that mssql_connect just isn't doing it's thing. I'm wondering if there's something that the admin has forgotton to do having installed the extension and FreeTDS. Any pointers greatly appreciated! :)

PROBLEM SOLVED!!!

After all that it turned out to be the FreeTDS protocol version number as specified in /usr/local/freetds/etc/freetds.conf, line number 13 had to be uncommented. That was it! :)


问:
I can not see the result. There is is a kind of adress on the result
```<code>class circle:
    pi = 3.14

    def __init__(self, radius = 1) :
        self.radius = radius

    def perimeter (self):
        return 2* self.pi * self.radius
    def area (self):
        return self.pi * (self.radius**2 )

c1 = circle()
c2 = circle(5)
print(f"c1 Alan , cevre: {c1.area} , {c1.perimeter} \n c2 alan , cevre: {c2.perimeter} , {c2.area}")
</code>```

below is the output,

```<code>c1 area ,  perimeter: <bound method circle.area of <__main__.circle object at 0x000002228E3A6E80>> , <bound method circle.perimeter of <__main__.circle object at 0x000002228E3A6E80>>
c2 area , perimeter: <bound method circle.perimeter of <__main__.circle object at 0x000002228E3A6F28>> , <bound method circle.area of <__main__.circle object at 0x000002228E3A6F28>>
</code>```

答:
Try c1.area() and c1.perimeter().

Hope this helps :)

Body:
class circle:
    pi = 3.14

    def __init__(self, radius = 1) :
        self.radius = radius

    def perimeter (self):
        return 2* self.pi * self.radius
    def area (self):
        return self.pi * (self.radius**2 )

c1 = circle()
c2 = circle(5)
print(f"c1 Alan , cevre: {c1.area} , {c1.perimeter} \n c2 alan , cevre: {c2.perimeter} , {c2.area}")

below is the output,

c1 area ,  perimeter: <bound method circle.area of <__main__.circle object at 0x000002228E3A6E80>> , <bound method circle.perimeter of <__main__.circle object at 0x000002228E3A6E80>>
c2 area , perimeter: <bound method circle.perimeter of <__main__.circle object at 0x000002228E3A6F28>> , <bound method circle.area of <__main__.circle object at 0x000002228E3A6F28>>


问:
Javascript promise implementation
Whats best way to implement below in javascript.

```<code>/*
  A --|
      |-- D --|
  B --|       |-- E
              |
  C ----------|
</code>```

Each node is a async job, illustrated by setTimeout.

A, B, and C can run at the same time.

D, needs to wait for A and B to be done.

E needs to wait for C and D to be done.

How can I implement an interface which accepts the above nodes as args, which would take care of above implementation. Not sure what's best to implement whether async/await or JavaScript promise can be used and pros/cons.

答:
Here is a class Task you could use. When you create one, you need to provide it with a name, an asynchronous function (that will be called when the task can start), and a list of other task instances on which this task is dependent:

class Task {
    constructor(name, asyncWork, ...neededTasks) {
        this.promise = (async () => {
            await Promise.all(neededTasks.map(task => task.promise));
            console.log("start " + name);
            await asyncWork();
            console.log("complete " + name);
        })();
    }
}

// Utility function to mimic some asynchronous work, using setTimeout:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// Define the tasks. Note that they will automatically call
// the given function if there are no other tasks to wait for:
let a = new Task("a", () => delay(1000));
let b = new Task("b", () => delay(1500));
let c = new Task("c", () => delay(2000));
let d = new Task("d", () => delay(1000), a, b);
let e = new Task("e", () => delay(1000), c, d);```

When a task is created, a promise is created for it. It is stored in its promise property. This promise will only resolve when:

the "predecessor" promises, created for the tasks it is dependent on, are resolved

the actual asynchronous work for this task has run to completion (i.e. its returned promise has resolved)

These two steps are chained, so the actual work will not commence before the promises of the first step have resolved.

Title: Javascript promise implementation

Body:
Whats best way to implement below in javascript.

/*
  A --|
      |-- D --|
  B --|       |-- E
              |
  C ----------|

Each node is a async job, illustrated by setTimeout.

A, B, and C can run at the same time.

D, needs to wait for A and B to be done.

E needs to wait for C and D to be done.

How can I implement an interface which accepts the above nodes as args, which would take care of above implementation. Not sure what's best to implement whether async/await or JavaScript promise can be used and pros/cons.

Body:
Here is a class Task you could use. When you create one, you need to provide it with a name, an asynchronous function (that will be called when the task can start), and a list of other task instances on which this task is dependent:

class Task {
    constructor(name, asyncWork, ...neededTasks) {
        this.promise = (async () => {
            await Promise.all(neededTasks.map(task => task.promise));
            console.log("start " + name);
            await asyncWork();
            console.log("complete " + name);
        })();
    }
}

// Utility function to mimic some asynchronous work, using setTimeout:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// Define the tasks. Note that they will automatically call
// the given function if there are no other tasks to wait for:
let a = new Task("a", () => delay(1000));
let b = new Task("b", () => delay(1500));
let c = new Task("c", () => delay(2000));
let d = new Task("d", () => delay(1000), a, b);
let e = new Task("e", () => delay(1000), c, d);

When a task is created, a promise is created for it. It is stored in its promise property. This promise will only resolve when:

the "predecessor" promises, created for the tasks it is dependent on, are resolved

the actual asynchronous work for this task has run to completion (i.e. its returned promise has resolved)

These two steps are chained, so the actual work will not commence before the promises of the first step have resolved.


问:
How to parse json with unknown keys in android
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.

Can any one help me how to parse json with below keys.

```<code>{"users": {"19x1": "Admin","19x5": "Manager"}}
</code>```

答:
The keys are not the problem the user should be an object

```<code>{
  "users": {
  "19x1": "Admin",
  "19x5": "Manager"
  }
}
</code>```

Try the above code in any json validator to check.. ie https://jsonlint.com/

Updated to access the values:

<!DOCTYPE html>

How to access nested JSON objects.

```
</div>
</div>
</p>

<p>and for Android:</p>

```JSONObject jsonString = {"users": {"19x1": "Admin","19x5": "Manager"}};

JSONObject obj1 = new JSONObject(jsonString);
JSONObject obj2=obj1.getJSONObject("users");
JSONObject obj3=obj2.getJSONObject("19x1");

System.out.println("The value is " + obj3);
```

Body:
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.

Can any one help me how to parse json with below keys.

{"users": {"19x1": "Admin","19x5": "Manager"}}

Body:
The keys are not the problem the user should be an object

{
  "users": {
  "19x1": "Admin",
  "19x5": "Manager"
  }
}

Try the above code in any json validator to check.. ie https://jsonlint.com/

Updated to access the values:

<!DOCTYPE html>
<html>
<body>

<p>How to access nested JSON objects.</p>

<p id="demo"></p>

<script>
var myObj = {
  "users": {
  "19x1": "Admin",
  "19x5": "Manager"
  }
}
document.getElementById("demo").innerHTML += myObj.users["19x1"];
</script>

</body>
</html>

and for Android:

JSONObject jsonString = {"users": {"19x1": "Admin","19x5": "Manager"}};

JSONObject obj1 = new JSONObject(jsonString);
JSONObject obj2=obj1.getJSONObject("users");
JSONObject obj3=obj2.getJSONObject("19x1");

System.out.println("The value is " + obj3);


问:
Using Angular HttpClient inside for loop
I have some issues with Angular's HttpClient:

So, the app logic looks like:
component.ts:

I need to call createNewVideoUploadId() from service to get ID for upload video. Than I need to send file to Service Method:

```<code>uploadVideoToApi() {
    this.lessonService.createNewVideoUploadId()
        .subscribe(res => {
            this.lessonService.uploadNewVideo(this.videoToUpload, res['X-Upload-File-ID'])
        })
}
</code>```

lessonService look like:

```<code>createNewVideoUploadId() {
    return this.http.get<string>(`${environment.apiUrl}/upload/id`)
}
</code>```

uploadNewVideo:

```<code>uploadNewVideo(video: File, id: string) {

    const chunkSize = 10 * 1024 ** 2;
    const count = Math.ceil(video.size / chunkSize);

    let calls = []

    for (let i = 0; i < count; i++) {
        let chunk = video.slice(i * chunkSize, (i + 1) * chunkSize);

        let fd = new FormData();
        fd.append('file', chunk);
        fd.append('file_name', video.name);
        fd.append('file_size', video.size.toString());
        fd.append('chunk_size', chunkSize.toString());
        fd.append('chunk_number', i.toString());
        fd.append('chunks_count', count.toString());

        return this.http.post(`${environment.apiUrl}/upload/${id}`, fd)
    }
} // uploadNewVideo()
</code>```

So, for loop is stopping in first iteration because of return

I need to execute each for loop iteration one by one from component.ts

So, I need to subscribe to uploadNewVideo, and get responses. But I cant return anything from cycle.

答:
Just store the http-post streams in an array and concat thoose:</p>

```<code>uploadNewVideo(video: File, id: string) {

    const chunkSize = 10 * 1024 ** 2;
    const count = Math.ceil(video.size / chunkSize);

    let calls = []
    let httpCalls = [];

    for (let i = 0; i < count; i++) {
        let chunk = video.slice(i * chunkSize, (i + 1) * chunkSize);

        let fd = new FormData();
        fd.append('file', chunk);
        fd.append('file_name', video.name);
        fd.append('file_size', video.size.toString());
        fd.append('chunk_size', chunkSize.toString());
        fd.append('chunk_number', i.toString());
        fd.append('chunks_count', count.toString());

        httpCalls.push(this.http.post(`${environment.apiUrl}/upload/${id}`, fd));
    }

    return concat(httpCalls)
}
</code>```

Body:
I have some issues with Angular's HttpClient:

So, the app logic looks like:
component.ts:

I need to call createNewVideoUploadId() from service to get ID for upload video. Than I need to send file to Service Method:

uploadVideoToApi() {
    this.lessonService.createNewVideoUploadId()
        .subscribe(res => {
            this.lessonService.uploadNewVideo(this.videoToUpload, res['X-Upload-File-ID'])
        })
}

lessonService look like:

createNewVideoUploadId() {
    return this.http.get<string>(`${environment.apiUrl}/upload/id`)
}

uploadNewVideo:

uploadNewVideo(video: File, id: string) {

    const chunkSize = 10 * 1024 ** 2;
    const count = Math.ceil(video.size / chunkSize);

    let calls = []

    for (let i = 0; i < count; i++) {
        let chunk = video.slice(i * chunkSize, (i + 1) * chunkSize);

        let fd = new FormData();
        fd.append('file', chunk);
        fd.append('file_name', video.name);
        fd.append('file_size', video.size.toString());
        fd.append('chunk_size', chunkSize.toString());
        fd.append('chunk_number', i.toString());
        fd.append('chunks_count', count.toString());

        return this.http.post(`${environment.apiUrl}/upload/${id}`, fd)
    }
} // uploadNewVideo()

So, for loop is stopping in first iteration because of return

I need to execute each for loop iteration one by one from component.ts

So, I need to subscribe to uploadNewVideo, and get responses. But I cant return anything from cycle.

Body:
Just store the http-post streams in an array and concat thoose:

uploadNewVideo(video: File, id: string) {

    const chunkSize = 10 * 1024 ** 2;
    const count = Math.ceil(video.size / chunkSize);

    let calls = []
    let httpCalls = [];

    for (let i = 0; i < count; i++) {
        let chunk = video.slice(i * chunkSize, (i + 1) * chunkSize);

        let fd = new FormData();
        fd.append('file', chunk);
        fd.append('file_name', video.name);
        fd.append('file_size', video.size.toString());
        fd.append('chunk_size', chunkSize.toString());
        fd.append('chunk_number', i.toString());
        fd.append('chunks_count', count.toString());

        httpCalls.push(this.http.post(`${environment.apiUrl}/upload/${id}`, fd));
    }

    return concat(httpCalls)
}


答:
You could RxJS forkJoin() method. Try the following

uploadNewVideo(video: File, id: string) {
  const chunkSize = 10 * 1024 ** 2;
  const count = Math.ceil(video.size / chunkSize);
  let calls = []

  for (let i = 0; i < count; i++) {
    let chunk = video.slice(i * chunkSize, (i + 1) * chunkSize);

    let fd = new FormData();
    fd.append('file', chunk);
    fd.append('file_name', video.name);
    fd.append('file_size', video.size.toString());
    fd.append('chunk_size', chunkSize.toString());
    fd.append('chunk_number', i.toString());
    fd.append('chunks_count', count.toString());

    calls.push(this.http.post(`${environment.apiUrl}/upload/${id}`, fd).pipe(retry(3)))   // <-- retry 3x in case of error
  }

  return forkJoin(calls);     // <-- use `forkJoin` here
}
```

<p>Now you could subscribe to the function to trigger the calls</p>

<pre class="lang-js prettyprint-override"><code>uploadVideoToApi() {
  this.lessonService.createNewVideoUploadId().pipe(
    switchMap(res => this.lessonService.uploadNewVideo(this.videoToUpload, res['X-Upload-File-ID'])),
    catchError(error => of(error))
  ).subscribe(
    response => {
      // handle response
    },
    error => {
      // handle error
    }
  );
}
</code>```

Title: Using Angular HttpClient inside for loop

Body:
You could RxJS forkJoin() method. Try the following

uploadNewVideo(video: File, id: string) {
  const chunkSize = 10 * 1024 ** 2;
  const count = Math.ceil(video.size / chunkSize);
  let calls = []

  for (let i = 0; i < count; i++) {
    let chunk = video.slice(i * chunkSize, (i + 1) * chunkSize);

    let fd = new FormData();
    fd.append('file', chunk);
    fd.append('file_name', video.name);
    fd.append('file_size', video.size.toString());
    fd.append('chunk_size', chunkSize.toString());
    fd.append('chunk_number', i.toString());
    fd.append('chunks_count', count.toString());

    calls.push(this.http.post(`${environment.apiUrl}/upload/${id}`, fd).pipe(retry(3)))   // <-- retry 3x in case of error
  }

  return forkJoin(calls);     // <-- use `forkJoin` here
}

Now you could subscribe to the function to trigger the calls

uploadVideoToApi() {
  this.lessonService.createNewVideoUploadId().pipe(
    switchMap(res => this.lessonService.uploadNewVideo(this.videoToUpload, res['X-Upload-File-ID'])),
    catchError(error => of(error))
  ).subscribe(
    response => {
      // handle response
    },
    error => {
      // handle error
    }
  );
}


问:
How to count the Done status in vue
I'm using vue and I have a json file and the file looks like this

```<code>
{
  "Task-1": {
    "Name": "Task 1",
    "Start": "2020-04-08",
    "End": "2020-04-17",
    "Issues": {
      "Issue-1": {
        "Name": "Issue 1",
        "issueStatus": "Done"
      },
      "Issue-2": {
        "Name": "Issue 2",
        "Status": "Done"
      },
      "Issue-3": {
        "Name": "Issue 3",
        "Status": "Done"
      },
      "Issue-4": {
        "Name": "Issue 4",
        "Status": "Done"
      },
      "Issue-5": {
        "Name": "Issue 5",
        "Status": "Done"
      },
      "Issue-6": {
        "Name": "Issue 6",
        "Status": "Done"
      }
    }
  },
  "Task-2": {
    "Name": "Task 2",
    "Start": "2020-04-08",
    "End": "2020-04-17",
    "Issues": {
      "Issue-1": {
        "Name": "Issue 1",
        "Status": "Done"
      },
      "Issue-2": {
        "Name": "Issue 2",
        "Status": "Done"
      },
      "Issue-3": {
        "Name": "Issue 3",
        "Status": "In Progress"
      },
      "Issue-4": {
        "Name": "Issue 4",
        "Status": "In Progress"
      },
      "Issue-5": {
        "Name": "Issue 5",
        "Status": "In Progress"
      },
      "Issue-6": {
        "Name": "Issue 6",
        "Status": "In Progress"
      }
    }
  },
}
</code>```

What I would like to do is calculate how many Done issues there is per task.

This is what I have at the moment

Task.vue

```<code>getTasks(){

    $.each(this.tasks, function(key, value){

        var count = Object.keys(value.Issues).length;

        $.each(value.Issues, function(k, v){
            if(v.Status == "Done")
            {
                console.log(v.Status.length);
            }

        });
     });
},
</code>```

This section

```<code>if(v.Status == "Done")
{
    console.log(v.Status.length);
}
</code>```

finds all the issues that is done and this is where I'm stuck

答:
You are using jQuery instead of vue. In vue.js you can use computed property with JavaScript higher-order function to iterate through the json data and filter the elements. Then get the length.

See this example:

new Vue({
  el: "#app",
  data: {
    tasks: {
      "Task-1": {
        "Name": "Task 1",
        "Start": "2020-04-08",
        "End": "2020-04-17",
        "Issues": {
          "Issue-1": {
            "Name": "Issue 1",
            "issueStatus": "Done"
          },
          "Issue-2": {
            "Name": "Issue 2",
            "Status": "Done"
          },
          "Issue-3": {
            "Name": "Issue 3",
            "Status": "Done"
          },
          "Issue-4": {
            "Name": "Issue 4",
            "Status": "Done"
          },
          "Issue-5": {
            "Name": "Issue 5",
            "Status": "Done"
          },
          "Issue-6": {
            "Name": "Issue 6",
            "Status": "Done"
          }
        }
      },
      "Task-2": {
        "Name": "Task 2",
        "Start": "2020-04-08",
        "End": "2020-04-17",
        "Issues": {
          "Issue-1": {
            "Name": "Issue 1",
            "Status": "Done"
          },
          "Issue-2": {
            "Name": "Issue 2",
            "Status": "Done"
          },
          "Issue-3": {
            "Name": "Issue 3",
            "Status": "In Progress"
          },
          "Issue-4": {
            "Name": "Issue 4",
            "Status": "In Progress"
          },
          "Issue-5": {
            "Name": "Issue 5",
            "Status": "In Progress"
          },
          "Issue-6": {
            "Name": "Issue 6",
            "Status": "In Progress"
          }
        }
      }
    }
  },
  computed: {
    doneLength: function() {
      // Map throught first keys
      const findDone = Object.keys(this.tasks).map(t => {
        // Get the issues object and filter based on required value (Done)
        return Object.keys(this.tasks[t].Issues).filter(i => {
          // return only matching values
          return this.tasks[t].Issues[i].Status == "Done";
        })
      });

      // flatten and get length
      return [].concat(...findDone).length;

    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>{{doneLength}}</div></code>```

Title: How to count the Done status in vue

Body:
I'm using vue and I have a json file and the file looks like this

{
  "Task-1": {
    "Name": "Task 1",
    "Start": "2020-04-08",
    "End": "2020-04-17",
    "Issues": {
      "Issue-1": {
        "Name": "Issue 1",
        "issueStatus": "Done"
      },
      "Issue-2": {
        "Name": "Issue 2",
        "Status": "Done"
      },
      "Issue-3": {
        "Name": "Issue 3",
        "Status": "Done"
      },
      "Issue-4": {
        "Name": "Issue 4",
        "Status": "Done"
      },
      "Issue-5": {
        "Name": "Issue 5",
        "Status": "Done"
      },
      "Issue-6": {
        "Name": "Issue 6",
        "Status": "Done"
      }
    }
  },
  "Task-2": {
    "Name": "Task 2",
    "Start": "2020-04-08",
    "End": "2020-04-17",
    "Issues": {
      "Issue-1": {
        "Name": "Issue 1",
        "Status": "Done"
      },
      "Issue-2": {
        "Name": "Issue 2",
        "Status": "Done"
      },
      "Issue-3": {
        "Name": "Issue 3",
        "Status": "In Progress"
      },
      "Issue-4": {
        "Name": "Issue 4",
        "Status": "In Progress"
      },
      "Issue-5": {
        "Name": "Issue 5",
        "Status": "In Progress"
      },
      "Issue-6": {
        "Name": "Issue 6",
        "Status": "In Progress"
      }
    }
  },
}

What I would like to do is calculate how many Done issues there is per task.

This is what I have at the moment

Task.vue

getTasks(){

    $.each(this.tasks, function(key, value){

        var count = Object.keys(value.Issues).length;

        $.each(value.Issues, function(k, v){
            if(v.Status == "Done")
            {
                console.log(v.Status.length);
            }

        });
     });
},

This section

if(v.Status == "Done")
{
    console.log(v.Status.length);
}

finds all the issues that is done and this is where I'm stuck

Body:
You are using jQuery instead of vue. In vue.js you can use computed property with JavaScript higher-order function to iterate through the json data and filter the elements. Then get the length.

See this example:

new Vue({
  el: "#app",
  data: {
    tasks: {
      "Task-1": {
        "Name": "Task 1",
        "Start": "2020-04-08",
        "End": "2020-04-17",
        "Issues": {
          "Issue-1": {
            "Name": "Issue 1",
            "issueStatus": "Done"
          },
          "Issue-2": {
            "Name": "Issue 2",
            "Status": "Done"
          },
          "Issue-3": {
            "Name": "Issue 3",
            "Status": "Done"
          },
          "Issue-4": {
            "Name": "Issue 4",
            "Status": "Done"
          },
          "Issue-5": {
            "Name": "Issue 5",
            "Status": "Done"
          },
          "Issue-6": {
            "Name": "Issue 6",
            "Status": "Done"
          }
        }
      },
      "Task-2": {
        "Name": "Task 2",
        "Start": "2020-04-08",
        "End": "2020-04-17",
        "Issues": {
          "Issue-1": {
            "Name": "Issue 1",
            "Status": "Done"
          },
          "Issue-2": {
            "Name": "Issue 2",
            "Status": "Done"
          },
          "Issue-3": {
            "Name": "Issue 3",
            "Status": "In Progress"
          },
          "Issue-4": {
            "Name": "Issue 4",
            "Status": "In Progress"
          },
          "Issue-5": {
            "Name": "Issue 5",
            "Status": "In Progress"
          },
          "Issue-6": {
            "Name": "Issue 6",
            "Status": "In Progress"
          }
        }
      }
    }
  },
  computed: {
    doneLength: function() {
      // Map throught first keys
      const findDone = Object.keys(this.tasks).map(t => {
        // Get the issues object and filter based on required value (Done)
        return Object.keys(this.tasks[t].Issues).filter(i => {
          // return only matching values
          return this.tasks[t].Issues[i].Status == "Done";
        })
      });

      // flatten and get length
      return [].concat(...findDone).length;

    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>{{doneLength}}</div>


答:
You need to call the method by putting ()

```<code>print(f"c1 Alan , cevre: {c1.area()} , {c1.perimeter()} \n c2 alan , cevre: {c2.perimeter()} , {c2.area()}")
</code>```

Title: I can not see the result. There is is a kind of adress on the result

Body:
You need to call the method by putting ()

print(f"c1 Alan , cevre: {c1.area()} , {c1.perimeter()} \n c2 alan , cevre: {c2.perimeter()} , {c2.area()}")


问:
pivot rows certain values to columns
i have this table,

```<code>id activity type      start_date
1  a        type_o    01/01/20
1  b        type_o    05/01/20
1  c        type_o    07/01/20
1  d        type_o    23/01/20
1  e        type_o    24/01/20
2  a        type_k    08/01/20
2  b        type_k    10/01/20
2  c        type_k    11/01/20
2  d        type_k    12/01/20
3  a        type_h    12/01/20
3  c        type_h    13/01/20
3  e        type_h    14/01/20
</code>```

all activities are (a,b,c,d,e)
i want it to look like this,

```<code>id type     a         b         c         d         e
1  type_o   01/01/20  05/01/20  07/01/20  23/01/20  24/01/20
2  type_k   08/01/20  10/01/20  11/01/20  null      null
3  type_h   12/01/20  null      13/01/20  null      12/01/20
</code>```

where we compensate null in other activities not exists in some id's,
i don't understand the pivot keyword in sql, any help ?

答:
Use conditional aggregation:</p>

```<code>select id, type,
       max(case when activity = 'a' then start_date end) as a,
       max(case when activity = 'b' then start_date end) as b,
       max(case when activity = 'c' then start_date end) as c,
       max(case when activity = 'd' then start_date end) as d,
       max(case when activity = 'e' then start_date end) as e
from thistable
group by id, type;
</code>```

Title: pivot rows certain values to columns

Body:
i have this table,

id activity type      start_date
1  a        type_o    01/01/20
1  b        type_o    05/01/20
1  c        type_o    07/01/20
1  d        type_o    23/01/20
1  e        type_o    24/01/20
2  a        type_k    08/01/20
2  b        type_k    10/01/20
2  c        type_k    11/01/20
2  d        type_k    12/01/20
3  a        type_h    12/01/20
3  c        type_h    13/01/20
3  e        type_h    14/01/20

all activities are (a,b,c,d,e)
i want it to look like this,

id type     a         b         c         d         e
1  type_o   01/01/20  05/01/20  07/01/20  23/01/20  24/01/20
2  type_k   08/01/20  10/01/20  11/01/20  null      null
3  type_h   12/01/20  null      13/01/20  null      12/01/20

where we compensate null in other activities not exists in some id's,
i don't understand the pivot keyword in sql, any help ?

Body:
Use conditional aggregation:

select id, type,
       max(case when activity = 'a' then start_date end) as a,
       max(case when activity = 'b' then start_date end) as b,
       max(case when activity = 'c' then start_date end) as c,
       max(case when activity = 'd' then start_date end) as d,
       max(case when activity = 'e' then start_date end) as e
from thistable
group by id, type;


问:
How can I do cross validation on user-item interactions matrix for LightFM movie recommender system?
I have an interactions matrix (scipy.sparse.csr_matrix) from movielens dataset with movie ratings from users, and I am building a LightFM model with item_features. Right now I have the matrix divided into train and test, but how do I do cross-validation for it? How do I measure the efficiency?</p>

```<code>!pip install lightfm
from lightfm import LightFM, cross_validation
from lightfm.evaluation import precision_at_k, auc_score

train, test = cross_validation.random_train_test_split(user_item, test_percentage=0.25)
model_lightfm = LightFM(loss='warp', learning_rate=0.01, k=10)
model_lightfm.fit(train, item_features=item_features, epochs=50)

def recommend(model, user_id):
  n_users, n_items = train.shape
  best_rated = ratings_df[(ratings_df.userId == user_id) & (ratings_df.rating >= 4.5)].movieId.values

  known_positives = metadata.loc[metadata['MOVIEID'].isin(best_rated)].title_clean.values

  scores = model.predict(user_id, np.arange(n_items), item_features=item_features)
  top_items = metadata['title_clean'][np.argsort(-scores)]

  print("User %s likes:" % user_id)
  for k in known_positives[:10]:
    print(k)

  print("\nRecommended:")
  for x in top_items[:10]:
    print(x)

recommend(model_lightfm, 10)

train_precision = precision_at_k(model_lightfm, train, k=10, item_features=item_features).mean()
test_precision = precision_at_k(model_lightfm, test, k=10, item_features=item_features, train_interactions=train).mean()

train_auc = auc_score(model_lightfm, train, item_features=item_features).mean()
test_auc = auc_score(model_lightfm, test, item_features=item_features, train_interactions=train).mean()

print('Precision: train %.2f, test %.2f.' % (train_precision, test_precision))
print('AUC: train %.2f, test %.2f.' % (train_auc, test_auc))
</code>```

答:
The evaluation metrics available for lightFM are auc_score and precision@k.
You are calculating both the metrics, Precision and auc_score.
Efficiency of your model can be judged by looking at

auc_score for test - Tells you how good your model is, in predicting the right recommendation for users, considering all the movies predicted. Doesn't considers the order/rank of movies predicted.

precision_at_k for test - Tells you the precision of you model, at generating top k(10 in your case) predictions. Helps if you want to judge your model in generating top-n recommendations.

Body:
I have an interactions matrix (scipy.sparse.csr_matrix) from movielens dataset with movie ratings from users, and I am building a LightFM model with item_features. Right now I have the matrix divided into train and test, but how do I do cross-validation for it? How do I measure the efficiency?

!pip install lightfm
from lightfm import LightFM, cross_validation
from lightfm.evaluation import precision_at_k, auc_score

train, test = cross_validation.random_train_test_split(user_item, test_percentage=0.25)
model_lightfm = LightFM(loss='warp', learning_rate=0.01, k=10)
model_lightfm.fit(train, item_features=item_features, epochs=50)

def recommend(model, user_id):
  n_users, n_items = train.shape
  best_rated = ratings_df[(ratings_df.userId == user_id) & (ratings_df.rating >= 4.5)].movieId.values

  known_positives = metadata.loc[metadata['MOVIEID'].isin(best_rated)].title_clean.values

  scores = model.predict(user_id, np.arange(n_items), item_features=item_features)
  top_items = metadata['title_clean'][np.argsort(-scores)]

  print("User %s likes:" % user_id)
  for k in known_positives[:10]:
    print(k)

  print("\nRecommended:")
  for x in top_items[:10]:
    print(x)

recommend(model_lightfm, 10)

train_precision = precision_at_k(model_lightfm, train, k=10, item_features=item_features).mean()
test_precision = precision_at_k(model_lightfm, test, k=10, item_features=item_features, train_interactions=train).mean()

train_auc = auc_score(model_lightfm, train, item_features=item_features).mean()
test_auc = auc_score(model_lightfm, test, item_features=item_features, train_interactions=train).mean()

print('Precision: train %.2f, test %.2f.' % (train_precision, test_precision))
print('AUC: train %.2f, test %.2f.' % (train_auc, test_auc))


问:
How to count 2 rows between 2 numbers in the same column
```<code>SELECT (COUNT (*))
FROM dbo.DIM_Calendar
WHERE (IdCalendar = 20190916  AND IdCalendar = 20191031)
</code>```

<p>The IDCalendar its an INT type, I would like to know the count between those 2 IdCalendars. </p>

答:
Maybe you're missing information. But what I understand what you want is as simple as use >= and <=

```<code> SELECT (COUNT (*))
 FROM dbo.DIM_Calendar
 WHERE (IdCalendar >= 20190916  AND IdCalendar <= 20191031)
</code>```

Body:
SELECT (COUNT (*))
FROM dbo.DIM_Calendar
WHERE (IdCalendar = 20190916  AND IdCalendar = 20191031)

The IDCalendar its an INT type, I would like to know the count between those 2 IdCalendars.

Body:
Maybe you're missing information. But what I understand what you want is as simple as use >= and <=

 SELECT (COUNT (*))
 FROM dbo.DIM_Calendar
 WHERE (IdCalendar >= 20190916  AND IdCalendar <= 20191031)