问:
How to extract values within square brackets fields in a json log
i am a newbie in the use of logstash and i need help with the following json log format:

```<code>{
"field1" :[
{
"sub_field1": {
"sub_field2":"value X"
"sub_field3": {"sub_field4":"value Y"}

}
"sub_field5":"value W"
}
]
}
</code>```

i want to know how to get Value X,Value Y and Value W using the mutate: "Add_field".

Thanks in advance!

答:
Assuming that you will only have one array element under field1, it's just:

```<code>add_field => {
  sub_field1 => '%{[field1][0][sub_field1]}'
  sub_field2 => '%{[field1][0][sub_field1][sub_field2]}'
...
}
</code>```

A good way to test this -- create a file called test.json

```<code>{ "field1" :[ { "sub_field1": { "sub_field2":"value X","sub_field3": {"sub_field4":"value Y"} }, "sub_field5":"value W" } ] }
</code>```

Create a config file like test.conf:

```<code>{
    stdin { codec => 'json_lines' }
}
filter {
    mutate {
        add_field => {
            sub_field1 => '%{[field1][0][sub_field1]}'
            sub_field2 => '%{[field1][0][sub_field1][sub_field2]}'
        }
    }
}

output {
    stdout { codec => "rubydebug" }
}
</code>```

And then run it: cat test.json | bin/logstash -f test.conf

You'll get output like this:

```<code>{
        "field1" => [
        [0] {
            "sub_field5" => "value W",
            "sub_field1" => {
                "sub_field3" => {
                    "sub_field4" => "value Y"
                },
                "sub_field2" => "value X"
            }
        }
    ],
    "@timestamp" => 2020-02-17T17:26:59.471Z,
      "@version" => "1",
          "host" => "xxxxxxxx",
    "sub_field2" => "value X",
    "sub_field1" => "{\"sub_field3\":{\"sub_field4\":\"value Y\"},\"sub_field2\":\"value X\"}",
          "tags" => []
}
</code>```

Which shows sub_field2 and sub_field1.

If you don't predictable field names then you'll need to resort to a ruby filter or something like that.  And if you have more than one element you need to spit out, you'll need to use a strategy that's discussed in the comments here: https://stackoverflow.com/a/45493411/2785358

Body:
i am a newbie in the use of logstash and i need help with the following json log format:

{
"field1" :[
{
"sub_field1": {
"sub_field2":"value X"
"sub_field3": {"sub_field4":"value Y"}

}
"sub_field5":"value W"
}
]
}

i want to know how to get Value X,Value Y and Value W using the mutate: "Add_field".

Thanks in advance!

Body:
Assuming that you will only have one array element under field1, it's just:

add_field => {
  sub_field1 => '%{[field1][0][sub_field1]}'
  sub_field2 => '%{[field1][0][sub_field1][sub_field2]}'
...
}

A good way to test this -- create a file called test.json

{ "field1" :[ { "sub_field1": { "sub_field2":"value X","sub_field3": {"sub_field4":"value Y"} }, "sub_field5":"value W" } ] }

Create a config file like test.conf:

{
    stdin { codec => 'json_lines' }
}
filter {
    mutate {
        add_field => {
            sub_field1 => '%{[field1][0][sub_field1]}'
            sub_field2 => '%{[field1][0][sub_field1][sub_field2]}'
        }
    }
}

output {
    stdout { codec => "rubydebug" }
}

And then run it: cat test.json | bin/logstash -f test.conf

You'll get output like this:

{
        "field1" => [
        [0] {
            "sub_field5" => "value W",
            "sub_field1" => {
                "sub_field3" => {
                    "sub_field4" => "value Y"
                },
                "sub_field2" => "value X"
            }
        }
    ],
    "@timestamp" => 2020-02-17T17:26:59.471Z,
      "@version" => "1",
          "host" => "xxxxxxxx",
    "sub_field2" => "value X",
    "sub_field1" => "{\"sub_field3\":{\"sub_field4\":\"value Y\"},\"sub_field2\":\"value X\"}",
          "tags" => []
}

Which shows sub_field2 and sub_field1.

If you don't predictable field names then you'll need to resort to a ruby filter or something like that.  And if you have more than one element you need to spit out, you'll need to use a strategy that's discussed in the comments here: https://stackoverflow.com/a/45493411/2785358


来源: stackexchange

问:
GLuint not being recognised
I am creating a 3D application in OpenGL, and in order to display textures on the models that I'm reading in, I'm using GLuint. However, I am getting the visual studio error C4430 missing type, and a handful of others related to the issue.

The glut files are included and were working fine before this was put in. Is it that GLuint is outdated, or something else?

Edit:
The code that has changed is:

Object constructor before

```<code>Object::Object(string shapeFileName, string texFileName){
    readFile(shapeFileName);
    loadTexture(texFileName);
}
</code>```

Object constructor afterwards

```<code>Object::Object(string shapeFileName, string texFileName){
    readFile(shapeFileName);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    loadTexture(texFileName);
    gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 1024, 512, GL_RGB, GL_UNSIGNED_BYTE, image_array);

    free(image_array);

    glTexImage2D(GL_TEXTURE_2D, 0, 3, 1024, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, image_array);
}
</code>```

Along with the line GLuint texture; added in the header file, which is the only bit that is throwing an error.

答:
For iOS you need to link OpenGLES.framework to your target and import header in your code:</p>

```<code>#import <OpenGLES/gltypes.h>
</code>```

ContentLicense: CC BY-SA 3.0

Title: GLuint not being recognised

Body:
I am creating a 3D application in OpenGL, and in order to display textures on the models that I'm reading in, I'm using GLuint. However, I am getting the visual studio error C4430 missing type, and a handful of others related to the issue.

The glut files are included and were working fine before this was put in. Is it that GLuint is outdated, or something else?

Edit:
The code that has changed is:

Object constructor before

Object::Object(string shapeFileName, string texFileName){
    readFile(shapeFileName);
    loadTexture(texFileName);
}

Object constructor afterwards

Object::Object(string shapeFileName, string texFileName){
    readFile(shapeFileName);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    loadTexture(texFileName);
    gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 1024, 512, GL_RGB, GL_UNSIGNED_BYTE, image_array);

    free(image_array);

    glTexImage2D(GL_TEXTURE_2D, 0, 3, 1024, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, image_array);
}

Along with the line GLuint texture; added in the header file, which is the only bit that is throwing an error.

Body:
For iOS you need to link OpenGLES.framework to your target and import header in your code:

#import <OpenGLES/gltypes.h>

ContentLicense: CC BY-SA 4.0


问:
Many kubernetes secrets vs many keys in one k8s secret
Imagine a complex deployment with many dependencies that needs to connect to lots of things, and where the secrets is only used this current namespace with this one complex deployment.

Would you recommend having many secrets:

certificates.yaml

redis-password.yaml

gcp-credentials.yaml

etc....

Or one secret for the deployment with lots of keys:

```<code>apiVersion: v1
kind: Secret
metadata:
  name: all-the-secrets
data:
  redis-password: asdfa
  certificate-key: asdfadf
  certificatee-crt: adfadf
  ...
</code>```

The secrets will be used as environment variables:

```<code>name: redis-password
valueFrom:
  secretKeyRef:
    name: secret-name
    key: key-name

</code>```

And why is one better than the other?

Ps. They will all be encrypted with kubeseal

答:
There is no difference for your pod whether its many secrets or one. Whenever there's a change your pod needs to know about it. The suggestion is if your files are independent then keep them separate to avoid changing the same secret again even if there's a change in one single file. This will only help you in managing your secrets. This will also help if you want to have different RBAC for different secrets.
If you are not planning to change them, then one secret is also fine.</p>

Body:
Imagine a complex deployment with many dependencies that needs to connect to lots of things, and where the secrets is only used this current namespace with this one complex deployment.

Would you recommend having many secrets:

certificates.yaml

redis-password.yaml

gcp-credentials.yaml

etc....

Or one secret for the deployment with lots of keys:

apiVersion: v1
kind: Secret
metadata:
  name: all-the-secrets
data:
  redis-password: asdfa
  certificate-key: asdfadf
  certificatee-crt: adfadf
  ...

The secrets will be used as environment variables:

name: redis-password
valueFrom:
  secretKeyRef:
    name: secret-name
    key: key-name

And why is one better than the other?

Ps. They will all be encrypted with kubeseal


问:
How to run bash commands from array?
I have three commands I running in shell file (app.sh):

```<code>docker-compose -f .docker/docker-compose.my-app1.yml push my-app1
docker-compose -f .docker/docker-compose.my-app2.yml push my-app2
docker-compose -f .docker/docker-compose.my-app3.yml push my-app3
</code>```

how to create array and pass the values to command with foreach?

say if it's was nodejs I'll do:

```<code>['my-app1', 'my-app2', 'my-app3'].forEach(i => {

  … `-f .docker/docker-compose.${i}.yml push ${i}` ...;
})
</code>```

答:
In BASH you can have arrays and for loops as follows

```<code>arr=( 'my-app1' 'my-app2' 'my-app3' )

for i in "${arr[@]}" ; do
   docker-compose -f ".docker/docker-compose.${i}.yml" push "${i}"
done
</code>```

Note, that you do not need to use commas to separate array elements as whitespace is a token separator in BASH.

Title: How to run bash commands from array?

Body:
I have three commands I running in shell file (app.sh):

docker-compose -f .docker/docker-compose.my-app1.yml push my-app1
docker-compose -f .docker/docker-compose.my-app2.yml push my-app2
docker-compose -f .docker/docker-compose.my-app3.yml push my-app3

how to create array and pass the values to command with foreach?

say if it's was nodejs I'll do:

['my-app1', 'my-app2', 'my-app3'].forEach(i => {

  … `-f .docker/docker-compose.${i}.yml push ${i}` ...;
})

Body:
In BASH you can have arrays and for loops as follows

arr=( 'my-app1' 'my-app2' 'my-app3' )

for i in "${arr[@]}" ; do
   docker-compose -f ".docker/docker-compose.${i}.yml" push "${i}"
done

Note, that you do not need to use commas to separate array elements as whitespace is a token separator in BASH.


问:
Populating subfield from other collections (not refs)
I am trying to populate subfields of a document, which are not defined as refs. The problem is that mongoose keeps returning null, whenever I try to fetch the document and populate the fields.

I will try to make this a generic question. I haven't found an answer anywhere online.

schemaA:

```<code>const schemaA = new Schema({
  before: {
    type: Object,
    default: {}
  },
  after: {
    type: Object,
    default: {}
  }
});

module.exports = SchemaA = mongoose.model("schemaA", schemaA);
</code>```

schemaB:

```<code>const schemaB = new Schema({
  someField: {
    subFieldA: {
      type: String
    },
    subFieldB: {
      type: String
    }
  }
});

module.exports = SchemaB = mongoose.model("schemaB", schemaB);
</code>```

And an example document that would exist in schemaA is:

```<code>_id: ObjectId('5e4ab79d9d3ce8633aedf524')
before: {
  someField: {
    subFieldA: ObjectId('5e4ab74f9d3ce8633aedf2eb'),
    subFieldB: ObjectId('5e4ab74f9d3ce8633aedf2ep')
  },
}
after: {
  someField: {
    subFieldA: ObjectId('5e4ab74f9d4ce8633aedf2eb'),
    subFieldB: ObjectId('5e4ab74f9d3ce8639aedf2ep')
  },
}
date: 2020-02-17T15:56:13.340+00:00
</code>```

My query:

```<code>const schemaAs = await SchemaA.find()
  .populate(
    "before.someField.subFieldA, before.someField.subFieldB, after.someField.subFieldA, after.someField.subFieldB"
  )
</code>```

But this query returns null. What am I doing wrong?

答:
You are looking for Dynamic References.
This lets you set what collection you are referencing as a property to each individual document, instead of hard coding it to one specific collection.

As far as I know, it is not possible to populate a property without any reference.

Body:
I am trying to populate subfields of a document, which are not defined as refs. The problem is that mongoose keeps returning null, whenever I try to fetch the document and populate the fields.

I will try to make this a generic question. I haven't found an answer anywhere online.

schemaA:

const schemaA = new Schema({
  before: {
    type: Object,
    default: {}
  },
  after: {
    type: Object,
    default: {}
  }
});

module.exports = SchemaA = mongoose.model("schemaA", schemaA);

schemaB:

const schemaB = new Schema({
  someField: {
    subFieldA: {
      type: String
    },
    subFieldB: {
      type: String
    }
  }
});

module.exports = SchemaB = mongoose.model("schemaB", schemaB);

And an example document that would exist in schemaA is:

_id: ObjectId('5e4ab79d9d3ce8633aedf524')
before: {
  someField: {
    subFieldA: ObjectId('5e4ab74f9d3ce8633aedf2eb'),
    subFieldB: ObjectId('5e4ab74f9d3ce8633aedf2ep')
  },
}
after: {
  someField: {
    subFieldA: ObjectId('5e4ab74f9d4ce8633aedf2eb'),
    subFieldB: ObjectId('5e4ab74f9d3ce8639aedf2ep')
  },
}
date: 2020-02-17T15:56:13.340+00:00

My query:

const schemaAs = await SchemaA.find()
  .populate(
    "before.someField.subFieldA, before.someField.subFieldB, after.someField.subFieldA, after.someField.subFieldB"
  )

But this query returns null. What am I doing wrong?


问:
Jquery Cookie plugin, check to see if cookie is unset
So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:

```<code>if ($.cookie('language')==null) {

}
</code>```

This doesn't seem to work. Any ideas why?

答:
To see what the plugin is returning, do a console.log() call:

```<code>console.log($.cookie("language"));
</code>```

This should tell you what is being returned from the plugin if you monitor your Inspector / Firebug console.

I think you can get away with just doing if($.cookie("language")) but you'll have to test that.

Body:
So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:

if ($.cookie('language')==null) {

}

This doesn't seem to work. Any ideas why?

Body:
To see what the plugin is returning, do a console.log() call:

console.log($.cookie("language"));

This should tell you what is being returned from the plugin if you monitor your Inspector / Firebug console.

I think you can get away with just doing if($.cookie("language")) but you'll have to test that.


问:
Querying by id in Firestore Console
Currently, as far as I know, there is no command-line interface for querying Firestore. The only way to query our documents is to do it through our own program, or through Firestore console. In the console, the only way to query a document by its id is to use the browser "Find" feature. However, when the number of documents in a collection increases above a threshold, which I don't know, Google Chrome cannot find the id. It's very inconvenient to scroll through the list of documents and use the find function of the browser again and again to find the id.

Please advise a more efficient way or implement a more efficient way to query documents by id in Firestore Console.

答:
While you can't filter a collection by a document ID, you can find a document with a specific ID by entering it in the little address bar/breadcrumb trail that sits above your data structure in the console.

Steps:

Select the collection that the document is in

Hover over the breadcrumb trail at the top and click on the pencil icon

Enter a / and then the ID of the document

Hit Enter

The console will now load the document with the ID you entered.

Title: Querying by id in Firestore Console


问:
Google Script version of VLookup (More Efficient Method?)
I'm trying to put together a function that will allow me to pull a column's info from one sheet to another based on a key column. This would work similar to an index match or vlookup in excel/google.

Sample Data:

What I've tried:

```<code>function vlookup(importFromSht, importToSht, importFromCompCol, importToCompCol,importFromCol, importToCol){
  var lastImportFromRN = importFromSht.getLastRow();
  var lastImportToRN = importToSht.getLastRow();
  var importFromCompArr =  importFromSht.getRange(2, importFromCompCol, lastImportFromRN, 1).getValues();
  var importToCompArr =  importToSht.getRange(2, importToCompCol, lastImportToRN, 1).getValues();
  var importFromArr =  importFromSht.getRange(2, importFromCol, lastImportFromRN, 1).getValues();
  var importToArr = [];

  for (var i in importToCompArr) {
    for (var j in importFromCompArr){
      if (importToCompArr[i].toString() == importFromCompArr[j].toString()) {
        importToArr.push(importFromArr[j]);
      }
    }
  }

  //Paste to column
  importToSht.getRange(2,importToCol,importToArr.length,1).setValues(importToArr);
}
</code>```

Parameters Defined

importFromSht - Sheet we are grabbing values from.

importToSht - Sheet values will be copied to.

importFromCompCol - Column (number) that has values to match on.

importToCompCol - Column (number) that has values to match on.

importFromCol - Column (number) that contains value that needs to be copied.

importToCol - Column (number) to copy value to.

Requirements:

There are over 6K rows minimum and could be many more thousand. Speed of execution is important. Is my approach the correct approach or are there more efficient methods? My script added about 30 seconds to my execution time.

Would like to call it as a function as I can see myself using this in other areas of this projects and other projects.

答:
Issue:

Slow script:

O(n2): For every  element in array 1, the array 2 is iterated from top to bottom. Even  after finding a match in array 2, the loop is not broken(break), but the inner loop is completed until the end of the array2 unnecessarily.

getValues()  is  requested twice for  two columns of the same sheet. Contact with spreadsheet is costly. So, limiting it is necessary.

Solution:

One possible solution to achieve O(n):

Create a new object  using array 1 with key as 'the value to look for'. Then it's possible to directly access the value in this object each time for each value in array 2.

Sample script:

```<code>const ss = SpreadsheetApp.getActive();
/**
 * @param {GoogleAppsScript.Spreadsheet.Sheet} fromSht -Sheet to import from
 * @param {GoogleAppsScript.Spreadsheet.Sheet} toSht -Sheet to import to
 * @param {Number} fromCompCol -Column number of fromSht to compare
 * @param {Number} toCompCol -Column number of toSht to compare
 * @param {Number} fromCol -Column number of fromSht to get result
 * @param {Number} toCol -Column number of toSht to get result
 * @author https://stackoverflow.com/users/8404453
 */
function vlookup_custom(
  fromSht = ss.getSheetByName('Sheet1'),
  toSht = ss.getSheetByName('Sheet2'),
  fromCompCol = 1,
  toCompCol = 1,
  fromCol = 2,
  toCol = 2
) {
  const toShtLr = toSht.getLastRow();
  const toCompArr = toSht.getRange(2, toCompCol, toShtLr - 1, 1).getValues();
  const fromArr = fromSht.getDataRange().getValues();
  fromCompCol--;
  fromCol--;

  /*Create a hash object of fromSheet*/
  const obj1 = fromArr.reduce((obj, row) => {
    let el = row[fromCompCol];
    el in obj ? null : (obj[el] = row[fromCol]);
    return obj;
  }, {});

  //Paste to column
  toSht
    .getRange(2, toCol, toShtLr - 1, 1)
    .setValues(toCompArr.map(row => (row[0] in obj1 ? [obj1[row[0]]] : [null])));
}

</code>```

Performance:

~5s for 10000 rows in sheet1 and 10000 rows in sheet 2

References:

Time complexity

Hash map

Body:
I'm trying to put together a function that will allow me to pull a column's info from one sheet to another based on a key column. This would work similar to an index match or vlookup in excel/google.

Sample Data:

What I've tried:

function vlookup(importFromSht, importToSht, importFromCompCol, importToCompCol,importFromCol, importToCol){
  var lastImportFromRN = importFromSht.getLastRow();
  var lastImportToRN = importToSht.getLastRow();
  var importFromCompArr =  importFromSht.getRange(2, importFromCompCol, lastImportFromRN, 1).getValues();
  var importToCompArr =  importToSht.getRange(2, importToCompCol, lastImportToRN, 1).getValues();
  var importFromArr =  importFromSht.getRange(2, importFromCol, lastImportFromRN, 1).getValues();
  var importToArr = [];

  for (var i in importToCompArr) {
    for (var j in importFromCompArr){
      if (importToCompArr[i].toString() == importFromCompArr[j].toString()) {
        importToArr.push(importFromArr[j]);
      }
    }
  }

  //Paste to column
  importToSht.getRange(2,importToCol,importToArr.length,1).setValues(importToArr);
}

Parameters Defined

importFromSht - Sheet we are grabbing values from.

importToSht - Sheet values will be copied to.

importFromCompCol - Column (number) that has values to match on.

importToCompCol - Column (number) that has values to match on.

importFromCol - Column (number) that contains value that needs to be copied.

importToCol - Column (number) to copy value to.

Requirements:

There are over 6K rows minimum and could be many more thousand. Speed of execution is important. Is my approach the correct approach or are there more efficient methods? My script added about 30 seconds to my execution time.

Would like to call it as a function as I can see myself using this in other areas of this projects and other projects.

Body:
Issue:

Slow script:

O(n2): For every  element in array 1, the array 2 is iterated from top to bottom. Even  after finding a match in array 2, the loop is not broken(break), but the inner loop is completed until the end of the array2 unnecessarily.

getValues()  is  requested twice for  two columns of the same sheet. Contact with spreadsheet is costly. So, limiting it is necessary.

Solution:

One possible solution to achieve O(n):

Create a new object  using array 1 with key as 'the value to look for'. Then it's possible to directly access the value in this object each time for each value in array 2.

Sample script:

const ss = SpreadsheetApp.getActive();
/**
 * @param {GoogleAppsScript.Spreadsheet.Sheet} fromSht -Sheet to import from
 * @param {GoogleAppsScript.Spreadsheet.Sheet} toSht -Sheet to import to
 * @param {Number} fromCompCol -Column number of fromSht to compare
 * @param {Number} toCompCol -Column number of toSht to compare
 * @param {Number} fromCol -Column number of fromSht to get result
 * @param {Number} toCol -Column number of toSht to get result
 * @author https://stackoverflow.com/users/8404453
 */
function vlookup_custom(
  fromSht = ss.getSheetByName('Sheet1'),
  toSht = ss.getSheetByName('Sheet2'),
  fromCompCol = 1,
  toCompCol = 1,
  fromCol = 2,
  toCol = 2
) {
  const toShtLr = toSht.getLastRow();
  const toCompArr = toSht.getRange(2, toCompCol, toShtLr - 1, 1).getValues();
  const fromArr = fromSht.getDataRange().getValues();
  fromCompCol--;
  fromCol--;

  /*Create a hash object of fromSheet*/
  const obj1 = fromArr.reduce((obj, row) => {
    let el = row[fromCompCol];
    el in obj ? null : (obj[el] = row[fromCol]);
    return obj;
  }, {});

  //Paste to column
  toSht
    .getRange(2, toCol, toShtLr - 1, 1)
    .setValues(toCompArr.map(row => (row[0] in obj1 ? [obj1[row[0]]] : [null])));
}

Performance:

~5s for 10000 rows in sheet1 and 10000 rows in sheet 2

References:

Time complexity

Hash map


问:
for loop in c# for IDs of controls to read text of textbox
```<code><asp:TextBox ID="PFtxtname1" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname2" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname3" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname4" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname5" runat="server"></asp:TextBox>
.
.
.
<asp:TextBox ID="PFtxtname100" runat="server"></asp:TextBox>
</code>```

I need to create for loop to read all data of txt and save all in string array variable!

```<code>       //string[] arr = new string[100];
        //   for (int i = 0; i < 100; i++)
         //  {
               //arr[i] = (i+1).ToString();
               //i+=1;
               //TextBox mytext = new TextBox();
               //mytext.ID = "PFtxtname" + i;
               //TextBox txtbox = Page.FindControl("PFtxtname"+i) as TextBox;

               //i += 1;
               //arr[i] = txtbox.Text;
          //}
</code>```

答:
In the future, please provide any detail and data that can help us help you.  Also, do appropriate research prior to posting.  There are MANY different ways to do this, and it can differ between ASP.NET frameworks (forms/mvc/razor/etc); many of which have questions already asked and answered on stackoverflow.

In any case this should at least get you started. LINQ is your friend! (may need to add using)

    var listOfText = new List<string>();
    foreach (var textbox in this.Controls.OfType<TextBox>())
    {
        listOfText.Add(textbox.Text);
    }
```

Body:
<asp:TextBox ID="PFtxtname1" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname2" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname3" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname4" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname5" runat="server"></asp:TextBox>
.
.
.
<asp:TextBox ID="PFtxtname100" runat="server"></asp:TextBox>

I need to create for loop to read all data of txt and save all in string array variable!

       //string[] arr = new string[100];
        //   for (int i = 0; i < 100; i++)
         //  {
               //arr[i] = (i+1).ToString();
               //i+=1;
               //TextBox mytext = new TextBox();
               //mytext.ID = "PFtxtname" + i;
               //TextBox txtbox = Page.FindControl("PFtxtname"+i) as TextBox;

               //i += 1;
               //arr[i] = txtbox.Text;
          //}


问:
jquery change td text
```<code><td>09 Mars 2020</td>
</code>```

I have a div constructed using the above string.

the Jquery variables that I have

```<code>date1 = 09 Mars 2020
date2 = 18 Mars 2020
</code>```

I just wanted to add content from another date with that date to get a result like that

```<code><td>09 Mars 2020 - 18 Mars 2020</td>
</code>```

the td that I have on the html page has nothing id nothing name nothing to value there is that the date display and I know it on a variable it misses that like looking for it to find td

```<code><tr>
  <td>
    <table class="nobordernopadding" width="100%">
      <tbody>
        <tr>
          <td>Date prévue de livraison</td>
          <td align="right"><a href="/commande/card.php?action=editdate_livraison&id=56"><span class="fa fa-pencil marginleftonly valignmiddle pictoedit" style=" color: #444;" alt="Définir la date d'expédition" title="Définir la date d'expédition"></span></a>
          </td>
        </tr>
      </tbody>
    </table>
  </td>
  <td>09 Mars 2020</td>
</tr>
</code>```

答:
Given your provided markup, one possible path for selection is:</p>

```<code>$('.nobordernopadding')
    .closest('td')
    .next('td')
    // conditionally filter the td on the desired target text
    .filter(':contains("09 Mars 2020")')
    .text('my new value')
</code>```

Title: jquery change td text

Body:
09 Mars 2020

I have a div constructed using the above string.

the Jquery variables that I have

date1 = 09 Mars 2020
date2 = 18 Mars 2020

I just wanted to add content from another date with that date to get a result like that

09 Mars 2020 - 18 Mars 2020

the td that I have on the html page has nothing id nothing name nothing to value there is that the date display and I know it on a variable it misses that like looking for it to find td

          Date prévue de livraison

  09 Mars 2020

Body:
Given your provided markup, one possible path for selection is:

$('.nobordernopadding')
    .closest('td')
    .next('td')
    // conditionally filter the td on the desired target text
    .filter(':contains("09 Mars 2020")')
    .text('my new value')


问:
How to Get Mouse Scroll from Touchpad?
Input.mouseScrollDelta only changes for a physical mouse scroll wheel. It is not changing for a touch-pad two-finger scroll gesture (though the scroll icon does appear and otherwise works in other programs). Input.GetAxis("Mouse ScrollWheel") has the same effect. Input.touchCount (or anything touch related) is only for touch screens and doesn't help me make my own scroll check on a touch pad. So I'm out of ideas. How in the world am I supposed to know I'm scrolling on a laptop's touch pad?

答:
Since you've tagged it Unity3d,  maybe this will help you overcome: https://answers.unity.com/questions/356767/how-to-get-scrollwheel-values-using-a-laptop-touch.html

```<code>public void OnGUI()
 {
     if(Event.current.type == EventType.ScrollWheel)
         // do stuff with  Event.current.delta
         Debug.Log(Event.current.delta);
 }
</code>```

The OnGui documentation can be found here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnGUI.html

```<code>using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 150, 100), "I am a button"))
        {
            print("You clicked the button!");
        }
    }
}
</code>```

OnGUI is called for rendering and handling GUI events.

This means that your OnGUI implementation might be called several times per frame (one call per event). For more information on GUI events see the Event reference. If the MonoBehaviour's enabled property is set to false, OnGUI() will not be called.

Title: How to Get Mouse Scroll from Touchpad?

Body:
Since you've tagged it Unity3d,  maybe this will help you overcome: https://answers.unity.com/questions/356767/how-to-get-scrollwheel-values-using-a-laptop-touch.html

public void OnGUI()
 {
     if(Event.current.type == EventType.ScrollWheel)
         // do stuff with  Event.current.delta
         Debug.Log(Event.current.delta);
 }

The OnGui documentation can be found here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnGUI.html

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 150, 100), "I am a button"))
        {
            print("You clicked the button!");
        }
    }
}

OnGUI is called for rendering and handling GUI events.

This means that your OnGUI implementation might be called several times per frame (one call per event). For more information on GUI events see the Event reference. If the MonoBehaviour's enabled property is set to false, OnGUI() will not be called.


问:
I need the sum of numbers from a for-loop that is NOT in a list in Python
I'm having a problem returning the sum. I keep getting zero. </p>

<p>I commented the print results for better understanding. Again, my code is returning 0, and not 11. </p>

```<code>
A = [1, 5, 2, 1, 4, 0]

def solution(A):

    start = [i - j for i, j in enumerate(A)]

    start.sort()     #[-4, -1, 0, 0, 2, 5]

    for i in range(0, len(A)):
        pair = 0

        end = i + A[i]   #1, 6, 4, 4, 8, 5

        count = bisect_right(start, end)     #4, 6, 5, 5, 6, 6

        count_1 = count-1        #3, 5, 4, 4, 5, 5
        count_2 = count_1 - i    #3, 4, 2, 1, 1, 0
        pair += count_2          #???????  I need the above added together like this 3+4+2+1+1+0 since
                                           that's the answer.

    return pair

print(solution(A))
</code>```

答:
As you've written in the comments, the last count2 is zero.

You're adding zero to zero, the loop ends, and you return zero.

You need to start the counter outside the loop, or you can sum outside too, like so

```<code>counts = []
for i, x in enumerate(A):
   counts.append(bisect_right(start, i + x) - 1 - i)
return sum(counts)
</code>```

Which could be rewritten

```<code>return sum(bisect_right(start, i + x) - 1 - i for for i, x in enumerate(A))
</code>```

Body:
I'm having a problem returning the sum. I keep getting zero.

I commented the print results for better understanding. Again, my code is returning 0, and not 11.

A = [1, 5, 2, 1, 4, 0]

def solution(A):

    start = [i - j for i, j in enumerate(A)]

    start.sort()     #[-4, -1, 0, 0, 2, 5]

    for i in range(0, len(A)):
        pair = 0

        end = i + A[i]   #1, 6, 4, 4, 8, 5

        count = bisect_right(start, end)     #4, 6, 5, 5, 6, 6

        count_1 = count-1        #3, 5, 4, 4, 5, 5
        count_2 = count_1 - i    #3, 4, 2, 1, 1, 0
        pair += count_2          #???????  I need the above added together like this 3+4+2+1+1+0 since
                                           that's the answer.

    return pair

print(solution(A))

Body:
As you've written in the comments, the last count2 is zero.

You're adding zero to zero, the loop ends, and you return zero.

You need to start the counter outside the loop, or you can sum outside too, like so

counts = []
for i, x in enumerate(A):
   counts.append(bisect_right(start, i + x) - 1 - i)
return sum(counts)

Which could be rewritten

return sum(bisect_right(start, i + x) - 1 - i for for i, x in enumerate(A))


问:
Gravity forms: exporting two forms of entries data to one CSV file
I'm wondering if I can export two deferent forms entries based on the submitter id but with a specific concept,
The concept is:
If the entry title from the first form == some entry field of the other form, let's show these two entries in the exported data in one row, and so on, something like array_map in php.
I hope that you got the idea, any help to do that?
Thanks a lot,
Magdi</p>

答:
Use These Codes:
(first code returns data from csv file into an array)
(second code gets data from an array and save into a csv file)</p>

```<code>function csvExporter($path) {
    $csv = array();
    $row = 1;
    if (($handle = fopen($path, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            $csv[str_pad($row,4,0,STR_PAD_LEFT)] = array();
            for ($c = 0; $c < $num; $c++) {
                $csv[str_pad($row,4,0,STR_PAD_LEFT)][$c] = $data[$c];
            }
            $row++;
        }
        fclose($handle);
    }
    return $csv;
}
</code>```

```<code>function csvImporter($path,$array) {
    $csvFile = fopen($path,'w+');
    foreach ($array as $rows) {
        $eachRow = '[';
        foreach ($rows as $columns) {
            $eachRow .= '\'' . trim($columns,'\'') .'\',';
        }
        $eachRow .= ']' . PHP_EOL;
    }
    fclose($csvFile);
}
</code>```

Body:
Use These Codes:
(first code returns data from csv file into an array)
(second code gets data from an array and save into a csv file)

function csvExporter($path) {
    $csv = array();
    $row = 1;
    if (($handle = fopen($path, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            $csv[str_pad($row,4,0,STR_PAD_LEFT)] = array();
            for ($c = 0; $c < $num; $c++) {
                $csv[str_pad($row,4,0,STR_PAD_LEFT)][$c] = $data[$c];
            }
            $row++;
        }
        fclose($handle);
    }
    return $csv;
}

function csvImporter($path,$array) {
    $csvFile = fopen($path,'w+');
    foreach ($array as $rows) {
        $eachRow = '[';
        foreach ($rows as $columns) {
            $eachRow .= '\'' . trim($columns,'\'') .'\',';
        }
        $eachRow .= ']' . PHP_EOL;
    }
    fclose($csvFile);
}


问:
Async Loading of a TreeView
Hey I am very new to tornadofx struggeling with async loading of data for the treeview. I am loading categories from a rest endpoint, which I want to show in there.

It seems like there's no direct data binding to the children.

when using 'bindChildren' I can provide the observable list, but I have to convert them into Node's. which then would make the populate block kind of obsolete.

What's the recommended way of doing this? I cannot find anything about this.

```<code>// Category
interface Category<T : Category<T>> {
  val id: String
  val name: String
  val subcategories: List<T>?
}

//default category:
class DefaultCategory(override val name: String) : Category<DefaultCategory> {
  override val id: String = "default"
  override val subcategories: List<DefaultCategory>? = null
}
//ViewModel
class CategoryViewModel : ViewModel() {
  val sourceProperty = SimpleListProperty<Category<*>>()
  fun loadData() {
    // load items for treeview into 'newItems'
    sourceProperty.value = newItems
  }
}

// TreeViewFactoryMethod
private fun createTreeView(
  listProperty: SimpleListProperty<Category<*>>
): TreeView<Category<*>> {
  return treeview {
    root = TreeItem(DefaultCategory("Categories"))
    isShowRoot = false
    root.isExpanded = true
    root.children.forEach { it.isExpanded = true }
    cellFormat { text = it.name }
    populate { parent ->
      when (parent) {
        root -> listProperty.value
        else -> parent.value.subcategories
      }
    }
  }
}
</code>```

Assuming that on a button click I call viewmodel.loadData(), I would expect the TreeView to update as soon as there's some new data. (If I would've found a way to bind)

答:
I've never had to use bindChildren for TornadoFX before and your use of async isn't very relevant to what I think is your primary problem. So, admittedly, this question kind of confused me at first but I'm guessing you're just wondering why the list isn't appearing in your TreeView? I've made a test example with changes to make it work.

```<code>// Category
interface Category<T : Category<T>> {
    val id: String
    val name: String
    val subcategories: List<T>?
}

//default category:
class DefaultCategory(override val name: String) : Category<DefaultCategory> {
    override val id: String = "default"
    override val subcategories: List<DefaultCategory>? = null
}
//Just a dummy category
class ChildCategory(override val name: String) : Category<ChildCategory> {
    override val id = name
    override val subcategories: List<ChildCategory>? = null
}

//ViewModel
class CategoryViewModel : ViewModel() {
    //filled with dummy data
    val sourceProperty = SimpleListProperty<Category<*>>(listOf(
            ChildCategory("Categorya"),
            ChildCategory("Categoryb"),
            ChildCategory("Categoryc"),
            ChildCategory("Categoryd")
    ).asObservable())

    fun loadData() {
        sourceProperty.asyncItems {
            //items grabbed somehow
            listOf(
                    ChildCategory("Category1"),
                    ChildCategory("Category2"),
                    ChildCategory("Category3"),
                    ChildCategory("Category4")
            ).asObservable()
        }
    }
}

class TestView : View() {
    val model: CategoryViewModel by inject()

    override val root = vbox(10) {
        button("Refresh Items").action {
            model.loadData()
        }
        add(createTreeView(model.sourceProperty))
    }

    // TreeViewFactoryMethod
    private fun createTreeView(
            listProperty: SimpleListProperty<Category<*>>
    ): TreeView<Category<*>> {
        return treeview {
            root = TreeItem(DefaultCategory("Categories"))
            isShowRoot = false
            root.isExpanded = true
            root.children.forEach { it.isExpanded = true }
            cellFormat { text = it.name }
            populate { parent ->
                when (parent) {
                    root -> listProperty
                    else -> parent.value.subcategories
                }
            }
        }
    }
}
</code>```

There are 2 important distinctions that are important.

1. The more relevant distinction is that inside the populate block, root -> listProperty is used instead of root.listProperty.value. This will make your list appear. The reason is that a SimpleListProperty is not a list, it holds a list. So, yes, passing in a plain list is perfectly valid (like how you passed in the value of the list property). But now that means the tree view isn't listening to your property, just the list you passed in. With that in mind, I would be considerate over the categories' subcategory lists are implemented as well.

2. Secondly, notice the use of asyncItems in the ViewModel. This will perform whatever task asynchronously, then set the items to list on success. You can even add fail or cancel blocks to it. I'd recommend using this, as long/intensive operations aren't supposed to be performed on the UI thread.

Title: Async Loading of a TreeView

Body:
Hey I am very new to tornadofx struggeling with async loading of data for the treeview. I am loading categories from a rest endpoint, which I want to show in there.

It seems like there's no direct data binding to the children.

when using 'bindChildren' I can provide the observable list, but I have to convert them into Node's. which then would make the populate block kind of obsolete.

What's the recommended way of doing this? I cannot find anything about this.

// Category
interface Category<T : Category<T>> {
  val id: String
  val name: String
  val subcategories: List<T>?
}

//default category:
class DefaultCategory(override val name: String) : Category<DefaultCategory> {
  override val id: String = "default"
  override val subcategories: List<DefaultCategory>? = null
}
//ViewModel
class CategoryViewModel : ViewModel() {
  val sourceProperty = SimpleListProperty<Category<*>>()
  fun loadData() {
    // load items for treeview into 'newItems'
    sourceProperty.value = newItems
  }
}

// TreeViewFactoryMethod
private fun createTreeView(
  listProperty: SimpleListProperty<Category<*>>
): TreeView<Category<*>> {
  return treeview {
    root = TreeItem(DefaultCategory("Categories"))
    isShowRoot = false
    root.isExpanded = true
    root.children.forEach { it.isExpanded = true }
    cellFormat { text = it.name }
    populate { parent ->
      when (parent) {
        root -> listProperty.value
        else -> parent.value.subcategories
      }
    }
  }
}

Assuming that on a button click I call viewmodel.loadData(), I would expect the TreeView to update as soon as there's some new data. (If I would've found a way to bind)

Body:
I've never had to use bindChildren for TornadoFX before and your use of async isn't very relevant to what I think is your primary problem. So, admittedly, this question kind of confused me at first but I'm guessing you're just wondering why the list isn't appearing in your TreeView? I've made a test example with changes to make it work.

// Category
interface Category<T : Category<T>> {
    val id: String
    val name: String
    val subcategories: List<T>?
}

//default category:
class DefaultCategory(override val name: String) : Category<DefaultCategory> {
    override val id: String = "default"
    override val subcategories: List<DefaultCategory>? = null
}
//Just a dummy category
class ChildCategory(override val name: String) : Category<ChildCategory> {
    override val id = name
    override val subcategories: List<ChildCategory>? = null
}

//ViewModel
class CategoryViewModel : ViewModel() {
    //filled with dummy data
    val sourceProperty = SimpleListProperty<Category<*>>(listOf(
            ChildCategory("Categorya"),
            ChildCategory("Categoryb"),
            ChildCategory("Categoryc"),
            ChildCategory("Categoryd")
    ).asObservable())

    fun loadData() {
        sourceProperty.asyncItems {
            //items grabbed somehow
            listOf(
                    ChildCategory("Category1"),
                    ChildCategory("Category2"),
                    ChildCategory("Category3"),
                    ChildCategory("Category4")
            ).asObservable()
        }
    }
}

class TestView : View() {
    val model: CategoryViewModel by inject()

    override val root = vbox(10) {
        button("Refresh Items").action {
            model.loadData()
        }
        add(createTreeView(model.sourceProperty))
    }

    // TreeViewFactoryMethod
    private fun createTreeView(
            listProperty: SimpleListProperty<Category<*>>
    ): TreeView<Category<*>> {
        return treeview {
            root = TreeItem(DefaultCategory("Categories"))
            isShowRoot = false
            root.isExpanded = true
            root.children.forEach { it.isExpanded = true }
            cellFormat { text = it.name }
            populate { parent ->
                when (parent) {
                    root -> listProperty
                    else -> parent.value.subcategories
                }
            }
        }
    }
}

There are 2 important distinctions that are important.

1. The more relevant distinction is that inside the populate block, root -> listProperty is used instead of root.listProperty.value. This will make your list appear. The reason is that a SimpleListProperty is not a list, it holds a list. So, yes, passing in a plain list is perfectly valid (like how you passed in the value of the list property). But now that means the tree view isn't listening to your property, just the list you passed in. With that in mind, I would be considerate over the categories' subcategory lists are implemented as well.

2. Secondly, notice the use of asyncItems in the ViewModel. This will perform whatever task asynchronously, then set the items to list on success. You can even add fail or cancel blocks to it. I'd recommend using this, as long/intensive operations aren't supposed to be performed on the UI thread.


问:
type object 'datetime.datetime' has no attribute 'fromisoformat'
I have a script with the following import:

```<code>from datetime import datetime
</code>```

and a piece of code where I call:

```<code>datetime.fromisoformat(duedate)
</code>```

Sadly, when I run the script with an instance of Python 3.6, the console returns the following error:

AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'

I tried to run it from two instances of anaconda (3.7 and 3.8) and it works nice and smooth.
I supposed there was an import problem so I tried to copy datetime.py from anaconda/Lib to the script directory, with no success.

The datetime.py clearly contains the class datetime and the method fromisoformat but still it seems unlinked. I even tried to explicitly link the datetime.py file, with the same error:

```<code>parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'libs')
sys.path.append(vendor_dir+os.path.sep+"datetime.py")
</code>```

Can you help me? My ideas are over...

答:
The issue here is actually that fromisoformat is not available in Python versions older than 3.7, you can see that clearly stated in the documenation here.

```<code>Return a date corresponding to a date_string given in the format YYYY-MM-DD:
>>>

>>> from datetime import date
>>> date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)

This is the inverse of date.isoformat(). It only supports the format YYYY-MM-DD.

New in version 3.7.
</code>```

Body:
I have a script with the following import:

from datetime import datetime

and a piece of code where I call:

datetime.fromisoformat(duedate)

Sadly, when I run the script with an instance of Python 3.6, the console returns the following error:

AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'

I tried to run it from two instances of anaconda (3.7 and 3.8) and it works nice and smooth.
I supposed there was an import problem so I tried to copy datetime.py from anaconda/Lib to the script directory, with no success.

The datetime.py clearly contains the class datetime and the method fromisoformat but still it seems unlinked. I even tried to explicitly link the datetime.py file, with the same error:

parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'libs')
sys.path.append(vendor_dir+os.path.sep+"datetime.py")

Can you help me? My ideas are over...

Body:
The issue here is actually that fromisoformat is not available in Python versions older than 3.7, you can see that clearly stated in the documenation here.

Return a date corresponding to a date_string given in the format YYYY-MM-DD:
>>>

>>> from datetime import date
>>> date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)

This is the inverse of date.isoformat(). It only supports the format YYYY-MM-DD.

New in version 3.7.


问:
How to take data from aspx page to stored procedure?
I have to create an RDLC report in asp.net. For which I am writing a stored procedure using different scalar functions.
I have a GUI from which I have to select a criteria and collect data according to that criteria. The GUI is here:

I have implemented all cases like "All Staff", "All services", etc but the problem comes when I have to select specific records from list box and bring data according to that. For example I select specfic Staff records from list and my report should display the records only having that selected records.
How can I handle this? I mean when I select some records from listbox, how can I take these records to the where clause of my stored procedure and how to use it there?

I am using SQL SERVER 2008.
My Stored Procedure is:

```<code>USE [PC_Rewrite]
</code>```

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetClients]
(
    @orderBy varchar(50)
)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

```<code>-- Insert statements for procedure here
IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY c.LastName, c.FirstName, c.MiddleInit
END

ELSE IF(@orderBy = 'Consumer Address')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca on c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY ca.Address
END
</code>```

END

Any help would be appreciated.

答:
Does your stored procedure already exist?  If so, are there parameters you have to use?  Are you free to change the stored procedure as you see fit?

There are a number of options on how you can call the stored procedure.  Here are two: you can create an SqlCommand object and set it to use the stored procedure, then create SqlParameters for the various clauses in your where clause.  Eg A parameter for each of the options on your shown screen.  In the case of the list box, you may pass in a comma delimitered string but that depends on your db schema.

Another method is to use Linq To Sql and drag-drop the sproc onto the designer and have it create a method for you, then call it with the method parameters generated.

Sorry to not be more specific but it is affected by how stored procedure works.

Body:
I have to create an RDLC report in asp.net. For which I am writing a stored procedure using different scalar functions.
I have a GUI from which I have to select a criteria and collect data according to that criteria. The GUI is here:

I have implemented all cases like "All Staff", "All services", etc but the problem comes when I have to select specific records from list box and bring data according to that. For example I select specfic Staff records from list and my report should display the records only having that selected records.
How can I handle this? I mean when I select some records from listbox, how can I take these records to the where clause of my stored procedure and how to use it there?

I am using SQL SERVER 2008.
My Stored Procedure is:

USE [PC_Rewrite]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetClients]
(
    @orderBy varchar(50)
)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

-- Insert statements for procedure here
IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY c.LastName, c.FirstName, c.MiddleInit
END

ELSE IF(@orderBy = 'Consumer Address')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca on c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY ca.Address
END

END

Any help would be appreciated.


问:
16bit Texture with odd sized width is sheering
I am uploading a 35 x 100 16bpp texture with the following OpenGL command:

```<code>glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, 35, 100, 0, GL_RG, GL_UNSIGNED_BYTE, pixelData);
</code>```

But the resulting texture is sheered by one pixel toward the left as y increases (both when drawn and when inspected in gpu memory):

```<code>o o x o o               o o o x o
o o x o o               o o o o x
o o x o o               x o o o o
o o x o o               o x o o o
o o x o o  becomes->    o o x o o
</code>```

This type of sheering could occur if the width given differed from pixelData by one pixel, but the buffer and given dimensions are accurate.  Changing my texture to be 36 x 100 with no other changes fixes the issue as well.  This ONLY occurs for textures with an odd number as it's width.

My question is, is this a driver bug?  It was my understanding that non-POT textures were allowed on modern hardware, but this would suggest there's still some sort of unadvertised alignment requirement, perhaps specific to 16bpp textures; there's no mention of this behavior or requirement anywhere I could find at least.

答:
Textures have an alignment they must meet at the end of each scanline (horizontal row), usually a default of 4 bytes.  If this alignment isn't met, the texture will need padding at these locations that you yourself must provide in the uploaded pixel data.  This isn't usually a concern until you mix non-pow2 texture sizes with less than 32bit per pixel texture data.

Using glPixelStorei() can adjust this requirement to an alignment of 2 or 1 as necessary, or you can simply ensure texture sizes align to a multiple of 4 when dealing with 16bit textures.

Body:
I am uploading a 35 x 100 16bpp texture with the following OpenGL command:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, 35, 100, 0, GL_RG, GL_UNSIGNED_BYTE, pixelData);

But the resulting texture is sheered by one pixel toward the left as y increases (both when drawn and when inspected in gpu memory):

o o x o o               o o o x o
o o x o o               o o o o x
o o x o o               x o o o o
o o x o o               o x o o o
o o x o o  becomes->    o o x o o

This type of sheering could occur if the width given differed from pixelData by one pixel, but the buffer and given dimensions are accurate.  Changing my texture to be 36 x 100 with no other changes fixes the issue as well.  This ONLY occurs for textures with an odd number as it's width.

My question is, is this a driver bug?  It was my understanding that non-POT textures were allowed on modern hardware, but this would suggest there's still some sort of unadvertised alignment requirement, perhaps specific to 16bpp textures; there's no mention of this behavior or requirement anywhere I could find at least.


问:
Trying to understand subscribeActual()
This question asks what I want to know, but the answer doesn't explain it. Could someone share a concrete example that illustrates how to use subscribeActual() vs. subscribe()?

答:
I think I may have figured it out. Please comment:
When you write a custom Observable, you do it by extending the base class. But you want users to be able to subscribe()in the normal way. So the base class just forwards the call to your subscribeActual() method that does the actual work of subscribing.

Title: Trying to understand subscribeActual()


问:
How to save a tensor to a file in TensorFlow using the low level (C) interface?
Using the low level Operations in TensorFlow, I try to save a Tensor (its actual value) to a disk, but cannot find how to.
If the data is e.g. a UInt8 matrix representing an image then I can easily do EncodeJpeg to create the Content and then use WriteFile to write the generated Content to a file with a given name. Similarly EncodeWav works the same way.
On the other hand, if I just want to save a matrix with numbers, there is no "EncodeData", "TensorToContent" or similar Operation to convert the Tensor into a Content, what can be saved with WriteFile.
I can get the Tensor as an output from my Graph and then save it outside the Graph, but my purpose is to do it inside.</p>

答:
It took me some time, but finally found a solution, though it might not be the best. If you can improve, you're welcome.

So, I use the Save/Restore raw operation pair. It is relatively straight forward, once found.

"Save" has two tensor Inputs, one tensor InputList and one Attribute. The first tensor (scalar string) has to give the filename. The second tensor (1D string) contains the names you want to give to the tensors in the file (for Restore purposes later). The InputList is actually a collection of the tensors to be saved. The Attribute is a list of data types of the tensors to be saved.

"Restore" is also simple. It has two tensor Inputs, one tensor Output, one type Attribute and one optional integer Attribute. The first Input (scalar string) gives the file name or file pattern if more files can be looked at. The second Input (scalar string) gives the name (see above in "Save") of the tensor you want to find in the files. The Output is the loaded tensor itself. The type Attribute specifies what type is the tensor that will be loaded. The optional Attribute can be used if tensors with the same name exist in multiple files matching the pattern, telling which one is preferred.

The only thing to be careful with is the InputList in "Save". When the "Save" raw operation is added to the Graph at design time, the number of inputs in the Inputlist has to be given, as well as the (same number!) of types in the type list argument. This means that at runtime, when giving the actual names of the tensors and giving the tensorlist as the InputList, you cannot change anymore the number and data type of the tensors.


问:
R How to sample from an interrupted upside down bell curve
I've asked a related question before which successfully received an answer. Now I want to sample values from an upside down bell curve but exclude a range of values that fall in the middle of it like shown on the picture below:

I have this code currently working:

```<code>min <- 1
max <- 20
q <- min + (max-min)*rbeta(10000, 0.5, 0.5)
</code>```

How may I adapt it to achieve the desired output?

答:
Say you want a sample of 10,000 from your distribution but don't want any numbers between 5 and 15 in your sample. Why not just do:

```<code>q <- min + (max-min)*rbeta(50000, 0.5, 0.5);
q <- q[!(q > 5 & q < 15)][1:10000]
</code>```

Which gives you this:

```<code>hist(q)
</code>```

But still has the correct size:

```<code>length(q)
#> [1] 10000
</code>```

Body:
I've asked a related question before which successfully received an answer. Now I want to sample values from an upside down bell curve but exclude a range of values that fall in the middle of it like shown on the picture below:

I have this code currently working:

min <- 1
max <- 20
q <- min + (max-min)*rbeta(10000, 0.5, 0.5)

How may I adapt it to achieve the desired output?

Body:
Say you want a sample of 10,000 from your distribution but don't want any numbers between 5 and 15 in your sample. Why not just do:

q <- min + (max-min)*rbeta(50000, 0.5, 0.5);
q <- q[!(q > 5 & q < 15)][1:10000]

Which gives you this:

hist(q)

But still has the correct size:

length(q)
#> [1] 10000


问:
Does anyone have tried the HLF 2.0 feature "External Builders and Launchers" and wants to get in touch?
I'm getting my way through the HLF 2.0 docs and would love to discuss and try out the new features "External Builders and Launchers" and "Chaincode as an external service".
My goal is to run HLF2.0 on an K8s cluster (OpenShift). Does anyone wants to get in touch or has anyone already figured his way through?
Cheers from Germany</p>

答:
Also trying to use the ExternalBuilder.  Setup core.yaml, rebuilt the containers to use it. I get an error that on "peer lifecycle chaincode install .tgz...", that the path to the scripts in core.yaml can not be found.
I've added volume bind commands in the peer-base.yaml, and in docker-compose-cli.yaml, and am using the first-network setup.  Dropped out the part of the byfn.sh that would connect to the cli container, so that I do that part manually, do the create, join, update anchors successfully, and then try to do the install and fail.  However, on the install, I'm failing on the /bin/detect, because it can't find that file to fork/exec it.  To get that far, peer was able to read my external configuration, and read the core.yaml file.  At the moment, trying the "mode: dev" in the core.yaml which seems to indicate that the scripts and the chaincode will be run "locally", which I think means it should run in the cli container.  Otherwise, tried to walk the code to see how the docker containers are being created dynamically, and from what image, but haven't been able to nail that down yet.  </p>


问:
how to watch field in react (dynamically add useEffect)?
I am trying to watch a field which have watch:true field.In other words I want add useEffect dynamically.I have one json (which is coming from server).I want to watch field value (which have property watch:true).using it's value I want to update other field value .

here is my code

https://codesandbox.io/s/crimson-violet-uxbzd

see this object have watch: true, so I need to watch or check if it value is changed or not

```<code> {
     label: "First",
     name: "first",
     type: "select",
     remove: true,
     watch: true,
     options: ["", "one", "two"]
},
</code>```

if it's value is changed then call this function

```<code>const getSecondDropdownValue = function(value) {
    return new Promise((resolve, reject) => {
      if (value === "one") {
        setTimeout(function() {
          resolve(["three", "four"]);
        }, 1000);
      }

      if (value === "two") {
        setTimeout(function() {
          resolve(["five", "six"]);
        }, 1000);
      }
    });
  };
</code>```

any update?.

答:
Check if the item has watch property, if it does pass getSecondDropdownValue to onChange event of the select option. something like

```<code><select onChange={hasWatch ? getSecondDropdownValue : () => {}}>...</select>
</code>```

Create a component that will render select options.

```<code>// options = array of list options
// onChange = onchange event handler
// name = name of the select
const Option = ({ options, onChange, name }) =>
  (options.length && (
    <select onChange={(e) => onChange(e.target.value, name)}>
      {Array.isArray(options) &&
        options.map((option, index) => (
          <option value={option} key={option + index}>{option}</option>
        ))}
    </select>
  )) ||
  false;
</code>```

Add useState for storing the data from the api.

```<code>// initial data from the api
const [data, updateData] = useState(apiData);

// update select options and the list
const updateSelectData = (list, updated) => {

    const index = list.findIndex(item => item.name === updated.name);
    return [
      ...list.slice(0, index),
      Object.assign({}, list[index], updated),
      ...list.slice(index + 1)
    ];
  };
</code>```

getSecondDropdownValue function

```<code>const getSecondDropdownValue = function(value, name) {
  const updated = data.find(
    item => item.dependentField && item.dependentField[0] === name
  );

  // return new Promise((resolve, reject) => {
  if (value === "one") {
    // setTimeout(function() {
    // resolve(["three", "four"]);
    // }, 1000);
    updated.options = ["three", "four"];
  }

  if (value === "two") {
    // setTimeout(function() {
    // resolve(["five", "six"]);
    // }, 1000);
    updated.options = ["five", "six"];
  }
  // });

  updateData(updateSelectData(data, updated));
};
</code>```

Example

// Get a hook function
const {useState} = React;

const apiData = [
    {
      label: "First",
      name: "first",
      type: "select",
      watch: true,
      options: ["", "one", "two"]
    },
    {
      label: "Second",
      name: "second",
      options: [],
      dependentField: ["first"],
      type: "select"
    }
  ];

// option component
const Option = ({ options, onChange, name }) =>
  (options.length && (
    <select onChange={(e) => onChange(e.target.value, name)}>
      {Array.isArray(options) &&
        options.map((option, index) => (
          <option value={option} key={option + index}>{option}</option>
        ))}
    </select>
  )) ||
  false;

function App() {

  const [data, updateData] = useState(apiData);

  const updateSelectData = (list, updated) => {
    const index = list.findIndex(item => item.name === updated.name);
    return [
      ...list.slice(0, index),
      Object.assign({}, list[index], updated),
      ...list.slice(index + 1)
    ];
  };

  const getSecondDropdownValue = function(value, name) {
    const updated = data.find(
      item => item.dependentField && item.dependentField[0] === name
    );

    // return new Promise((resolve, reject) => {
    if (value === "one") {
      // setTimeout(function() {
      // resolve(["three", "four"]);
      // }, 1000);
      updated.options = ["three", "four"];
    }

    if (value === "two") {
      // setTimeout(function() {
      // resolve(["five", "six"]);
      // }, 1000);
      updated.options = ["five", "six"];
    }
    // });

    updateData(updateSelectData(data, updated));
  };

  return (

      {data.map((options, index) => (
        <Option
          name={options.name}
          key={index}
          onChange={options.watch ? getSecondDropdownValue : () => {}}
          options={options.options}
        />
      ))}

  );
}
// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Body:
I am trying to watch a field which have watch:true field.In other words I want add useEffect dynamically.I have one json (which is coming from server).I want to watch field value (which have property watch:true).using it's value I want to update other field value .

here is my code

https://codesandbox.io/s/crimson-violet-uxbzd

see this object have watch: true, so I need to watch or check if it value is changed or not

 {
     label: "First",
     name: "first",
     type: "select",
     remove: true,
     watch: true,
     options: ["", "one", "two"]
},

if it's value is changed then call this function

const getSecondDropdownValue = function(value) {
    return new Promise((resolve, reject) => {
      if (value === "one") {
        setTimeout(function() {
          resolve(["three", "four"]);
        }, 1000);
      }

      if (value === "two") {
        setTimeout(function() {
          resolve(["five", "six"]);
        }, 1000);
      }
    });
  };

any update?.

Body:
Check if the item has watch property, if it does pass getSecondDropdownValue to onChange event of the select option. something like

<select onChange={hasWatch ? getSecondDropdownValue : () => {}}>...</select>

Create a component that will render select options.

// options = array of list options
// onChange = onchange event handler
// name = name of the select
const Option = ({ options, onChange, name }) =>
  (options.length && (
    <select onChange={(e) => onChange(e.target.value, name)}>
      {Array.isArray(options) &&
        options.map((option, index) => (
          <option value={option} key={option + index}>{option}</option>
        ))}
    </select>
  )) ||
  false;

Add useState for storing the data from the api.

// initial data from the api
const [data, updateData] = useState(apiData);

// update select options and the list
const updateSelectData = (list, updated) => {

    const index = list.findIndex(item => item.name === updated.name);
    return [
      ...list.slice(0, index),
      Object.assign({}, list[index], updated),
      ...list.slice(index + 1)
    ];
  };

getSecondDropdownValue function

const getSecondDropdownValue = function(value, name) {
  const updated = data.find(
    item => item.dependentField && item.dependentField[0] === name
  );

  // return new Promise((resolve, reject) => {
  if (value === "one") {
    // setTimeout(function() {
    // resolve(["three", "four"]);
    // }, 1000);
    updated.options = ["three", "four"];
  }

  if (value === "two") {
    // setTimeout(function() {
    // resolve(["five", "six"]);
    // }, 1000);
    updated.options = ["five", "six"];
  }
  // });

  updateData(updateSelectData(data, updated));
};

Example

// Get a hook function
const {useState} = React;

const apiData = [
    {
      label: "First",
      name: "first",
      type: "select",
      watch: true,
      options: ["", "one", "two"]
    },
    {
      label: "Second",
      name: "second",
      options: [],
      dependentField: ["first"],
      type: "select"
    }
  ];

// option component
const Option = ({ options, onChange, name }) =>
  (options.length && (
    <select onChange={(e) => onChange(e.target.value, name)}>
      {Array.isArray(options) &&
        options.map((option, index) => (
          <option value={option} key={option + index}>{option}</option>
        ))}
    </select>
  )) ||
  false;

function App() {

  const [data, updateData] = useState(apiData);

  const updateSelectData = (list, updated) => {
    const index = list.findIndex(item => item.name === updated.name);
    return [
      ...list.slice(0, index),
      Object.assign({}, list[index], updated),
      ...list.slice(index + 1)
    ];
  };

  const getSecondDropdownValue = function(value, name) {
    const updated = data.find(
      item => item.dependentField && item.dependentField[0] === name
    );

    // return new Promise((resolve, reject) => {
    if (value === "one") {
      // setTimeout(function() {
      // resolve(["three", "four"]);
      // }, 1000);
      updated.options = ["three", "four"];
    }

    if (value === "two") {
      // setTimeout(function() {
      // resolve(["five", "six"]);
      // }, 1000);
      updated.options = ["five", "six"];
    }
    // });

    updateData(updateSelectData(data, updated));
  };

  return (
    <div className="App">
      {data.map((options, index) => (
        <Option
          name={options.name}
          key={index}
          onChange={options.watch ? getSecondDropdownValue : () => {}}
          options={options.options}
        />
      ))}
    </div>
  );
}
// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>


问:
the counter increases the value 100 times vuejs
I recently started learning wuejs. There was a task to get data from api, add it to the array and display the blocks with the date attribute through v-for. But I have the following output

ДИЕТА 600

dfhgsdfghdfgh 601

fghdfghdfghd 602

dfghdfghdfgh 603

dfghdfghdfghdfgh 604

dftghdfghdfghdfghfgh 605

(Right value counter)

C increasing the size of the array by 1 counter increases by 100, that is, if you add one element to the array next to each line, the values from 700 will be

CONSOLE:
[Vue warn]: You may have an infinite update loop in a component render function.

(found in )

I’ve seen a way with @, but the Razor syntax is bothering me, I don’t know how to connect them. And maybe this is not the problem. Help

html

```<code><div id="axiostest">
        <div v-for="item in message"  :data-testid="counter">
            <p class="text-danger">{{ item }} {{ counter++}}</p>
        </div>
    </div>
</code>```

vuejs

```<code>var axios = new Vue({
            el: '#axiostest',
            data: {
                message: [],
                counter: 0
            },
            methods: {

            },
            mounted() {
                axios
                    .get('/Profile/GetLastChallenge', {
                        params: {
                            userEmail: '@User.Identity.Name'
                        }
                    })
                    .then(response => (this.message = response.data));
            }
        });
</code>```

答:
If you have to just output the array you can use this:

{{ item }} {{ index }}

```

And you can do something you want with index^ {{index + 1}}, {{index * 2 }}, etc

And, as Estradiaz said, you get warn because counter++ occurs rerender

Body:
I recently started learning wuejs. There was a task to get data from api, add it to the array and display the blocks with the date attribute through v-for. But I have the following output

ДИЕТА 600

dfhgsdfghdfgh 601

fghdfghdfghd 602

dfghdfghdfgh 603

dfghdfghdfghdfgh 604

dftghdfghdfghdfghfgh 605

(Right value counter)

C increasing the size of the array by 1 counter increases by 100, that is, if you add one element to the array next to each line, the values from 700 will be

CONSOLE:
[Vue warn]: You may have an infinite update loop in a component render function.

(found in )

I’ve seen a way with @, but the Razor syntax is bothering me, I don’t know how to connect them. And maybe this is not the problem. Help

html

{{ item }} {{ counter++}}

vuejs

var axios = new Vue({
            el: '#axiostest',
            data: {
                message: [],
                counter: 0
            },
            methods: {

            },
            mounted() {
                axios
                    .get('/Profile/GetLastChallenge', {
                        params: {
                            userEmail: '@User.Identity.Name'
                        }
                    })
                    .then(response => (this.message = response.data));
            }
        });

Body:
If you have to just output the array you can use this:

<div id="axiostest">
    <div v-for="(item, index) in message"  :data-testid="index">
        <p class="text-danger">{{ item }} {{ index }}</p>
    </div>
</div>

And you can do something you want with index^ {{index + 1}}, {{index * 2 }}, etc

And, as Estradiaz said, you get warn because counter++ occurs rerender


问:
How can I split a vector into a vector of slices based on a separator?
If I have a vector such as

```<code>let mut bytes = vec![0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];
</code>```

I want to separate the vector by the 0x40 separator. Is there a clean way of doing this functionality?

expected output:
[[0x01, 0x02, 0x03], [0x04, 0x05], [0x06]]

答:
Use slice::split:

fn main() {
    let bytes = [0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];
    let pieces: Vec<_> = bytes
        .split(|&e| e == 0x40)
        .filter(|v| !v.is_empty())
        .collect();
    println!("{:?}", pieces)
}
```

See also:

How can slices be split using another slice as a delimiter?

In Rust, what's the idiomatic way to split a &str into an iterator of &strs of one character each?

Body:
If I have a vector such as

let mut bytes = vec![0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];

I want to separate the vector by the 0x40 separator. Is there a clean way of doing this functionality?

expected output:
[[0x01, 0x02, 0x03], [0x04, 0x05], [0x06]]

Body:
Use slice::split:

fn main() {
    let bytes = [0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];
    let pieces: Vec<_> = bytes
        .split(|&e| e == 0x40)
        .filter(|v| !v.is_empty())
        .collect();
    println!("{:?}", pieces)
}

See also:

How can slices be split using another slice as a delimiter?

In Rust, what's the idiomatic way to split a &str into an iterator of &strs of one character each?


问:
How to remove unnecessary numbers in DateTime
So, when I print DateTime.now() value, it shows those unnecessary numbers(on the screen the numbers are 323884). Is there any possibility on removing those numbers?
enter image description here</p>

答:
Let's Try This </p>

```<code>import datetime
date=str(datetime.datetime.now())
date.split('.')[0]
</code>```

Body:
Let's Try This

import datetime
date=str(datetime.datetime.now())
date.split('.')[0]


问:
Javascript function returns an object but the answer is undefined
I'm doing this quiz  question http://davidshariff.com/js-quiz/#q=2
The question is:

function aaa() {
  return
  {
    test: 1
  }
}
console.log(typeof aaa())```

The prompted answer for console.log is undefined but I thought it should be an 'object'

Can anyone explain why?

答:
You haven't copied the code correctly, indentation is important here. The original code is

```<code>function aaa() {
    return
    {
        test: 1
    };
}
alert(typeof aaa());
</code>```

As you can see there's a new line after return, which after automatic semicolon insertion (ASI), looks as follows:

```<code>function aaa() {
    return;
    {
        test: 1
    };
}
alert(typeof aaa());
</code>```

So the return result of this function will be undefined, since there's no return value and the code is unreachable after the return statement.

Body:
I'm doing this quiz  question http://davidshariff.com/js-quiz/#q=2
The question is:

function aaa() {
  return
  {
    test: 1
  }
}
console.log(typeof aaa())

The prompted answer for console.log is undefined but I thought it should be an 'object'

Can anyone explain why?

Body:
You haven't copied the code correctly, indentation is important here. The original code is

function aaa() {
    return
    {
        test: 1
    };
}
alert(typeof aaa());

As you can see there's a new line after return, which after automatic semicolon insertion (ASI), looks as follows:

function aaa() {
    return;
    {
        test: 1
    };
}
alert(typeof aaa());

So the return result of this function will be undefined, since there's no return value and the code is unreachable after the return statement.


问:
The current .NET SDK does not support targeting .NET Core 3.0 on TFS 2015 build
I am migrating an existing ASP.NET Core 2.2 web app to 3.0. I've updated the .csproj file and all references to support 3.0. Everything compiles on my dev machine, but when I try to build the app on the build server (TFS 2015 with the SDK / runtimes for ASP.NET Core 3.0) I get this error.

```<code>The current .NET SDK does not support targeting .NET Core 3.0. Either target .NET Core 2.2 or lower, or use a version of the .NET SDK that supports .NET Core 3.0
</code>```

I have correctly referenced the ASP.NET Core framework in the .csproj

Here are my project dependencies from my Visual Studio project.

Why does MSBUILD still try to reference ASP.NET Core 2.2 when everything now references 3.0?

答: After further investigation the problem was I didn't have the correct version of MSBUILD on the build server. As ASP.NET Core 3.0 only runs on VS2019 you therefore need MSBUILD for VS2019. After installing this on the build server the problem has now been resolved. </p>

Body:
I am migrating an existing ASP.NET Core 2.2 web app to 3.0. I've updated the .csproj file and all references to support 3.0. Everything compiles on my dev machine, but when I try to build the app on the build server (TFS 2015 with the SDK / runtimes for ASP.NET Core 3.0) I get this error.

The current .NET SDK does not support targeting .NET Core 3.0. Either target .NET Core 2.2 or lower, or use a version of the .NET SDK that supports .NET Core 3.0

I have correctly referenced the ASP.NET Core framework in the .csproj

Here are my project dependencies from my Visual Studio project.

Why does MSBUILD still try to reference ASP.NET Core 2.2 when everything now references 3.0?


问:
Increment column based on second column
Consider a dataframe like this:

```<code>dat <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, NA, NA, 12, 10, NA, NA, NA, 9, 10, 10, 11, NA, 11, 11, NA),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    NA 2008
3   John    NA 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    NA 2019
7    Sam    NA 2019
8    Sam    NA 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    NA 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    NA 2020
</code>```

I'd like to fill in the missing NAs in grade based on year.  So Sam for example is in 10th grade in 2018, and in 2019 he'll be in 11th grade:

```<code>dat_desired <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, 10, 11, 12, 10, 11, 11, 12, 9, 10, 10, 11, 10, 11, 11, 12),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    10 2008
3   John    11 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    11 2019
7    Sam    11 2019
8    Sam    12 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    10 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    12 2020
</code>```

How can I do this?  I've tried:

```<code>dat %>%
  group_by(name) %>%
  fill(grade, .direction = "updown")
</code>```

which doesn't work because it doesn't take year into account.  Adding a group_by(year) doesn't help either, because then no NAs are replaced.

答:
Could try:

```<code>dat %>%
  group_by(name) %>%
  mutate(
    grade = coalesce(grade, first(grade[!is.na(grade)]) - (first(year[!is.na(grade)]) - year))
  )
</code>```

Output:

```<code># A tibble: 16 x 3
# Groups:   name [4]
   name  grade  year
   <fct> <dbl> <dbl>
 1 John      9  2007
 2 John     10  2008
 3 John     11  2009
 4 John     12  2010
 5 Sam      10  2018
 6 Sam      11  2019
 7 Sam      11  2019
 8 Sam      12  2020
 9 Emily     9  2007
10 Emily    10  2008
11 Emily    10  2009
12 Emily    11  2010
13 Alex     10  2018
14 Alex     11  2019
15 Alex     11  2019
16 Alex     12  2020
</code>```

Title: Increment column based on second column

Body:
Consider a dataframe like this:

dat <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, NA, NA, 12, 10, NA, NA, NA, 9, 10, 10, 11, NA, 11, 11, NA),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    NA 2008
3   John    NA 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    NA 2019
7    Sam    NA 2019
8    Sam    NA 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    NA 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    NA 2020

I'd like to fill in the missing NAs in grade based on year.  So Sam for example is in 10th grade in 2018, and in 2019 he'll be in 11th grade:

dat_desired <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, 10, 11, 12, 10, 11, 11, 12, 9, 10, 10, 11, 10, 11, 11, 12),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    10 2008
3   John    11 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    11 2019
7    Sam    11 2019
8    Sam    12 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    10 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    12 2020

How can I do this?  I've tried:

dat %>%
  group_by(name) %>%
  fill(grade, .direction = "updown")

which doesn't work because it doesn't take year into account.  Adding a group_by(year) doesn't help either, because then no NAs are replaced.

Body:
Could try:

dat %>%
  group_by(name) %>%
  mutate(
    grade = coalesce(grade, first(grade[!is.na(grade)]) - (first(year[!is.na(grade)]) - year))
  )

Output:

# A tibble: 16 x 3
# Groups:   name [4]
   name  grade  year
   <fct> <dbl> <dbl>
 1 John      9  2007
 2 John     10  2008
 3 John     11  2009
 4 John     12  2010
 5 Sam      10  2018
 6 Sam      11  2019
 7 Sam      11  2019
 8 Sam      12  2020
 9 Emily     9  2007
10 Emily    10  2008
11 Emily    10  2009
12 Emily    11  2010
13 Alex     10  2018
14 Alex     11  2019
15 Alex     11  2019
16 Alex     12  2020


问:
unix query to check if a date falls within a limit
I have a date variable which stores date like:

```<code>$date = 20100201  //2010, Feb, 01
</code>```

i want to check if the date i have fetched falls in the month of feb. can someone please help? new to unix.

Body:
I have a date variable which stores date like:

$date = 20100201  //2010, Feb, 01

i want to check if the date i have fetched falls in the month of feb. can someone please help? new to unix.

Body: if (( "${date:4:2}" == "02" ));then echo "February";fi


问:
retrieve forign key first value in laravel
I have three tables Products, Category and Images. Category and Image tables have relationship with Product table. when I have use $all_product = Product::with('category','image')->get();product information category information and image information are display successfully want i want is Question : how to retrieve the image arrays first value?

```<code>"all_objects": [
    {
        "id": 1,
        "name": "samsung",
        "price": "2000",
        "category_id": 1,
        "created_at": "2020-02-17 13:27:24",
        "updated_at": "2020-02-17 13:27:24",
        "category": {
            "id": 1,
            "category_name": "android",
            "created_at": "2020-02-17 13:26:42",
            "updated_at": "2020-02-17 13:26:42"
        },
        "image": [
            {
                "id": 1,
                "image_name": "image_787.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 2,
                "image_name": "image_539.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 3,
                "image_name": "image_606.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 4,
                "image_name": "image_102.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:26",
                "updated_at": "2020-02-17 13:27:26"
            }
        ]
    },
</code>```

答:
try this:

```<code>$all_product = App\Product::with(['category','image' => function ($query) {
    $query->first();
}])->get();
</code>```

see Constraining Eager Loads

Body:
I have three tables Products, Category and Images. Category and Image tables have relationship with Product table. when I have use $all_product = Product::with('category','image')->get();product information category information and image information are display successfully want i want is Question : how to retrieve the image arrays first value?

"all_objects": [
    {
        "id": 1,
        "name": "samsung",
        "price": "2000",
        "category_id": 1,
        "created_at": "2020-02-17 13:27:24",
        "updated_at": "2020-02-17 13:27:24",
        "category": {
            "id": 1,
            "category_name": "android",
            "created_at": "2020-02-17 13:26:42",
            "updated_at": "2020-02-17 13:26:42"
        },
        "image": [
            {
                "id": 1,
                "image_name": "image_787.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 2,
                "image_name": "image_539.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 3,
                "image_name": "image_606.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 4,
                "image_name": "image_102.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:26",
                "updated_at": "2020-02-17 13:27:26"
            }
        ]
    },

Body:
try this:

$all_product = App\Product::with(['category','image' => function ($query) {
    $query->first();
}])->get();

see Constraining Eager Loads


问:
Python: deployment using fabric library not working - ERROR: unknown command "deploy:3.6.3"
I have the following fabfile.py implementation that I have used to install the previous version (3.6.2) of my application:

```<code>from fabric.api import local, run, cd, env, lcd
from fabric.contrib.project import upload_project

git_source = 'git@bitbucket.org:somegitsource'
test_git = False
# Temporary folder defined relative to folder containing this script
temp_folder = '../temp'

def production():
    env.user = 'mywebapp'
    env.hosts = ['aHost']
    env.config = {
        'home': '/home/myDir'
    }

production()

def deploy(version):

    # go to correct location
    with cd(env.config['home']):
        run('mkdir {}'.format(version))
        with cd(version):

            # run and activate virtualenv
            run('virtualenv ve')
            run('. ve/bin/activate')

            checkout(version, test=test_git)

            run('rm -f production')
            with cd('code'):
                pass
                # run("./manage.py sitetree_resync_apps")
                # run("./manage.py migrate")

        run('ln -s {} production'.format(version))
        # sudo /home/myDir/bin/restart-server

def checkout(version):

    local('mkdir {}'.format(temp_folder))
    with lcd(temp_folder):
        # Checkout latest code to temp folder
        local('git clone --branch {0} {1} --depth 1 code'.format(version, git_source))
        # local("gulp")
        upload_project(remote_dir='.')
</code>```

after settings some environment variables the script defines a function called deploy.

The script stopped working. If I invoke it

fab deploy:3.6.3

I get the error:

ERROR: unknown command "deploy:3.6.3"

I have read the Fabric documentation but I cannot understand what I am doing wrongly

答:
Since you are declaring a function that you are calling (production), Fabric doesn't know which function is a task and which one isn't

You should first import the task decorator from fabric.api, and then wrap the deploy function with this decorator

Body:
I have the following fabfile.py implementation that I have used to install the previous version (3.6.2) of my application:

from fabric.api import local, run, cd, env, lcd
from fabric.contrib.project import upload_project

git_source = 'git@bitbucket.org:somegitsource'
test_git = False
# Temporary folder defined relative to folder containing this script
temp_folder = '../temp'

def production():
    env.user = 'mywebapp'
    env.hosts = ['aHost']
    env.config = {
        'home': '/home/myDir'
    }

production()

def deploy(version):

    # go to correct location
    with cd(env.config['home']):
        run('mkdir {}'.format(version))
        with cd(version):

            # run and activate virtualenv
            run('virtualenv ve')
            run('. ve/bin/activate')

            checkout(version, test=test_git)

            run('rm -f production')
            with cd('code'):
                pass
                # run("./manage.py sitetree_resync_apps")
                # run("./manage.py migrate")

        run('ln -s {} production'.format(version))
        # sudo /home/myDir/bin/restart-server

def checkout(version):

    local('mkdir {}'.format(temp_folder))
    with lcd(temp_folder):
        # Checkout latest code to temp folder
        local('git clone --branch {0} {1} --depth 1 code'.format(version, git_source))
        # local("gulp")
        upload_project(remote_dir='.')

after settings some environment variables the script defines a function called deploy.

The script stopped working. If I invoke it

fab deploy:3.6.3

I get the error:

ERROR: unknown command "deploy:3.6.3"

I have read the Fabric documentation but I cannot understand what I am doing wrongly