问:
Reactive Forms Not Updating Value In Form Field Angular 7
I'm having an issue where the values in my formgroup is not being updated on submission.

I have formgroup that brings in values from an api, (which is working) but when I am trying to update the value and pass it back, the values are not being updated. I'm lost on what I am doing wrong.

I'm using reactive forms with Angular 7.

modify-view-action.component.html

```<code>    <div fxLayout="column" fxLayoutGap="25px" class="modify-view-container">
  <mat-card class="view-settings-descrpition-card">
    <mat-card-content fxLayout="column">

      <form [formGroup]="modifyActionForm">
        <div class="container" fxLayout="row" fxLayoutGap="25px">
          <div class="column1" fxLayout="column">
            <p>Folder: {{dbrAction.FolderTag.Value}}</p>
            <p>Primary Table: {{dbrAction.PrimaryTable}}</p>
            <p>Special Use: {{dbrAction.SpecialUse}}</p>
            <mat-form-field>
              <mat-label>Name</mat-label>
              <input matInput formControlName="ActionName">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Keywords</mat-label>
              <input matInput formControlName="Keywords">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Description</mat-label>
              <input matInput formControlName="Description">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Icon</mat-label>
              <mat-select formControlName="Icon" ngDefaultControl>
                <mat-option formControlName="Icon"
                  ngDefaultControl>
                  {{dbrAction.Icon}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Priority</mat-label>
              <input matInput formControlName="Priority">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Title Font Size</mat-label>
              <mat-select formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                <mat-option formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                  {{dbrAction.TitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Subtitle Font Size</mat-label>
              <mat-select formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                <mat-option formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                  {{dbrAction.SubtitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Title Font Size</mat-label>
              <mat-select formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                <mat-option formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                  {{dbrAction.PrintTitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Subtitle Font Size</mat-label>
              <mat-select formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                <mat-option formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                  {{dbrAction.PrintSubtitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <!-- <mat-form-field>
              <mat-checkbox matInput formControlName="IsActive" [(ngModel)]="dbrAction.IsActive" [value]="dbrAction.IsActive" [labelPosition]="labelPosition">Is Active: </mat-checkbox>
            </mat-form-field> -->
          </div>
        </div>
      </form>
</code>```

modify-view-action.component.ts

```<code>    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'modify-view-action',
  templateUrl: './modify-view-action.component.html',
  styleUrls: ['./modify-view-action.component.scss']
})
export class ModifyViewActionComponent implements OnInit {
  objectData: any;

  constructor(private fb: FormBuilder) { }

  dbrAction: any;
  labelPosition: 'before' | 'after' = 'before';
  modifyActionForm: FormGroup;

  ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: new FormControl(this.dbrAction.FolderTag),
    PrimaryTable: new FormControl(this.dbrAction.PrimaryTable),
    SpecialUse: new FormControl(this.dbrAction.SpecialUse),
    ActionName: new FormControl(this.dbrAction.ActionName),
    Keywords: new FormControl(this.dbrAction.Keywords),
    Description: new FormControl(this.dbrAction.Description),
    Icon: new FormControl(this.dbrAction.Icon),
    Priority: new FormControl(this.dbrAction.Priority),
    TitleFontSize: new FormControl(this.dbrAction.TitleFontSize),
    SubtitleFontSize: new FormControl(this.dbrAction.SubtitleFontSize),
    PrintTitleSize: new FormControl(this.dbrAction.PrintTitleSize),
    PrintSubtitleSize: new FormControl(this.dbrAction.PrintSubtitleSize),
    IsActive: new FormControl(this.dbrAction.IsActive)
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }

  get f() { return this.modifyActionForm.controls; }

initData() {
    this.dbrAction = JSON.parse(localStorage.getItem('DbrAction'));
  }
}
</code>```

答:
I see that your formControls has same name as dbrAction properties, so you can use FormBuilder:
https://angular.io/api/forms/FormBuilder

```<code>this.modifyActionForm = this.formBuilder.group(this.dbAction);
</code>```

This will create a formGroup, with properties, and values of dbrAction (a fast way to create a formGroup with an object).

If you create the FormGroup manually (as you did), you can use patchValue function, to put value into each FormControl:

```<code>  this.modifyActionForm.patchValue({
     FolderTag: this.dbrAction.FolderTag,
     PrimaryTable: this.dbrAction.PrimaryTable,
     SpecialUse: this.dbrAction.SpecialUse,
     ActionName: this.dbrAction.ActionName
     ....
  })
</code>```

Hope it will helps you

Body:
I'm having an issue where the values in my formgroup is not being updated on submission.

I have formgroup that brings in values from an api, (which is working) but when I am trying to update the value and pass it back, the values are not being updated. I'm lost on what I am doing wrong.

I'm using reactive forms with Angular 7.

modify-view-action.component.html

  <mat-card class="view-settings-descrpition-card">
    <mat-card-content fxLayout="column">

      <form [formGroup]="modifyActionForm">

Folder: {{dbrAction.FolderTag.Value}}

Primary Table: {{dbrAction.PrimaryTable}}

Special Use: {{dbrAction.SpecialUse}}

            <mat-form-field>
              <mat-label>Name</mat-label>
              <input matInput formControlName="ActionName">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Keywords</mat-label>
              <input matInput formControlName="Keywords">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Description</mat-label>
              <input matInput formControlName="Description">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Icon</mat-label>
              <mat-select formControlName="Icon" ngDefaultControl>
                <mat-option formControlName="Icon"
                  ngDefaultControl>
                  {{dbrAction.Icon}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Priority</mat-label>
              <input matInput formControlName="Priority">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Title Font Size</mat-label>
              <mat-select formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                <mat-option formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                  {{dbrAction.TitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Subtitle Font Size</mat-label>
              <mat-select formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                <mat-option formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                  {{dbrAction.SubtitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Title Font Size</mat-label>
              <mat-select formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                <mat-option formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                  {{dbrAction.PrintTitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Subtitle Font Size</mat-label>
              <mat-select formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                <mat-option formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                  {{dbrAction.PrintSubtitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>

      </form>

modify-view-action.component.ts

    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'modify-view-action',
  templateUrl: './modify-view-action.component.html',
  styleUrls: ['./modify-view-action.component.scss']
})
export class ModifyViewActionComponent implements OnInit {
  objectData: any;

  constructor(private fb: FormBuilder) { }

  dbrAction: any;
  labelPosition: 'before' | 'after' = 'before';
  modifyActionForm: FormGroup;

  ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: new FormControl(this.dbrAction.FolderTag),
    PrimaryTable: new FormControl(this.dbrAction.PrimaryTable),
    SpecialUse: new FormControl(this.dbrAction.SpecialUse),
    ActionName: new FormControl(this.dbrAction.ActionName),
    Keywords: new FormControl(this.dbrAction.Keywords),
    Description: new FormControl(this.dbrAction.Description),
    Icon: new FormControl(this.dbrAction.Icon),
    Priority: new FormControl(this.dbrAction.Priority),
    TitleFontSize: new FormControl(this.dbrAction.TitleFontSize),
    SubtitleFontSize: new FormControl(this.dbrAction.SubtitleFontSize),
    PrintTitleSize: new FormControl(this.dbrAction.PrintTitleSize),
    PrintSubtitleSize: new FormControl(this.dbrAction.PrintSubtitleSize),
    IsActive: new FormControl(this.dbrAction.IsActive)
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }

  get f() { return this.modifyActionForm.controls; }

initData() {
    this.dbrAction = JSON.parse(localStorage.getItem('DbrAction'));
  }
}

Body:
I see that your formControls has same name as dbrAction properties, so you can use FormBuilder:
https://angular.io/api/forms/FormBuilder

this.modifyActionForm = this.formBuilder.group(this.dbAction);

This will create a formGroup, with properties, and values of dbrAction (a fast way to create a formGroup with an object).

If you create the FormGroup manually (as you did), you can use patchValue function, to put value into each FormControl:

  this.modifyActionForm.patchValue({
     FolderTag: this.dbrAction.FolderTag,
     PrimaryTable: this.dbrAction.PrimaryTable,
     SpecialUse: this.dbrAction.SpecialUse,
     ActionName: this.dbrAction.ActionName
     ....
  })

Hope it will helps you


来源: stackexchange

问:
How do i make thos work on any windows pc
So i wanted to make a program it grabs images from a certain path but it doesn twork on any other device than mine i dont wanna change the paths everytime so is there anyway to make

```<code>teti= open('C:/Users/hyper/OneDrive/Desktop/Database/Gpus/Nvidia/Nvidia-2080ti.txt', 'r')
</code>```

global accross all windows platforms

答:
You don't need to make it global you better search for the file you needed. You can just add this function and give your file name only (if you use windows) else you should give all the directories in a list in order to find the path</p>

```<code>import os
# this is for windows searching all the directories with os.walk
def find_files(filename, search_path=["C:","D:","E:"]):
   result = []
   for i in search_path:
       for root, dir, files in os.walk(i):
          if filename in files:
             # this is to append the absolute path of the file
             result.append(os.path.abspath(os.path.join(root, filename)))
             break
       if len(result)!=0:
          break
   return result
# searching my own .txt  file
print(find_files("xxx.txt"))

Output :
['C:\\Users\\TONY STARK\\Desktop\\ProgrammingAssignment2\\xxx.txt']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So i wanted to make a program it grabs images from a certain path but it doesn twork on any other device than mine i dont wanna change the paths everytime so is there anyway to make

teti= open('C:/Users/hyper/OneDrive/Desktop/Database/Gpus/Nvidia/Nvidia-2080ti.txt', 'r')

global accross all windows platforms

Body:
You don't need to make it global you better search for the file you needed. You can just add this function and give your file name only (if you use windows) else you should give all the directories in a list in order to find the path

import os
# this is for windows searching all the directories with os.walk
def find_files(filename, search_path=["C:","D:","E:"]):
   result = []
   for i in search_path:
       for root, dir, files in os.walk(i):
          if filename in files:
             # this is to append the absolute path of the file
             result.append(os.path.abspath(os.path.join(root, filename)))
             break
       if len(result)!=0:
          break
   return result
# searching my own .txt  file
print(find_files("xxx.txt"))

Output :
['C:\\Users\\TONY STARK\\Desktop\\ProgrammingAssignment2\\xxx.txt']


问:
How can I solve "Interpolation inside attributes has been removed. Use v-bind or the colon shorthand"? Vue.js 2
My Vue.js component is like this:

    <template>

                ...

                        Show

                ...

    </template>

```

When executed, there exists an error like this:

Vue template syntax error:

id="purchase-{{ item.id }}": Interpolation inside attributes has
been removed. Use v-bind or the colon shorthand instead.

How can I solve it?

答:
The most elegant solution is save images outside Webpack. By default, Webpack compress images in Base64, so if you save images in your assets folder, that doesn't work because Webpack will compress images in base64, and that isn’t a reactive variable.

To solve your problem, you need to save your images in your public path. Usually the public path is in "public" folder or "statics".

Finally, you can do this:

```<code>data(){
  return {
    image: 1,
    publicPath: process.env.BASE_URL
  }
}
</code>```

And your HTML you can do this:

```<code><img :src="publicPath+'../statics/img/p'+image+'.png'" alt="HANGOUT PHOTO">
</code>```

When to use the public folder

You need a file with a specific name in the build output

File depends on a reactive variable that can change in execution time

You have images and need to dynamically reference their paths

Some library may be incompatible with Webpack and you have no other option but to include it as a

Body:
My Vue.js component is like this:

    <template>

                ...

                        Show

                ...

    </template>

When executed, there exists an error like this:

Vue template syntax error:

id="purchase-{{ item.id }}": Interpolation inside attributes has
been removed. Use v-bind or the colon shorthand instead.

How can I solve it?

Body:
The most elegant solution is save images outside Webpack. By default, Webpack compress images in Base64, so if you save images in your assets folder, that doesn't work because Webpack will compress images in base64, and that isn’t a reactive variable.

To solve your problem, you need to save your images in your public path. Usually the public path is in "public" folder or "statics".

Finally, you can do this:

data(){
  return {
    image: 1,
    publicPath: process.env.BASE_URL
  }
}

And your HTML you can do this:

<img :src="publicPath+'../statics/img/p'+image+'.png'" alt="HANGOUT PHOTO">

When to use the public folder

You need a file with a specific name in the build output

File depends on a reactive variable that can change in execution time

You have images and need to dynamically reference their paths

Some library may be incompatible with Webpack and you have no other option but to include it as a <script> tag.

More information: "HTML and Static Assets" in Vue.js documentation


问:
How to programmatically create ssh tunnel in C/C++ cross-platform?
I need to connect via TCP to a port that's behind a firewall, accessible through an SSH tunnel.  I can achieve connection by opening a tunnel and hittting that port, but I want to build this tunneling in to my application.

Additionally, I want to be able to provide automatic login by use of having authorized keys on the server

This must work on the following platforms (in order of importance)

iOS (trickiest because I can't fork an ssh tunnel like I can on other platforms)

OS X

Linux

Windows

What's the easy way to do this?  I don't want to spend a great deal of effort obviously since this isn't the meat of my application.  But I'll reuse it so I may care enough to "do things right"

答: There is a commercial LIB if you want to have a look at, www.chilkatsoft.com/, it is a genric C++ lib for all languages, in it there is a support for SSH tunneling for IOS.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Making two branches identical
I have two branches - A and B. B was created from A.

Work on both branches continued in parallel. Work on branch A was bad (resulting in a non-working version) while work on branch B was good. During this time branch B was sometimes merged into branch A (but not the other way around).

Now I want to make branch A identical to branch B. I can't use git revert because I need to revert too many commits - I only want to revert the commits that were done on branch A but not as a result of merging branch B.

The solution I found was to clone branch B into a another folder, delete all the files from the working folder of branch A, copy the files from the temp branch B folder and add all untracked files.

Is there a git command that does the same thing? Some git revert switch I missed?

答:
```<code> git merge A
</code>```

is the best way to make 2 branches identical if the head is in branch b

Title: Making two branches identical

Body:
 git merge A

is the best way to make 2 branches identical if the head is in branch b


问:
Can I add optional attributes to an element in React?
Currently, in my React app I have this,

```<code><input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />
</code>```

If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,

```<code><input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
</code>```

But I know that's not the right syntax. Isn't there a better way to do this?

答: You should use className to add style classes conditionally.You can use the classnames package as answered to the question</p>

Body:
Currently, in my React app I have this,

<input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />

If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,

<input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />

But I know that's not the right syntax. Isn't there a better way to do this?


问:
selenium wait until colour changes
I need my code to wait until a button has changed colour.

I have used the below code however it sometimes fails because the item is no longer accessible (due to the postback).

To give an overview on what I'm trying to do:

When I click a save button on a website, everything turns grey for an unknown amount of time and then an asp.net postback is used. With selenium I'm trying to wait until a button is no longer grey and the postback has completed. The only way of telling If the postback is finished is if the colour is no longer grey.

Code:

```<code>def element_colour_check (self, locator, expected_color):
    # loop to retry if element is still loading
    for f in range(0,10)
        try:
            element = self.driver.find_element_by_id(locator)
            hex_color = Color.from_string(element.value_of_css_property("background-color")).hex

            #check to see if element is correct colour
            if (hex_color == expected_color) == True:
                return True
            else:
                sleep(1)
                continue

        except Exception as e:
            sleep(1)
            continue
    raise self.insert_error("Element did not change colour")
</code>```

Calling the function:

```<code>element_color_loading_check("save_btn", "#17a2b8")
</code>```

HTML:

```<code><input type="submit" name="save_btn" id=" save_btn " class="btn btn-info col-sm-12" value="Home">
</code>```

Please note, the class name does not change when the buttons are grey

答:
You should use Selenium's Wait which is designed for such a scenario. Their example of a custom expected condition is very close to what you're after. You might even be able to get away with using the presence_of_element_located expected condition with a CSS locator (By.CSS)

You could alter this logic to your own from their example.

```<code>    if self.css_class in element.get_attribute("class"):
        return element
</code>```

Title: selenium wait until colour changes

Body:
I need my code to wait until a button has changed colour.

I have used the below code however it sometimes fails because the item is no longer accessible (due to the postback).

To give an overview on what I'm trying to do:

When I click a save button on a website, everything turns grey for an unknown amount of time and then an asp.net postback is used. With selenium I'm trying to wait until a button is no longer grey and the postback has completed. The only way of telling If the postback is finished is if the colour is no longer grey.

Code:

def element_colour_check (self, locator, expected_color):
    # loop to retry if element is still loading
    for f in range(0,10)
        try:
            element = self.driver.find_element_by_id(locator)
            hex_color = Color.from_string(element.value_of_css_property("background-color")).hex

            #check to see if element is correct colour
            if (hex_color == expected_color) == True:
                return True
            else:
                sleep(1)
                continue

        except Exception as e:
            sleep(1)
            continue
    raise self.insert_error("Element did not change colour")

Calling the function:

element_color_loading_check("save_btn", "#17a2b8")

HTML:

<input type="submit" name="save_btn" id=" save_btn " class="btn btn-info col-sm-12" value="Home">

Please note, the class name does not change when the buttons are grey

Body:
You should use Selenium's Wait which is designed for such a scenario. Their example of a custom expected condition is very close to what you're after. You might even be able to get away with using the presence_of_element_located expected condition with a CSS locator (By.CSS)

You could alter this logic to your own from their example.

    if self.css_class in element.get_attribute("class"):
        return element


问:
How to replace parameter of a json file by a shell script?
Let's say 123.json with below content:

```<code>{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "76"
  }
}
</code>```

If I want to use a shell script to change the parameter of X_serial by the original number +1 which is 77 in this example.
I have tried the below script to take out the parameter of X_serial:

```<code>grep "X_serial" 123.json | awk {print"$3"}
</code>```

which outputs 76. But then I don't know how to make it into 77 and then put it back to the parameter of X_serial.

答:
With pure Javascript: nodejs and bash :

node <<EOF
var o=$(</tmp/file);
o["LINE"]["X_serial"] = parseInt(o["LINE"]["X_serial"]) + 1;
console.log(o);
EOF

```
<h2> Output</h2>
```{ LINE:
   { A_serial: '1234',
     B_serial: '2345',
     C_serial: '3456',
     X_serial: 78 }
}
```

Body:
Let's say 123.json with below content:

{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "76"
  }
}

If I want to use a shell script to change the parameter of X_serial by the original number +1 which is 77 in this example.
I have tried the below script to take out the parameter of X_serial:

grep "X_serial" 123.json | awk {print"$3"}

which outputs 76. But then I don't know how to make it into 77 and then put it back to the parameter of X_serial.

Body:
With pure Javascript: nodejs and bash :

node <<EOF
var o=$(</tmp/file);
o["LINE"]["X_serial"] = parseInt(o["LINE"]["X_serial"]) + 1;
console.log(o);
EOF

 Output

{ LINE:
   { A_serial: '1234',
     B_serial: '2345',
     C_serial: '3456',
     X_serial: 78 }
}


问:
Generate random number within defined range, using loops
I have a csv, where the first row is the minimum estimated growth rate of a species and the second row is the maximum estimated growth rate.

```<code>   herbivores  youngScrub   sapling  matureTree
0       0.001       0.001     0.045       0.001
1       0.50        0.30      0.990       0.990
</code>```

I am trying to create a new dataframe that randomly generates the growth rate per species 10 times, within the bounds of the min and max defined above. I've been using np.random.uniform as follows but my code isn't working correctly. Here's my attempt so far:

```<code>growthRates_csv = pd.read_csv...

# select the minimum and maximum values in the csv
min_growthRate = growthRates_csv.iloc[0:]
max_growthRate = growthRates_csv.iloc[1:]

# put these into a new dataframe and generate x values in that range
growthRates = pd.DataFrame([np.random.uniform(minG, maxG, size=(10)) for minG,maxG in zip(min_growthRate, max_growthRate)], index=species)

</code>```

The shape of the output is correct (see below), but the values are not. For example, if I have a min and max of 0, the code still generates values above 0.

```<code>   herbivores  youngScrub  matureScrub   sapling  matureTree  grassHerbs
0    0.830269    0.031925     0.781608  0.810162    0.810280    0.144622
1    0.845585    0.648186     0.091188  0.254415    0.156356    0.918178
2    0.615185    0.403556     0.824594  0.878639    0.899520    0.524859
3    0.841222    0.866065     0.926736  0.667068    0.504005    0.405044
4    0.598357    0.617152     0.364813  0.703951    0.188655    0.705077
5    0.110041    0.957693     0.251842  0.568105    0.728227    0.018699
6    0.888947    0.883742     0.580802  0.016060    0.155485    0.484473
7    0.116143    0.947701     0.238723  0.937753    0.415934    0.797138
8    0.733007    0.856673     0.274538  0.669954    0.505984    0.905555
9    0.012286    0.796349     0.539737  0.643185    0.375249    0.628799

</code>```

How can I do this?

Body:
I have a csv, where the first row is the minimum estimated growth rate of a species and the second row is the maximum estimated growth rate.

   herbivores  youngScrub   sapling  matureTree
0       0.001       0.001     0.045       0.001
1       0.50        0.30      0.990       0.990

I am trying to create a new dataframe that randomly generates the growth rate per species 10 times, within the bounds of the min and max defined above. I've been using np.random.uniform as follows but my code isn't working correctly. Here's my attempt so far:

growthRates_csv = pd.read_csv...

# select the minimum and maximum values in the csv
min_growthRate = growthRates_csv.iloc[0:]
max_growthRate = growthRates_csv.iloc[1:]

# put these into a new dataframe and generate x values in that range
growthRates = pd.DataFrame([np.random.uniform(minG, maxG, size=(10)) for minG,maxG in zip(min_growthRate, max_growthRate)], index=species)

The shape of the output is correct (see below), but the values are not. For example, if I have a min and max of 0, the code still generates values above 0.

   herbivores  youngScrub  matureScrub   sapling  matureTree  grassHerbs
0    0.830269    0.031925     0.781608  0.810162    0.810280    0.144622
1    0.845585    0.648186     0.091188  0.254415    0.156356    0.918178
2    0.615185    0.403556     0.824594  0.878639    0.899520    0.524859
3    0.841222    0.866065     0.926736  0.667068    0.504005    0.405044
4    0.598357    0.617152     0.364813  0.703951    0.188655    0.705077
5    0.110041    0.957693     0.251842  0.568105    0.728227    0.018699
6    0.888947    0.883742     0.580802  0.016060    0.155485    0.484473
7    0.116143    0.947701     0.238723  0.937753    0.415934    0.797138
8    0.733007    0.856673     0.274538  0.669954    0.505984    0.905555
9    0.012286    0.796349     0.539737  0.643185    0.375249    0.628799

How can I do this?

Body:
JI would generate the random data in 0,1 with either np.random.uniform or np.random.rand. Then scale them according to the min and max:

num_samples = 10
s = pd.DataFrame(np.random.rand(num_samples,df.shape[1]),  # rand is shorthand for uniform
                 columns=df.columns)

# max-min
ranges = df.iloc[1] - df.iloc[0]

# rescale:
s = (s + df.iloc[0]) * ranges

Output:

   herbivores  youngScrub   sapling  matureTree
0    0.418684    0.034717  0.913757    0.275574
1    0.236334    0.283547  0.676601    0.117145
2    0.201578    0.120658  0.706759    0.476228
3    0.296190    0.286075  0.970215    0.220551
4    0.149709    0.178456  0.255563    0.532362
5    0.384640    0.100779  0.717650    0.785947
6    0.321665    0.168369  0.532486    0.606925
7    0.068008    0.241038  0.378835    0.683488
8    0.387329    0.109531  0.595569    0.113893
9    0.451120    0.285593  0.918895    0.415743


问:
Add files to a ZIP archive?
What component or method can be used to specify a list of filenames and then zip them into a single archive?

I dont need advanced features or anything really, but if I could add some filenames to a stringlist for example then put those files into a ZIP that would be good.

Ive tried searching a few components but not sure which ones to use.

Thanks

答:
I have used sometimes ZipMaster, and it works well.

Regards.

Title: Add files to a ZIP archive?


问:
Log format not recognised - PhpStorm - Ideolog
I am using MAMP + PhpStorm + Wordpress. Ideolog says my log format is not recognized. Help me configure it, please.

My log format :

[06-Feb-2020 15:42:09 UTC] PHP Warning:  mysqli_real_connect(): (HY000/2002): No such file or directory in /Volumes/Workspace/Mamp/wordpress/wp-includes/wp-db.php on line 1633
[06-Feb-2020 15:42:09 UTC] PHP Stack trace:
[06-Feb-2020 15:42:09 UTC] PHP   1. {main}() /Volumes/Workspace/Mamp/wordpress/wp-admin/admin-ajax.php:0
[06-Feb-2020 15:42:09 UTC] PHP   2. require_once() /Volumes/Workspace/Mamp/wordpress/wp-admin/admin-ajax.php:22
[06-Feb-2020 15:42:09 UTC] PHP   3. require_once() /Volumes/Workspace/Mamp/wordpress/wp-load.php:37
[06-Feb-2020 15:42:09 UTC] PHP   4. require_once() /Volumes/Workspace/Mamp/wordpress/wp-config.php:92
[06-Feb-2020 15:42:09 UTC] PHP   5. require_wp_db() /Volumes/Workspace/Mamp/wordpress/wp-settings.php:116
[06-Feb-2020 15:42:09 UTC] PHP   6. wpdb->__construct() /Volumes/Workspace/Mamp/wordpress/wp-includes/load.php:425
[06-Feb-2020 15:42:09 UTC] PHP   7. wpdb->db_connect() /Volumes/Workspace/Mamp/wordpress/wp-includes/wp-db.php:632
[06-Feb-2020 15:42:09 UTC] PHP   8. mysqli_real_connect() /Volumes/Workspace/Mamp/wordpress/wp-includes/wp-db.php:1633
[06-Feb-2020 16:37:19 UTC] PHP Warning:  An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums. (WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.) in /Volumes/Workspace/Mamp/wordpress/wp-includes/update.php on line 388
[06-Feb-2020 16:37:19 UTC] PHP Stack trace:
[06-Feb-2020 16:37:19 UTC] PHP   1. {main}() /Volumes/Workspace/Mamp/wordpress/wp-admin/plugins.php:0
[06-Feb-2020 16:37:19 UTC] PHP   2. require_once() /Volumes/Workspace/Mamp/wordpress/wp-admin/plugins.php:10
[06-Feb-2020 16:37:19 UTC] PHP   3. do_action() /Volumes/Workspace/Mamp/wordpress/wp-admin/admin.php:367
[06-Feb-2020 16:37:19 UTC] PHP   4. WP_Hook->do_action() /Volumes/Workspace/Mamp/wordpress/wp-includes/plugin.php:478
[06-Feb-2020 16:37:19 UTC] PHP   5. WP_Hook->apply_filters() /Volumes/Workspace/Mamp/wordpress/wp-includes/class-wp-hook.php:312
[06-Feb-2020 16:37:19 UTC] PHP   6. wp_update_plugins() /Volumes/Workspace/Mamp/wordpress/wp-includes/class-wp-hook.php:288
[06-Feb-2020 16:37:19 UTC] PHP   7. trigger_error() /Volumes/Workspace/Mamp/wordpress/wp-includes/update.php:388

```

Ideolog settings. I think I need to enter some regular expressions.

答:
Here is what I have. It's not perfect, but it works.

Log Format:

Message pattern: ^\[([^]]+)\s*America/Denver\]\s+([\w\s]+)[.:]\s+(.+)$ (Change "America/Denver" to your timezone, or replace with a more generic regex)

Message start pattern: ^\[

Time format: dd-MMM-yyyy HH:mm:ss

Time capture group: 1

Severity capture group: 2

Category capture group: 0

Apply message pattern to all message lines: unchecked

Patterns: (You can use your own highlighting scheme)

^\s*(?:PHP\s*)?e(rror)?\s*$

^\s*(?:PHP\s*)?w(arn(ing)?)?\s*$

^\s*(?:PHP\s*)?i(nfo)?\s*$

^\s*(?:PHP\s*)?n(otice)?\s*$

^\s*(?:PHP\s*)?f(?:atal(?:\s*error)?)?\s*$

It still doesn't collapse the stack traces, and Ideolog seems to make the file read only within PhpStorm, so deleting log contents is cumbersome.

Body:
I am using MAMP + PhpStorm + Wordpress. Ideolog says my log format is not recognized. Help me configure it, please.

My log format :

[06-Feb-2020 15:42:09 UTC] PHP Warning:  mysqli_real_connect(): (HY000/2002): No such file or directory in /Volumes/Workspace/Mamp/wordpress/wp-includes/wp-db.php on line 1633
[06-Feb-2020 15:42:09 UTC] PHP Stack trace:
[06-Feb-2020 15:42:09 UTC] PHP   1. {main}() /Volumes/Workspace/Mamp/wordpress/wp-admin/admin-ajax.php:0
[06-Feb-2020 15:42:09 UTC] PHP   2. require_once() /Volumes/Workspace/Mamp/wordpress/wp-admin/admin-ajax.php:22
[06-Feb-2020 15:42:09 UTC] PHP   3. require_once() /Volumes/Workspace/Mamp/wordpress/wp-load.php:37
[06-Feb-2020 15:42:09 UTC] PHP   4. require_once() /Volumes/Workspace/Mamp/wordpress/wp-config.php:92
[06-Feb-2020 15:42:09 UTC] PHP   5. require_wp_db() /Volumes/Workspace/Mamp/wordpress/wp-settings.php:116
[06-Feb-2020 15:42:09 UTC] PHP   6. wpdb->__construct() /Volumes/Workspace/Mamp/wordpress/wp-includes/load.php:425
[06-Feb-2020 15:42:09 UTC] PHP   7. wpdb->db_connect() /Volumes/Workspace/Mamp/wordpress/wp-includes/wp-db.php:632
[06-Feb-2020 15:42:09 UTC] PHP   8. mysqli_real_connect() /Volumes/Workspace/Mamp/wordpress/wp-includes/wp-db.php:1633
[06-Feb-2020 16:37:19 UTC] PHP Warning:  An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums. (WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.) in /Volumes/Workspace/Mamp/wordpress/wp-includes/update.php on line 388
[06-Feb-2020 16:37:19 UTC] PHP Stack trace:
[06-Feb-2020 16:37:19 UTC] PHP   1. {main}() /Volumes/Workspace/Mamp/wordpress/wp-admin/plugins.php:0
[06-Feb-2020 16:37:19 UTC] PHP   2. require_once() /Volumes/Workspace/Mamp/wordpress/wp-admin/plugins.php:10
[06-Feb-2020 16:37:19 UTC] PHP   3. do_action() /Volumes/Workspace/Mamp/wordpress/wp-admin/admin.php:367
[06-Feb-2020 16:37:19 UTC] PHP   4. WP_Hook->do_action() /Volumes/Workspace/Mamp/wordpress/wp-includes/plugin.php:478
[06-Feb-2020 16:37:19 UTC] PHP   5. WP_Hook->apply_filters() /Volumes/Workspace/Mamp/wordpress/wp-includes/class-wp-hook.php:312
[06-Feb-2020 16:37:19 UTC] PHP   6. wp_update_plugins() /Volumes/Workspace/Mamp/wordpress/wp-includes/class-wp-hook.php:288
[06-Feb-2020 16:37:19 UTC] PHP   7. trigger_error() /Volumes/Workspace/Mamp/wordpress/wp-includes/update.php:388

Ideolog settings. I think I need to enter some regular expressions.


问:
Error while updating a table with sequence
I have table Hash_emp and a sequence as below

Sequence:

```<code>CREATE SEQUENCE Increment_bY_1
START WITH 1
INCREMENT BY 1
NOMAXVALUE NOCYCLE
CACHE 10;
</code>```

When I am updating the Employee_id with the For loop, it is throwing an error. Can someone explain what went wrong?

```<code>declare
i number;
begin
for i in 2..29
update hash_emp set EMPLOYEE_ID=INCREMENT_BY_1.nextval where rownum=i;
end loop;
end;
</code>```

Error

PLS-00103: Encountered the symbol "UPDATE" when expecting one of the following:

& - + / at loop mod remainder rem  ||

  multiset

  The symbol "loop" was substituted for "UPDATE" to continue.

00000 -  "line %s, column %s:\n%s"

  *Cause:    Usually a PL/SQL compilation error. --------------

答:
Also note that the use of ROWNUM is not necessary. ROWNUM is a pseudo column populated by Oracle only at runtime of a query or command. It only has meaning in the context of that command with its particular predicate and sort, and doesn't have anything to do with the order of data stored on disk or in the table. By specifying ROWNUM without other conditions, you're actually telling Oracle to update whatever random rows happen to get returned in positions 2 through 29 of the result set.

If you want to leave the row with an EMPLOYEE_ID value already assigned alone and only update those that are null, use this:

```<code>update hash_emp set EMPLOYEE_ID=INCREMENT_BY_1.nextval where EMPLOYEE_ID IS NULL;
</code>```

Body:
I have table Hash_emp and a sequence as below

Sequence:

CREATE SEQUENCE Increment_bY_1
START WITH 1
INCREMENT BY 1
NOMAXVALUE NOCYCLE
CACHE 10;

When I am updating the Employee_id with the For loop, it is throwing an error. Can someone explain what went wrong?

declare
i number;
begin
for i in 2..29
update hash_emp set EMPLOYEE_ID=INCREMENT_BY_1.nextval where rownum=i;
end loop;
end;

Error

PLS-00103: Encountered the symbol "UPDATE" when expecting one of the following:

& - + / at loop mod remainder rem  ||

  multiset

  The symbol "loop" was substituted for "UPDATE" to continue.

00000 -  "line %s, column %s:\n%s"

  *Cause:    Usually a PL/SQL compilation error. --------------

Body:
Also note that the use of ROWNUM is not necessary. ROWNUM is a pseudo column populated by Oracle only at runtime of a query or command. It only has meaning in the context of that command with its particular predicate and sort, and doesn't have anything to do with the order of data stored on disk or in the table. By specifying ROWNUM without other conditions, you're actually telling Oracle to update whatever random rows happen to get returned in positions 2 through 29 of the result set.

If you want to leave the row with an EMPLOYEE_ID value already assigned alone and only update those that are null, use this:

update hash_emp set EMPLOYEE_ID=INCREMENT_BY_1.nextval where EMPLOYEE_ID IS NULL;


问:
how to generate a Http Request for AAD?
so, I get the Access Token and I want to create a request...

HttpClient httpClient = new HttpClient();
                        httpClient.DefaultRequestHeaders.Authorization = new
                        AuthenticationHeaderValue("Bearer", accesToken);

HttpResponseMessage response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/users");

Also, the Problem may be on setting the scopes for the authentication...i set it to:

```<code>string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
</code>```

But I don't know if it gets all application permissions that I have (it is a deamon).

答:
You can use this sample which will help you to create events with same client credential flow which you are using but you need to change some things here.

You need to first give the Calendar.ReadWrite permission in the Azure portal for your app.

You need to add the below code in the Program.cs

```<code>if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebAPIToPostEvent($"{config.ApiUrl}v1.0/users/{user obj id}/calendars/{calendar id}/events", result.AccessToken, Display);
            }
</code>```

Then you need to add the below classes in the protectedApiCallHelper.cs

```<code>public class Event
{
    [JsonProperty("subject")]
    public string Subject { get; set; }
    [JsonProperty("body")]
    public Body Body;
    [JsonProperty("start")]
    public TimeAndDate Start;
    [JsonProperty("end")]
    public TimeAndDate End;
    [JsonProperty("location")]
    public Location Location;
    [JsonProperty("attendees")]
    public List<Attendees> Attendees;

}
public class Body
{
    [JsonProperty("contentType")]
    public string ContentType { get; set; }
    [JsonProperty("content")]
    public string Content { get; set; }
}
public class TimeAndDate
{
    [JsonProperty("dateTime")]
    public string DateTime { get; set; }
    [JsonProperty("timeZone")]
    public string TimeZone { get; set; }
}
public class Location
{
    [JsonProperty("displayName")]
    public string DisplayName { get; set; }
}
public class Attendees
{
    [JsonProperty("emailAddress")]
    public EmailAddress EmailAddress;
    [JsonProperty("type")]
    public string Type;
}
public class EmailAddress
{
    [JsonProperty("address")]
    public string Address { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
}
</code>```

In this same ProtectedApiCallHelper class you can create a post request and get the details by adding the below code

```<code>public async Task CallWebAPIToPostEvent(string webApiUrl, string accessToken, Action<JObject> processResult)
        {
            var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
            if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
            {
                HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }
            defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            var payload = new Event
            {
                Subject = "Let's go for lunch",
                Body = new Body
                {
                    ContentType = "HTML",
                    Content = "Does mid month work for you?"
                },
                Start = new TimeAndDate
                {
                    DateTime = "2019-03-15T12:00:00",
                    TimeZone = "Pacific Standard Time"
                },
                End = new TimeAndDate
                {
                    DateTime = "2019-03-15T14:00:00",
                    TimeZone = "Pacific Standard Time"
                },
                Location = new Location
                {
                    DisplayName = "Harry's Bar"
                },
                Attendees = new List<Attendees>
                {
                        new Attendees
                        {
                            EmailAddress = new EmailAddress
                            {
                                Address = "Shiva@nishantsingh.live",
                                Name = "Shiva"
                            },
                            Type = "required"
                        }
                }
            };
            // Serialize our concrete class into a JSON String
            var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, httpContent);

            if (response.Content != null)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
        }
</code>```

This will help you create the event with these details.

Title: how to generate a Http Request for AAD?

Body:
so, I get the Access Token and I want to create a request...

HttpClient httpClient = new HttpClient();
                        httpClient.DefaultRequestHeaders.Authorization = new
                        AuthenticationHeaderValue("Bearer", accesToken);

HttpResponseMessage response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/users");

Also, the Problem may be on setting the scopes for the authentication...i set it to:

string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

But I don't know if it gets all application permissions that I have (it is a deamon).

Body:
You can use this sample which will help you to create events with same client credential flow which you are using but you need to change some things here.

You need to first give the Calendar.ReadWrite permission in the Azure portal for your app.

You need to add the below code in the Program.cs

if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebAPIToPostEvent($"{config.ApiUrl}v1.0/users/{user obj id}/calendars/{calendar id}/events", result.AccessToken, Display);
            }

Then you need to add the below classes in the protectedApiCallHelper.cs

public class Event
{
    [JsonProperty("subject")]
    public string Subject { get; set; }
    [JsonProperty("body")]
    public Body Body;
    [JsonProperty("start")]
    public TimeAndDate Start;
    [JsonProperty("end")]
    public TimeAndDate End;
    [JsonProperty("location")]
    public Location Location;
    [JsonProperty("attendees")]
    public List<Attendees> Attendees;

}
public class Body
{
    [JsonProperty("contentType")]
    public string ContentType { get; set; }
    [JsonProperty("content")]
    public string Content { get; set; }
}
public class TimeAndDate
{
    [JsonProperty("dateTime")]
    public string DateTime { get; set; }
    [JsonProperty("timeZone")]
    public string TimeZone { get; set; }
}
public class Location
{
    [JsonProperty("displayName")]
    public string DisplayName { get; set; }
}
public class Attendees
{
    [JsonProperty("emailAddress")]
    public EmailAddress EmailAddress;
    [JsonProperty("type")]
    public string Type;
}
public class EmailAddress
{
    [JsonProperty("address")]
    public string Address { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
}

In this same ProtectedApiCallHelper class you can create a post request and get the details by adding the below code

public async Task CallWebAPIToPostEvent(string webApiUrl, string accessToken, Action<JObject> processResult)
        {
            var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
            if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
            {
                HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }
            defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            var payload = new Event
            {
                Subject = "Let's go for lunch",
                Body = new Body
                {
                    ContentType = "HTML",
                    Content = "Does mid month work for you?"
                },
                Start = new TimeAndDate
                {
                    DateTime = "2019-03-15T12:00:00",
                    TimeZone = "Pacific Standard Time"
                },
                End = new TimeAndDate
                {
                    DateTime = "2019-03-15T14:00:00",
                    TimeZone = "Pacific Standard Time"
                },
                Location = new Location
                {
                    DisplayName = "Harry's Bar"
                },
                Attendees = new List<Attendees>
                {
                        new Attendees
                        {
                            EmailAddress = new EmailAddress
                            {
                                Address = "Shiva@nishantsingh.live",
                                Name = "Shiva"
                            },
                            Type = "required"
                        }
                }
            };
            // Serialize our concrete class into a JSON String
            var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, httpContent);

            if (response.Content != null)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
        }

This will help you create the event with these details.


问:
Does clFlush (as opposed to clFinish) actually do anything?
The OpenCL clFinish() API call blocks until all commands on a command queue have completed execution. A related function, clFlush(), supposedly

Issues all previously queued OpenCL commands in a command-queue to the device associated with the command-queue.

What does that mean? Does it make these commands skip waiting on events? That doesn't sound reasonable. Does it block until the commands have been issued? Probably not, that's what clFinish() does. It almost seems as though clFlush() doens't actually have to do anything.

What am I missing?

答:
When you enqueue asynchronous commands using opencl there is no real guarantee that the GPU will actually execute those commands.

These asynchronous commands are usually memory transfers (clEnqueueWriteBuffer, clEnqueueReadBuffer) with the blocking flag set to CL_FALSE and kernel invocations (clEnqueueNDRangeKernel).

If you wish to guarantee the commands will execute, you have to either enqueue a blocking command such as an API call with the blocking flag set to CL_TRUE or call clFinish / clFlush.

clFlush basically transfers the recorded commands to the GPU. The commands are 'flushed' to the hardware command buffer, and gets executed once GPU scheduler schedules them for execution.

An important corner case is when the recorded command (or previously recorded command on the same queue) has to synchronize with a user event (clCreateUserEvent) or an event originating from command recorded to a different queue.
These events are supplied via the OpenCL API and can stall flushed commands until the event is triggered.

Why clFlush is necessary?

The logic behind this, is that it is most efficient to saturate the GPU with the max amount of work (fill up a large command buffer via many enqueue calls) and then tell the GPU to execute everything using a single asynchronous call to clFlush or its blocking variant clFinish.

One reason you might want to call clFlush over clFinish is if you wish to interleave CPU work with GPU work:

```<code>clEnqueue*** // async
clEnqueue*** // async
clEnqueue*** // async
clFlush(...); // async, make sure commands will execute
// do some heavy CPU work while GPU is executing commands
clFinish(...); // synchronous, ensure all commands are done, collect results.
</code>```

Some OpenCL implementations (AMD for instance) will batch commands recorded in between clFlush calls. Meaning it will treat the recorded commands as a single command from the point of view of event synchronization.

```<code>event1 = clEnqueue*** // async
event2 = clEnqueue*** // async
event3 = clEnqueue*** // async
clFlush(...); // async, previously recorded commands will execute
event4 = clEnqueue*** // async
event5 = clEnqueue*** // async
event6 = clEnqueue*** // async
clFlush(...); // async, previously recorded commands will execute
event3.wait();
// Do CPU work while the GPU processes kernels 4-6
event6.wait(); // wait for kernels 4-6
</code>```

In this case, events 1-3 will be signaled after the 3rd kernel finish execution, while events 4-6 will be signaled after the 6th kernel finish execution.

This allows you to post process results on the CPU side, while the GPU is still working.

Another use case for clFlush is to reduce latency emanating from driver work and GPU scheduling. If your enqueued commands must wait for an external event (barrier), you could flush them beforehand to the GPU. Once the event is triggered, the commands are already flushed to the hardware side waiting for actual execution. Thus saving the driver latency involved in transferring the recorded commands to the GPU.

Body:
When you enqueue asynchronous commands using opencl there is no real guarantee that the GPU will actually execute those commands.

These asynchronous commands are usually memory transfers (clEnqueueWriteBuffer, clEnqueueReadBuffer) with the blocking flag set to CL_FALSE and kernel invocations (clEnqueueNDRangeKernel).

If you wish to guarantee the commands will execute, you have to either enqueue a blocking command such as an API call with the blocking flag set to CL_TRUE or call clFinish / clFlush.

clFlush basically transfers the recorded commands to the GPU. The commands are 'flushed' to the hardware command buffer, and gets executed once GPU scheduler schedules them for execution.

An important corner case is when the recorded command (or previously recorded command on the same queue) has to synchronize with a user event (clCreateUserEvent) or an event originating from command recorded to a different queue.
These events are supplied via the OpenCL API and can stall flushed commands until the event is triggered.

Why clFlush is necessary?

The logic behind this, is that it is most efficient to saturate the GPU with the max amount of work (fill up a large command buffer via many enqueue calls) and then tell the GPU to execute everything using a single asynchronous call to clFlush or its blocking variant clFinish.

One reason you might want to call clFlush over clFinish is if you wish to interleave CPU work with GPU work:

clEnqueue*** // async
clEnqueue*** // async
clEnqueue*** // async
clFlush(...); // async, make sure commands will execute
// do some heavy CPU work while GPU is executing commands
clFinish(...); // synchronous, ensure all commands are done, collect results.

Some OpenCL implementations (AMD for instance) will batch commands recorded in between clFlush calls. Meaning it will treat the recorded commands as a single command from the point of view of event synchronization.

event1 = clEnqueue*** // async
event2 = clEnqueue*** // async
event3 = clEnqueue*** // async
clFlush(...); // async, previously recorded commands will execute
event4 = clEnqueue*** // async
event5 = clEnqueue*** // async
event6 = clEnqueue*** // async
clFlush(...); // async, previously recorded commands will execute
event3.wait();
// Do CPU work while the GPU processes kernels 4-6
event6.wait(); // wait for kernels 4-6

In this case, events 1-3 will be signaled after the 3rd kernel finish execution, while events 4-6 will be signaled after the 6th kernel finish execution.

This allows you to post process results on the CPU side, while the GPU is still working.

Another use case for clFlush is to reduce latency emanating from driver work and GPU scheduling. If your enqueued commands must wait for an external event (barrier), you could flush them beforehand to the GPU. Once the event is triggered, the commands are already flushed to the hardware side waiting for actual execution. Thus saving the driver latency involved in transferring the recorded commands to the GPU.


问:
Should I handle exception with Closable.use{...} in Kotlin?
According to the source of Closable.use, if an error occurs, an exception will be thrown.

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        when {
            apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
            this == null -> {}
            exception == null -> close()
            else ->
                try {
                    close()
                } catch (closeException: Throwable) {
                    // cause.addSuppressed(closeException) // ignored here
                }
        }
    }
```

<p>In most examples of <code>Closable.use</code>, try-catch is not used as shown below.
Why isn't error handling needed? Is it safe?</p>

<pre class="lang-kotlin prettyprint-override"><code>    BufferedReader(FileReader("test.file")).use { return it.readLine() }
</code>```

答:
We see from Kotlin documentation what is the purpose of the use function:

Executes the given block function on this resource and then closes it
  down correctly whether an exception is thrown or not.

This function closes the resource properly if the block function completed successfully or threw an exception. It is your responsibility to handle the result of the block function.

If an exception was thrown and there is a way to handle it and proceed with code execution, use a try/catch. If there is nothing to do about it and control should be passed to the caller, it is not necessary to use a try/catch.

Body:
According to the source of Closable.use, if an error occurs, an exception will be thrown.

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        when {
            apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
            this == null -> {}
            exception == null -> close()
            else ->
                try {
                    close()
                } catch (closeException: Throwable) {
                    // cause.addSuppressed(closeException) // ignored here
                }
        }
    }

In most examples of Closable.use, try-catch is not used as shown below.
Why isn't error handling needed? Is it safe?

    BufferedReader(FileReader("test.file")).use { return it.readLine() }


问:
Spring Path Variable that accepts email with special character
I have spring boot rest application (spring boot 2.1.8.RELEASE).

It has an API that accepts an email address and it works well on most emails like:

```<code>sampleemail@mailtest.com
sample-email@mailtest.com
sample.email@mailtest.com
sample_email@mailtest.com
</code>```

but it does not work with sample+email@mailtest.com

Below is my API method:

```<code>@PostMapping("/public/sendEmail/{email:.+}")
public void sendEmail(@ApiParam(value = "Account email", required = true) @PathVariable String email) {
    doSomethingToThis(email);
}
</code>```

Same issue if I use /public/sendEmail/{email} instead of /public/sendEmail/{email:.+}.

What should I change so that it will accept email with + character like sample+email@mailtest.com?

TIA

答:
You can try to add one '/' in the end of the @Postmapping, so it will consider it as a whole string.

From:

```<code>@PostMapping("/public/sendEmail/{email:.+}")
</code>```

To:

```<code>@PostMapping("/public/sendEmail/{email}/")
</code>```

The complete one is like below

```<code>@PostMapping("/public/sendEmail/{email}/")
public void sendEmail(@ApiParam(value = "Account email", required = true) @PathVariable String email) {
    doSomethingToThis(email);
}
</code>```

Body:
I have spring boot rest application (spring boot 2.1.8.RELEASE).

It has an API that accepts an email address and it works well on most emails like:

sampleemail@mailtest.com
sample-email@mailtest.com
sample.email@mailtest.com
sample_email@mailtest.com

but it does not work with sample+email@mailtest.com

Below is my API method:

@PostMapping("/public/sendEmail/{email:.+}")
public void sendEmail(@ApiParam(value = "Account email", required = true) @PathVariable String email) {
    doSomethingToThis(email);
}

Same issue if I use /public/sendEmail/{email} instead of /public/sendEmail/{email:.+}.

What should I change so that it will accept email with + character like sample+email@mailtest.com?

TIA

Body:
You can try to add one '/' in the end of the @Postmapping, so it will consider it as a whole string.

From:

@PostMapping("/public/sendEmail/{email:.+}")

To:

@PostMapping("/public/sendEmail/{email}/")

The complete one is like below

@PostMapping("/public/sendEmail/{email}/")
public void sendEmail(@ApiParam(value = "Account email", required = true) @PathVariable String email) {
    doSomethingToThis(email);
}


问:
Add a blog to an existing webpage
How can I insert a blog (not created yet) into an already existing 'static' webpage? The webpage is written mostly in PHP. I'm considering using something like WordPress.org (host install version) and using it to update the website's news page.

From what I've read, its sounds like I would need to do a lot of theme tweaking to get WordPress to display correctly with our website's template. This sounds a bit daunting to me.

答: I used SnewsCMS for that, it is trivial to integrate news section in static php pages. </p>

OwnerDisplayName: djbender

Title: Add a blog to an existing webpage

LastEditorDisplayName: tinkertim

OwnerDisplayName: esmajic


问:
Form Based Arrays
I'm trying to access each value in a array without serializing it.
I than want this data stored into a datetime field in MySQL.
The data is received from my form [collect] => Array ( [0] => 01 [1] => 06 [2] => 2011 [3] => 17 [4] => 41 )

How can i store this array data into my database 'datetime' field column?

```<code>$dd=$_POST('$collect[0]');
$mm=$_POST('$collect[1]');
$yy=$_POST('$collect[2]');
$hh=$_POST('$collect[3]');
$ii=$_POST('$collect[4]');
$ddate = ('$yy','$mm','$dd',NULL,'$hh','$ii',NULL)
</code>```

What i'm trying to do above is take each array value and store it in variable names and than use variable $ddate to store as a datetime in my database. I'm not sure if this is even possible, but i have tried serialize, but date will not insert into database just shows format 0000/00/00 00:00 on database so i'm trying the above to see if this can work.

If there's a universal way I can use instead of the above, please can someone show me a small example which I can work from.

答:
Try this to get the data out of your POST request:</p>

```<code>$collect = $_POST['collect'];
$dd=$collect[0];
$mm=$collect[1];
$yy=$collect[2];
$hh=$collect[3];
$ii=$collect[4];
</code>```

Title: Form Based Arrays

Body:
I'm trying to access each value in a array without serializing it.
I than want this data stored into a datetime field in MySQL.
The data is received from my form [collect] => Array ( [0] => 01 [1] => 06 [2] => 2011 [3] => 17 [4] => 41 )

How can i store this array data into my database 'datetime' field column?

$dd=$_POST('$collect[0]');
$mm=$_POST('$collect[1]');
$yy=$_POST('$collect[2]');
$hh=$_POST('$collect[3]');
$ii=$_POST('$collect[4]');
$ddate = ('$yy','$mm','$dd',NULL,'$hh','$ii',NULL)

What i'm trying to do above is take each array value and store it in variable names and than use variable $ddate to store as a datetime in my database. I'm not sure if this is even possible, but i have tried serialize, but date will not insert into database just shows format 0000/00/00 00:00 on database so i'm trying the above to see if this can work.

If there's a universal way I can use instead of the above, please can someone show me a small example which I can work from.

Body:
Try this to get the data out of your POST request:

$collect = $_POST['collect'];
$dd=$collect[0];
$mm=$collect[1];
$yy=$collect[2];
$hh=$collect[3];
$ii=$collect[4];


问:
Why is my recursive function won't work and why do I get strange results
I need to write a code that will take a string of numbers and find consecutive 5 digits that will give me the highest possible number (as in 9328498503734 the answer will be 9850374).

```<code>x = 0
def solution(digits):
    global x
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        solution(digits[1:])
</code>```

My idea was to do it with recursive function - check if the length of the input is not less than 5, if not, then check if the current 5 digits are the biggest number. If so, this number becomes new x, and function gets repeated but without the first digit until the base case is missed.

So my first problem is how to do this without a global variable? I heard they are shunned but when I was writing previous recursive code and used any variable inside that function it got reset every time.

My next problem is that this function returns None and I have no idea why? Also, when I tried to put "print (len(digit))" over global x for each recursion, I can see what's going on! Instead of returning 'None' it raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" and I have no idea why? Although, without this counter, I have None as a return.

So, how to do it without a global variable and why does my code change it's behavior so much over a simple print statement?

Your help would be appreciated!

EDIT: Ok, I was getting None, because I tried to call function from inside function, but I forgot that it has to be called with "return", not just like that, like I would do it outside a function.

Big thank you to the user below who told me that I can carry ariable in a function by placing this variable in function parenthesis. I would definitely not recommend Codecademy, as it omits such simple and important thing, giving only very basic and incomplete knowledge of the topic. I finished their Python course, all exercises and this is how much I know after this :/

答:
Instead of using a global variable, pass x 'along' when you call the function. By setting it to have a default value of 0 it doesn't need to be passed in at the start:

```<code>def solution(digits, x=0):
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        return solution(digits[1:], x)

print(solution('9328498503734'))
98503
</code>```

Body:
I need to write a code that will take a string of numbers and find consecutive 5 digits that will give me the highest possible number (as in 9328498503734 the answer will be 9850374).

x = 0
def solution(digits):
    global x
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        solution(digits[1:])

My idea was to do it with recursive function - check if the length of the input is not less than 5, if not, then check if the current 5 digits are the biggest number. If so, this number becomes new x, and function gets repeated but without the first digit until the base case is missed.

So my first problem is how to do this without a global variable? I heard they are shunned but when I was writing previous recursive code and used any variable inside that function it got reset every time.

My next problem is that this function returns None and I have no idea why? Also, when I tried to put "print (len(digit))" over global x for each recursion, I can see what's going on! Instead of returning 'None' it raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" and I have no idea why? Although, without this counter, I have None as a return.

So, how to do it without a global variable and why does my code change it's behavior so much over a simple print statement?

Your help would be appreciated!

EDIT: Ok, I was getting None, because I tried to call function from inside function, but I forgot that it has to be called with "return", not just like that, like I would do it outside a function.

Big thank you to the user below who told me that I can carry ariable in a function by placing this variable in function parenthesis. I would definitely not recommend Codecademy, as it omits such simple and important thing, giving only very basic and incomplete knowledge of the topic. I finished their Python course, all exercises and this is how much I know after this :/

Body:
Instead of using a global variable, pass x 'along' when you call the function. By setting it to have a default value of 0 it doesn't need to be passed in at the start:

def solution(digits, x=0):
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        return solution(digits[1:], x)

print(solution('9328498503734'))
98503


问:
Error handling with graphql-java-tools and graphql-spring-boot-starter
How to handle errors in my graphQL API? I am using graphql-java-tools and graphql-spring-boot-starter. I created error handler but every time I get response 200 even when exception was thrown. Could you tell me how I should set error code e.g 400 in response?</p>
```<code>@Component
public class CustomGraphQLErrorHandler implements GraphQLErrorHandler {

    @Override
    public List<GraphQLError> processErrors(List<GraphQLError> list) {
        return list.stream().map(this::getNested).collect(Collectors.toList());
    }

    private GraphQLError getNested(GraphQLError error) {
        if (error instanceof ExceptionWhileDataFetching) {
            ExceptionWhileDataFetching exceptionError = (ExceptionWhileDataFetching) error;
            if (exceptionError.getException() instanceof GraphQLError) {
                return (GraphQLError) exceptionError.getException();
            }
        }
        return error;
    }
}
</code>```

答:
The GraphQL server returns an HTTP 200 when it can accept the request (the syntax is valid, the server is up...).

If an error occurs, it returns an 200 and fills the errors list in the response.

So, on client side, you will have:

Technical server errors, if the HTTP status is different from 200

Errors when handling the request (technical or not) if the HTTP
status is 200 and the errors list is not empty

No error if the HTTP
status is 200 and the errors list is not present (it should not be
present and empty, according to the GraphQL spec)

Body:
How to handle errors in my graphQL API? I am using graphql-java-tools and graphql-spring-boot-starter. I created error handler but every time I get response 200 even when exception was thrown. Could you tell me how I should set error code e.g 400 in response?

@Component
public class CustomGraphQLErrorHandler implements GraphQLErrorHandler {

    @Override
    public List<GraphQLError> processErrors(List<GraphQLError> list) {
        return list.stream().map(this::getNested).collect(Collectors.toList());
    }

    private GraphQLError getNested(GraphQLError error) {
        if (error instanceof ExceptionWhileDataFetching) {
            ExceptionWhileDataFetching exceptionError = (ExceptionWhileDataFetching) error;
            if (exceptionError.getException() instanceof GraphQLError) {
                return (GraphQLError) exceptionError.getException();
            }
        }
        return error;
    }
}


问:
How to determine which heroku buildpack to use when multiple are available?
Obviously selecting the right buildpack is critical in order to make secure, performant, and resilient applications. Heroku seems to work with the dev community to create and share buildpacks. A side effect is that there may not be a single, 'obvious' choice for a given tech stack.

Random example (R)

If we wish to use an R buildpack, a quick google show this popular buildpack is out of date and no longer supported, but we can easily find these three (just examples) here, here, and here

Another random example (cairo)

The cairo buildpack - googling shows numerous in the top results, it's not clear which to use out of, say, the top four on google here, here, here (this one clearly states deprecated, so we can rule that out), and here

Question

What are the main criteria against which we should assess heroku buildpack when faced with >1 that look like they will do the job?

答:
I think the answer here depends on how much you're willing to trust someone else's code.

None of the buildpacks you mentioned are officially supported by Heroku. They are community buildpacks, maintained by the community, and they implement the Heroku Buildpack API.

The Buildpack API is open for anyone to implement. So the most discerning users will write their own buildpacks. Otherwise, you'll have to decide which community you trust the most.


问:
Setup alert in LUIS (Azure Cognitive Service) to track user activity
I want to know there's some way I can set up an email alert on the LUIS port if any users are changing established intent and utterances.

I need this feature because many users are able to access/edit my LUIS app using the company's single-sign-on, so I want to set up an alert on the portal if any user add/edit intent is in the current app, then I will get an email alert.

Please suggest ways that I can do this.

答:
Nicholas is correct. Your users should NOT have access to your app.

There is nothing in the LUIS app on LUIS.ai that will send an email or notification any time the app is changed, because the only people who should have access to it are the developers.

You need to request from your admin to ensure you and any devs on your bot are the only contributers to your LUIS app.

https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-concept-keys


问:
Error creating a BLOB_STORAGE type external data source in Azure SQL Data Warehouse
Here's the T-SQL I try to run:

```<code>CREATE EXTERNAL DATA SOURCE mySource WITH
(TYPE = BLOB_STORAGE, LOCATION = 'https://myContainer.blob.core.windows.net', CREDENTIAL = myCredential)
</code>```

Here's the error I get:

```<code>Msg 105057, Level 16, State 1, Line 6
CREATE EXTERNAL DATA SOURCE statement failed because the value for the 'TYPE' option is invalid. Change the value for the 'TYPE' option and try again.
</code>```

I've Googled for "Msg 105057" and I get nothing. My goal is to use the OPENROWSET function to bulk insert a JSON file from my Azure Storage account into my Azure Data Warehouse.

答:
It does support Blob Storage, but the TYPE needs to be 'HADOOP' and the location needs to use "wasbs" instead of "https":</p>

```<code>CREATE EXTERNAL DATA SOURCE mySource WITH
(TYPE = HADOOP, LOCATION = 'wasbs://myContainer.blob.core.windows.net', CREDENTIAL = myCredential)
</code>```

Body:
Here's the T-SQL I try to run:

CREATE EXTERNAL DATA SOURCE mySource WITH
(TYPE = BLOB_STORAGE, LOCATION = 'https://myContainer.blob.core.windows.net', CREDENTIAL = myCredential)

Here's the error I get:

Msg 105057, Level 16, State 1, Line 6
CREATE EXTERNAL DATA SOURCE statement failed because the value for the 'TYPE' option is invalid. Change the value for the 'TYPE' option and try again.

I've Googled for "Msg 105057" and I get nothing. My goal is to use the OPENROWSET function to bulk insert a JSON file from my Azure Storage account into my Azure Data Warehouse.

Body:
It does support Blob Storage, but the TYPE needs to be 'HADOOP' and the location needs to use "wasbs" instead of "https":

CREATE EXTERNAL DATA SOURCE mySource WITH
(TYPE = HADOOP, LOCATION = 'wasbs://myContainer.blob.core.windows.net', CREDENTIAL = myCredential)


答:
Typically to make a recursive function work, you need to return some kind of combination of a base result with the result of another recursive call on a reduced version of the original argument.  Using globals is usually going to be self-defeating because all the recursive calls will overwrite each other (there's a reason using globals is "shunned", it's because it usually makes your code not work, lol).

```<code>>>> def solution(digits: str) -> str:
...     """Returns the 5-digit substring of digits with the highest int value."""
...     if len(digits) <= 5:
...         return digits
...     else:
...         return max(digits[:5], solution(digits[1:]), key=int)
...
>>> solution("9328498503734")
'98503'
</code>```

Title: Why is my recursive function won't work and why do I get strange results

Body:
Typically to make a recursive function work, you need to return some kind of combination of a base result with the result of another recursive call on a reduced version of the original argument.  Using globals is usually going to be self-defeating because all the recursive calls will overwrite each other (there's a reason using globals is "shunned", it's because it usually makes your code not work, lol).

>>> def solution(digits: str) -> str:
...     """Returns the 5-digit substring of digits with the highest int value."""
...     if len(digits) <= 5:
...         return digits
...     else:
...         return max(digits[:5], solution(digits[1:]), key=int)
...
>>> solution("9328498503734")
'98503'


问:
Creating an JS array from PHP
I'm developing a Google Geochart and I'd like it to be dynamic. This is the static code to make the array to store the two values are as follows. The Country is the unique identifier for the map and the colour value is what the colour of the map will be. (Irrelevant but context)

```<code>  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]
</code>```

I'd like to be able to make this array from a for loop taken from php echo values. Something like this pseudo code;

```<code>for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>],
</code>```

So similar to a php table as it gets all the values, I would like to do the same but for a JavaScript array. Any advice would be kind!

EDIT: The static code is an example, I want to take values from the database, the first value being country and the second value being colour value. BOTH from the database. I suppose in turn making the geochart dynamic

答:
The function you are looking for is json_encode(), but it would be more useful if you first structured your input array.

So something like the following:

```<code>// Some code here to generate $arrayData from $statements, giving the following

$arrayData = [
  ['Country' => 'China', 'Color Value' => 3],
  ['Country' => 'Russia', 'Color Value' => 2.6],
  ['Country' => 'France', 'Color Value' => 2.5],
  ['Country' => 'Spain', 'Color Value' => 2.4],
  ['Country' => 'Portugal', 'Color Value' => 1.1]
];

// Then, once you have generated $arrayData

echo json_encode($arrayData);
</code>```

Title: Creating an JS array from PHP

Body:
I'm developing a Google Geochart and I'd like it to be dynamic. This is the static code to make the array to store the two values are as follows. The Country is the unique identifier for the map and the colour value is what the colour of the map will be. (Irrelevant but context)

  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]

I'd like to be able to make this array from a for loop taken from php echo values. Something like this pseudo code;

for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>],

So similar to a php table as it gets all the values, I would like to do the same but for a JavaScript array. Any advice would be kind!

EDIT: The static code is an example, I want to take values from the database, the first value being country and the second value being colour value. BOTH from the database. I suppose in turn making the geochart dynamic

Body:
The function you are looking for is json_encode(), but it would be more useful if you first structured your input array.

So something like the following:

// Some code here to generate $arrayData from $statements, giving the following

$arrayData = [
  ['Country' => 'China', 'Color Value' => 3],
  ['Country' => 'Russia', 'Color Value' => 2.6],
  ['Country' => 'France', 'Color Value' => 2.5],
  ['Country' => 'Spain', 'Color Value' => 2.4],
  ['Country' => 'Portugal', 'Color Value' => 1.1]
];

// Then, once you have generated $arrayData

echo json_encode($arrayData);


问:
ASP.NET CORE and EPPLUS library on Linux - IndexOutOfRangeException: Worksheet position out of range
Please note that I have found several existing topics with this problem (EPPLUS IndexOutOfRangeException: Worksheet position out of range.), but none that were specific only to Linux publish.

We have an ASP.NET CORE 3.1 web project with EPPlus 5.1.2 library.

For some reports we open a pre-existing Excel template (.xlsx), fill it with some data and return to the user for download. Everything works perfectly when Debugging or when we publish the web app to a Windows Server.

But, if we publish to our Linux server (Debian 10 64 Bit) we get the following error when trying to generate the report:

```<code>An unhandled exception occurred while processing the request.
IndexOutOfRangeException: Worksheet position out of range.

OfficeOpenXml.ExcelWorksheets.get_Item(int PositionID)
</code>```

Otherwise everything else seems to work fine (on Linux).

Report generating code:

MemoryStream result;

FileInfo fileInfo = new FileInfo(Path.Combine(path, "template.xlsx"));
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

using (ExcelPackage xlPackage = new ExcelPackage(fileInfo))
{
    ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[0];

    if (worksheet != null)
    {
        // fill some data ...
    }

    //return
    result = new MemoryStream(xlPackage.GetAsByteArray());
}
```

My first thought is that EPPLUS in not supported when publishing .NET CORE on Linux...? Or is there something we can do differently for it to work?

答:
The problem was not with EPPLUS library, but the handling of file/path name for the Excel template. Windows Server is not case sensitive for file/path name, Linux on the other hand is. </p>

<p>Once the folder name in our c# code was (case) matched with the actual folder name on Linux server, Excel export started working. </p>

Body:
Please note that I have found several existing topics with this problem (EPPLUS IndexOutOfRangeException: Worksheet position out of range.), but none that were specific only to Linux publish.

We have an ASP.NET CORE 3.1 web project with EPPlus 5.1.2 library.

For some reports we open a pre-existing Excel template (.xlsx), fill it with some data and return to the user for download. Everything works perfectly when Debugging or when we publish the web app to a Windows Server.

But, if we publish to our Linux server (Debian 10 64 Bit) we get the following error when trying to generate the report:

An unhandled exception occurred while processing the request.
IndexOutOfRangeException: Worksheet position out of range.

OfficeOpenXml.ExcelWorksheets.get_Item(int PositionID)

Otherwise everything else seems to work fine (on Linux).

Report generating code:

MemoryStream result;

FileInfo fileInfo = new FileInfo(Path.Combine(path, "template.xlsx"));
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

using (ExcelPackage xlPackage = new ExcelPackage(fileInfo))
{
    ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[0];

    if (worksheet != null)
    {
        // fill some data ...
    }

    //return
    result = new MemoryStream(xlPackage.GetAsByteArray());
}

My first thought is that EPPLUS in not supported when publishing .NET CORE on Linux...? Or is there something we can do differently for it to work?

Body:
The problem was not with EPPLUS library, but the handling of file/path name for the Excel template. Windows Server is not case sensitive for file/path name, Linux on the other hand is.

Once the folder name in our c# code was (case) matched with the actual folder name on Linux server, Excel export started working.