问:
Populating and passing complex object from MVC2 view to controller action
I have following code in my MVC2 view:

```<code><tr class="edit" style="display:none">
    <td>
        <%= Html.DropDownList("drpFields", new SelectList(Model.Fields, "FieldID", "NiceName", whiteout.FieldID)) %>
    </td>
    <td>
        <%= Html.DropDownList("drpStartTimeh", new SelectList(Model.Hours, whiteout.StartHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimem", new SelectList(Model.Minutes, whiteout.StartHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimet", new SelectList(Model.AMPM, whiteout.StartHour.Hour > 12 ? "PM" : "AM"))%>
        -
        <%= Html.DropDownList("drpEndTime", new SelectList(Model.Hours, whiteout.EndHour.Hour > 12 ? (whiteout.EndHour.Hour - 12).ToString("0,0") : whiteout.EndHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimem", new SelectList(Model.Minutes, whiteout.EndHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimet", new SelectList(Model.AMPM, whiteout.EndHour.Hour > 12 ? "PM" : "AM"))%>
    </td>
    <td>
      <%= Html.DropDownList("drprepeat", new SelectList(Model.RepeatList,whiteout.Repeats))%>
    </td>
    <td>
     Active
    </td>
    <td>
             <a class="icon-button-cancel" href='<%: Url.Action("EditWhiteOut", "Settings", new {Id = whiteout.WhiteoutID}) %>'>
    <img src='<%: Url.Content("~/static/Images/expanded.png") %>' alt="Delete this device" />
</a>
            <a class="icon-button-success" href="#">
            <img src="/static/images/gear.png" alt="Edit this device" /></a>
    </td>
    <td>
    </td>
</tr>
</code>```

I want to create an object of type Whiteout class and populate it with values selected by user from dropdowns and send to settingcontroller's EditWhiteout action method instead of passing only new {Id = whiteout.WhiteoutID}. How can I do this ?

Please suggest solution.

Thanks.

答:
Frist of all the link will result in a Get instead of Post. You need to use javascript function attached to the hyperlink to perform a POST to the action on the controller.

```<code><a class="icon-button-cancel" onclick="return SomeFunction(this)" href='<%: Url.Action("EditWhiteOut", "Settings", new {Id = whiteout.WhiteoutID}) %>'>

function SomeFunction(obj)
{

 document.forms[0].action = obj.href;
 document.forms[0].submit();
 return false;
}
</code>```

please also store the whiteout.whiteoutID in a hidden field.

```<code> ActionResult EditWhiteout (Whiteout whiteout)
</code>```

{
 Your Code goes here.
    }

Body:
I have following code in my MVC2 view:

        <%= Html.DropDownList("drpFields", new SelectList(Model.Fields, "FieldID", "NiceName", whiteout.FieldID)) %>

        <%= Html.DropDownList("drpStartTimeh", new SelectList(Model.Hours, whiteout.StartHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimem", new SelectList(Model.Minutes, whiteout.StartHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpStartTimet", new SelectList(Model.AMPM, whiteout.StartHour.Hour > 12 ? "PM" : "AM"))%>
        -
        <%= Html.DropDownList("drpEndTime", new SelectList(Model.Hours, whiteout.EndHour.Hour > 12 ? (whiteout.EndHour.Hour - 12).ToString("0,0") : whiteout.EndHour.Hour.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimem", new SelectList(Model.Minutes, whiteout.EndHour.Minute.ToString("0,0")))%>
        <%= Html.DropDownList("drpEndTimet", new SelectList(Model.AMPM, whiteout.EndHour.Hour > 12 ? "PM" : "AM"))%>

      <%= Html.DropDownList("drprepeat", new SelectList(Model.RepeatList,whiteout.Repeats))%>

     Active

             <a class="icon-button-cancel" href='<%: Url.Action("EditWhiteOut", "Settings", new {Id = whiteout.WhiteoutID}) %>'>
    <img src='<%: Url.Content("~/static/Images/expanded.png") %>' alt="Delete this device" />

I want to create an object of type Whiteout class and populate it with values selected by user from dropdowns and send to settingcontroller's EditWhiteout action method instead of passing only new {Id = whiteout.WhiteoutID}. How can I do this ?

Please suggest solution.

Thanks.

Body:
Frist of all the link will result in a Get instead of Post. You need to use javascript function attached to the hyperlink to perform a POST to the action on the controller.

<a class="icon-button-cancel" onclick="return SomeFunction(this)" href='<%: Url.Action("EditWhiteOut", "Settings", new {Id = whiteout.WhiteoutID}) %>'>

function SomeFunction(obj)
{

 document.forms[0].action = obj.href;
 document.forms[0].submit();
 return false;
}

please also store the whiteout.whiteoutID in a hidden field.

 ActionResult EditWhiteout (Whiteout whiteout)

{
 Your Code goes here.
    }


来源: stackexchange

问:
Flutter apps are too big in size
I have good experience in android app development using java. Recently I came to know about flutter. So, I have tried to create a simple android app with flutter based on official tutorial. But surprisingly the debug app size is 25MB and release apk costs more than 7MB. It is really larger when compare with native developed android app.

Is there any way to optimize it?

答:
For a debug apk below are steps for optimize -

Analyze for apk using Analyze APK from build tool of Android studio or manually by extracting the zip.

In my case the biggest folder was lib which contains 4 different folder named arm64-v8a , armeabi-v7a ,x86,x86_64

So these all four folders are basically different processor architecture of mobile devices.So to figure out your device falls under which category,below are some examples-

ARM: This is a mobile processor architecture first and foremost, and what the majority of phones run now. Qualcomm’s Snapdragon, Samsung’s Exynos, and MediaTek’s mobile chips are all examples of ARM processors. Most modern chips are 64-bit, or ARM64.

x86: This is the architecture specification for Intel chips. As dominant as Intel is in the computer market, these chips are far less common in Android handsets. x86_64 refers to 64-bit Intel chips.*

After finding your desired/required apk ,you can now split your apks based on these processor architecture using the command
flutter build apk --debug --split-per-abi

And finally check the  build/app/outputs/apk/debug/app-arm64-v8a-debug.apk(here replace with your choice) folder to get your desired and reduced apk.

ContentLicense: CC BY-SA 3.0

Title: Flutter apps are too big in size

ContentLicense: CC BY-SA 4.0


问:
Sorting a list based off of values in another list
I have two lists; invoice_ordering_list and pdfs. I need to sort pdfs based on the order of invoice_ordering_list.

```<code>invoice_ordering_list = ['265189', '265195', '265114', '265166', '265165', '265115']

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]
</code>```

I've tried:

```<code>keydict = dict(zip(pdfs, invoice_ordering_list))
pdfs.sort(key=keydict.get)
</code>```

For some reason it almost gets the order right but 265189 ends up at the end. I must be misunderstanding what's going on here. this seems like such an easy task that I just can't figure out.

The output should be:

```<code>pdfs_new = [
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57349 April Bill Inv 265115.pdf',
]
</code>```

答:
This seems like a problem for regex. As discussed in the comments, the actual problem is extracting the number for the sorting key from the pdf file name. I have created a simple match pattern to extract an integer from the end of a pdf file name, and use that as the key for sort.

```<code>import re

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]

def pdf_key(s):
    return int(re.search(r'(\d+)\.pdf$',s).group(1))

pdfs.sort(key=pdf_key)

print(pdfs)
</code>```

PS. I use https://regex101.com/ for testing regex match patterns, and it's very helpful.

Body:
I have two lists; invoice_ordering_list and pdfs. I need to sort pdfs based on the order of invoice_ordering_list.

invoice_ordering_list = ['265189', '265195', '265114', '265166', '265165', '265115']

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]

I've tried:

keydict = dict(zip(pdfs, invoice_ordering_list))
pdfs.sort(key=keydict.get)

For some reason it almost gets the order right but 265189 ends up at the end. I must be misunderstanding what's going on here. this seems like such an easy task that I just can't figure out.

The output should be:

pdfs_new = [
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57349 April Bill Inv 265115.pdf',
]

Body:
This seems like a problem for regex. As discussed in the comments, the actual problem is extracting the number for the sorting key from the pdf file name. I have created a simple match pattern to extract an integer from the end of a pdf file name, and use that as the key for sort.

import re

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]

def pdf_key(s):
    return int(re.search(r'(\d+)\.pdf$',s).group(1))

pdfs.sort(key=pdf_key)

print(pdfs)

PS. I use https://regex101.com/ for testing regex match patterns, and it's very helpful.


问:
How to enable github action to access secret property file
I was working on an android project where alot of sensitive api keys were involved. These keys were stored in a specific gradle property file which is ignored by git.

```<code>secret.properties
apikey="938484738288274932228"

</code>```

The question is how can I enable github actions to access this property file and the values inside it without pushing the file to git.

already tried
- making a fallback property file with blank values ( but the values might be required for future tests )

答:
So this is the method I used to make this work.

First place base64 encode the file content of the property file you want to hide.

Then add that base64 string into a Github secret by going to setting in Github web client

Then set up GitHub action in the project and add the task to write decoded content into a file from GH secret

```<code>- name: Decode secrets.properties file
        env:
          SECRETS_PROPERTIES: ${{ secrets.SECRETS_PROPERTIES }}
        run: echo "$SECRETS_PROPERTIES" | base64 -d > ./secrets.properties
</code>```

In your build.gradle file ( the one either in the root or /app directory ) you need to place the following code in order to let Gradle load the properties from the secrets.properties file.

```<code>def secretsPropertiesFile = rootProject.file("./secrets.properties")
def secretsProperties = new Properties()
secretsProperties.load(new FileInputStream(secretsPropertiesFile))
</code>```

Accessing the values within gradle would be secretsProperties['apikey']

More resources:

https://github.com/features/actions

https://help.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets

Body:
I was working on an android project where alot of sensitive api keys were involved. These keys were stored in a specific gradle property file which is ignored by git.

secret.properties
apikey="938484738288274932228"

The question is how can I enable github actions to access this property file and the values inside it without pushing the file to git.

already tried
- making a fallback property file with blank values ( but the values might be required for future tests )

Body:
So this is the method I used to make this work.

First place base64 encode the file content of the property file you want to hide.

Then add that base64 string into a Github secret by going to setting in Github web client

Then set up GitHub action in the project and add the task to write decoded content into a file from GH secret

- name: Decode secrets.properties file
        env:
          SECRETS_PROPERTIES: ${{ secrets.SECRETS_PROPERTIES }}
        run: echo "$SECRETS_PROPERTIES" | base64 -d > ./secrets.properties

In your build.gradle file ( the one either in the root or /app directory ) you need to place the following code in order to let Gradle load the properties from the secrets.properties file.

def secretsPropertiesFile = rootProject.file("./secrets.properties")
def secretsProperties = new Properties()
secretsProperties.load(new FileInputStream(secretsPropertiesFile))

Accessing the values within gradle would be secretsProperties['apikey']

More resources:

https://github.com/features/actions

https://help.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets


问:
How to jump to a particular line in a huge text file?
Are there any alternatives to the code below:

```<code>startFromLine = 141978 # or whatever line I need to jump to

urlsfile = open(filename, "rb", 0)

linesCounter = 1

for line in urlsfile:
    if linesCounter > startFromLine:
        DoSomethingWithThisLine(line)

    linesCounter += 1
</code>```

If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.

答:
Do the lines themselves contain any index information?  If the content of each line was something like "<line index>:Data", then the seek() approach could be used to do a binary search through the file, even if the amount of Data is variable.  You'd seek to the midpoint of the file, read a line, check whether its index is higher or lower than the one you want, etc.

Otherwise, the best you can do is just readlines().  If you don't want to read all 15MB, you can use the sizehint argument to at least replace a lot of readline()s with a smaller number of calls to readlines().

Body:
Are there any alternatives to the code below:

startFromLine = 141978 # or whatever line I need to jump to

urlsfile = open(filename, "rb", 0)

linesCounter = 1

for line in urlsfile:
    if linesCounter > startFromLine:
        DoSomethingWithThisLine(line)

    linesCounter += 1

If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.

OwnerDisplayName: DNS

ContentLicense: CC BY-SA 2.5


问:
Find nid from node's internal path in Drupal?
I have a path like this:

/news/2011/05/26/some-story-path

How do I find the nid for the node that the path points to?

Edit

The path above is simply a string value that I have on another page. I need to obtain information about the node that the path links to.

答:
In Drupal 6...

If you know the url alias, you can retrieve the internal system path:

```<code>$nid = str_replace("node/","",drupal_lookup_path("source","my/drupal/path"));
</code>```

From php, when viewing/editing a node, you can also retrieve it like so:

```<code>function get_current_nid () {
  if (arg(0) == 'node' && is_numeric(arg(1)) { return arg(1); }
  return null;
}

$nid = get_current_nid();
drupal_set_message("The current node id is: $nid");
</code>```

Body:
In Drupal 6...

If you know the url alias, you can retrieve the internal system path:

$nid = str_replace("node/","",drupal_lookup_path("source","my/drupal/path"));

From php, when viewing/editing a node, you can also retrieve it like so:

function get_current_nid () {
  if (arg(0) == 'node' && is_numeric(arg(1)) { return arg(1); }
  return null;
}

$nid = get_current_nid();
drupal_set_message("The current node id is: $nid");


问:
Adding an array of tags to xml root
I have an array of xml.etree.ElementTree.Element. i need to append it into root tag which contains few Tags (i.e) xml.etree.ElementTree.Element

for Example:

```<code><MxGraphModel>
    <root>
       <mxCell id="0"></mxCell>
       <mxCell id="1"></mxCell>
    </root>
</MxGraphModel>
</code>```

My array ['<mxCell id="3"></mxCell>','<mxCell id="4"></mxCell>']

My final output needs to be :

```<code><MxGraphModel>
     <root>
        <mxCell id="0"></mxCell>
        <mxCell id="1"></mxCell>
        <mxCell id="3"></mxCell>
        <mxCell id="4"></mxCell>
     </root>
</MxGraphModel>
</code>```

答:
Try this:

```<code>from xml.etree import ElementTree as ET

data = ['<mxCell id="3"></mxCell>','<mxCell id="4"></mxCell>']
root = ET.parse('test.xml').getroot()

nodes = root.find('root')
for x in data:
    nodes.append(ET.fromstring(x))

print(ET.tostring(root))
</code>```

Output:

```<code><MxGraphModel>
   <root>
      <mxCell id="0" />
      <mxCell id="1" />
      <mxCell id="3" />
      <mxCell id="4" />
   </root>
</MxGraphModel>
</code>```

Title: Adding an array of tags to xml root

Body:
I have an array of xml.etree.ElementTree.Element. i need to append it into root tag which contains few Tags (i.e) xml.etree.ElementTree.Element

for Example:

<MxGraphModel>
    <root>
       <mxCell id="0"></mxCell>
       <mxCell id="1"></mxCell>
    </root>
</MxGraphModel>

My array ['<mxCell id="3"></mxCell>','<mxCell id="4"></mxCell>']

My final output needs to be :

<MxGraphModel>
     <root>
        <mxCell id="0"></mxCell>
        <mxCell id="1"></mxCell>
        <mxCell id="3"></mxCell>
        <mxCell id="4"></mxCell>
     </root>
</MxGraphModel>

Body:
Try this:

from xml.etree import ElementTree as ET

data = ['<mxCell id="3"></mxCell>','<mxCell id="4"></mxCell>']
root = ET.parse('test.xml').getroot()

nodes = root.find('root')
for x in data:
    nodes.append(ET.fromstring(x))

print(ET.tostring(root))

Output:

<MxGraphModel>
   <root>
      <mxCell id="0" />
      <mxCell id="1" />
      <mxCell id="3" />
      <mxCell id="4" />
   </root>
</MxGraphModel>


问:
split a string without adjacent characters that matched regex in java
i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."

My regex-expression for spit is : "[^\\&]\\&[^\\&]"

My expectation is : [conditional&&operator and ampersand, Symbol]

But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

```<code>String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));
</code>```

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

答:
Your question is very similar to this one.

What you need is a negative look-behind. In your case, you could use something like:

String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("(?<!&)&(?!&)");
System.out.println(Arrays.toString(sarr));
// output: [conditional&&operator and ampersand, Symbol.]
```

Body:
i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."

My regex-expression for spit is : "[^\\&]\\&[^\\&]"

My expectation is : [conditional&&operator and ampersand, Symbol]

But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.


问:
how to run ionic app that works with api from another laravel app in real device?
the idea that i have laravel app and i want to make a mobile app that work with api from my laravel app . i succed to do this it's works perfectly in browser but when i want to test it with a real device or an emulator isn't work even i use the address ip of my computer to get the api from laravel app
instead of localhost
Sorry for my english and any one have idea for this problem please ?
this my code in ionic  provider where i get the api</p>

```<code> public token:any;
  constructor(public storage:Storage ,public http: Http) {
    console.log('Hello AuthProvider Provider');
  }
  login(credentials){
    return new Promise((resolve, reject) => {
        let headers = new Headers();

    headers.append('Access-Control-Allow-Origin' , '*');
       headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
      headers.append('Accept','application/json');
      headers.append('Content-type','application/json');
       headers.append('X-Requested-With','XMLHttpRequest');
        this.http.post('http://192.168.1.11:8101/api/auth/login', JSON.stringify(credentials), {headers: headers})
          .subscribe(res => {
            let data = res.json();
            this.token = data.token;
            localStorage.setItem('token',data.access_token);

            resolve(data);
   }, (err) => {
            reject(err);

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

答:
The code you have shared is not laravel code, this is your ionic code.
As you are saying your code is working in web app and not working in mobile platform with the same code. Then perhaps you are missing something from
config.xml file.

Please update this in your config.xml as it works fine for me.

```<code><author email="alex@artisanfertility.com" href="https://artisanfertility.com">Alex Steinleitner</autho
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
  <allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-navigation href="*" />
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
</platform>
</code>```

Body:
the idea that i have laravel app and i want to make a mobile app that work with api from my laravel app . i succed to do this it's works perfectly in browser but when i want to test it with a real device or an emulator isn't work even i use the address ip of my computer to get the api from laravel app
instead of localhost
Sorry for my english and any one have idea for this problem please ?
this my code in ionic  provider where i get the api

 public token:any;
  constructor(public storage:Storage ,public http: Http) {
    console.log('Hello AuthProvider Provider');
  }
  login(credentials){
    return new Promise((resolve, reject) => {
        let headers = new Headers();

    headers.append('Access-Control-Allow-Origin' , '*');
       headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
      headers.append('Accept','application/json');
      headers.append('Content-type','application/json');
       headers.append('X-Requested-With','XMLHttpRequest');
        this.http.post('http://192.168.1.11:8101/api/auth/login', JSON.stringify(credentials), {headers: headers})
          .subscribe(res => {
            let data = res.json();
            this.token = data.token;
            localStorage.setItem('token',data.access_token);

            resolve(data);
   }, (err) => {
            reject(err);

          });  });

Body:
The code you have shared is not laravel code, this is your ionic code.
As you are saying your code is working in web app and not working in mobile platform with the same code. Then perhaps you are missing something from
config.xml file.

Please update this in your config.xml as it works fine for me.

<author email="alex@artisanfertility.com" href="https://artisanfertility.com">Alex Steinleitner</autho
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
  <allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-navigation href="*" />
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
</platform>


问:
elasticsearch - get day of the week in text format like Monday, Tuesday etc
I want to get the aggregation result as day of week in text format like Monday, Tuesday etc. I have the following aggregation in which I am getting the result as day of week but in number format like 1 for monday, 2 for tuesday etc.

```<code>"aggs": {
   "perWeekDay": {
       "terms": {
           "script": "doc['order_datetime'].date.dayOfWeek"
       }
    }
}
</code>```

Update: I am doing this using script because I want to add custom field in kibana where I need to mention this script.

答:
Or you could do it like this

doc['timestamp'].date.dayOfWeek + " (" + ["", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][doc['timestamp'].date.dayOfWeek] + ")"

Body:
I want to get the aggregation result as day of week in text format like Monday, Tuesday etc. I have the following aggregation in which I am getting the result as day of week but in number format like 1 for monday, 2 for tuesday etc.

"aggs": {
   "perWeekDay": {
       "terms": {
           "script": "doc['order_datetime'].date.dayOfWeek"
       }
    }
}

Update: I am doing this using script because I want to add custom field in kibana where I need to mention this script.


问:
Creating a Rolling Mean with a Changing Window on Pandas
I have a Pandas dataframe as shown below. I am looking to creating a 7 day rolling mean for the temperature. I understand how to do this if it was one reading per day (dataset['rolling_temp'] = dataset.iloc[:,3].rolling(window=7).mean()) but the problem involves having a random number of readings per day. i.e. 1 day may be multiple rows.
 Any help would be much appreciated!

```<code>    day   temperature
1     1          18.0
2     1          19.0
3     2          18.0
4     3          17.0
5     4          18.5
6     4          19.0
7     5          18.0
8     6          19.0
9     7          18.5
10    8          17.5
11    9          17.0
12   10          18.0
13   11          19.0
14   12          19.5
15   13          16.5
16   13          17.0
</code>```

答:
You should be able to produce rolling stats if you convert your days into proper dates and make the index out of them. You will have to include months and years, so add extra columns if you do not store such values already, and then:

```<code>dataset['date'] = dataset[['year', 'month', 'day']].apply(lambda row: '{}-{}-{}'.format(row['year'], row['month'], row['day']), axis=1)
dataset.set_index('date', inplace=True')
dataset.temperature.rolling('7D', min_periods=1).mean()
</code>```

See for your reference at the bottom of this page.
You can also try to resample the index:

```<code>dataset.temperature.resample('D').rolling('7D', min_periods=1).mean()
</code>```

Note that this may not work with older versions of pandas, so if you run into errors consider upgrading to the latest stable.

Body:
I have a Pandas dataframe as shown below. I am looking to creating a 7 day rolling mean for the temperature. I understand how to do this if it was one reading per day (dataset['rolling_temp'] = dataset.iloc[:,3].rolling(window=7).mean()) but the problem involves having a random number of readings per day. i.e. 1 day may be multiple rows.
 Any help would be much appreciated!

    day   temperature
1     1          18.0
2     1          19.0
3     2          18.0
4     3          17.0
5     4          18.5
6     4          19.0
7     5          18.0
8     6          19.0
9     7          18.5
10    8          17.5
11    9          17.0
12   10          18.0
13   11          19.0
14   12          19.5
15   13          16.5
16   13          17.0

Body:
You should be able to produce rolling stats if you convert your days into proper dates and make the index out of them. You will have to include months and years, so add extra columns if you do not store such values already, and then:

dataset['date'] = dataset[['year', 'month', 'day']].apply(lambda row: '{}-{}-{}'.format(row['year'], row['month'], row['day']), axis=1)
dataset.set_index('date', inplace=True')
dataset.temperature.rolling('7D', min_periods=1).mean()

See for your reference at the bottom of this page.
You can also try to resample the index:

dataset.temperature.resample('D').rolling('7D', min_periods=1).mean()

Note that this may not work with older versions of pandas, so if you run into errors consider upgrading to the latest stable.


问:
Find and Return found string in an array
I am looking for a function that suits the following situation.

What the script does:
It retrieves the server.log from a minecraft server, and breaks it into sections from user chats, to server notifications etc.

I have an array containing the users information, it is set by another file called users.yml
and it is converted to an array like so

```<code>$userconfig = array(
    'TruDan'    => array(
        'prefix'    => '&3',
        'suffix'    => '&e',
    ),
    'TruGaming' => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'PancakeMiner'  => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'Teddybear952'  => array(
        'prefix'    => '&b',
        'suffix'    => '&f',
    ),
);
</code>```

What i want to do, is search the $line from server.log (it loops through lines) for a username above (array key) and return the array. so i can then parse $ret['prefix'] and $ret['suffix']

mc.php (the file) http://pastebin.com/9geyfuup
server.log (partial, the actual thing is 12,000 lines long, so i took a few lines from it) http://pastebin.com/DKz8YfgK

答:
So you want to take 'TruDan', 'TruGaming', 'PancakeMiner', and 'Teddybear952' and see if they show up in a particular log file at all?

```<code>$names = array_keys($userconfig); // get the user names

$name_regex = implode('|', $names);   // produce a|b|c|d

... load your log file
foreach($lines as $line) {
   if (preg_match("/($names)/", $line, $matches)) { // search for /(a|b|c|d)/ in the string
       echo "found $matches[1] in $line";
       print_r($userconfig[$matches[1]]); // show the user's config data.
   }
}
</code>```

Of course, this is simplistic. if there's any regex metacharacters in the username, it'll cause a syntax error in the regex, so you'd want to massage the names a bit before building the regex clause.

Body:
I am looking for a function that suits the following situation.

What the script does:
It retrieves the server.log from a minecraft server, and breaks it into sections from user chats, to server notifications etc.

I have an array containing the users information, it is set by another file called users.yml
and it is converted to an array like so

$userconfig = array(
    'TruDan'    => array(
        'prefix'    => '&3',
        'suffix'    => '&e',
    ),
    'TruGaming' => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'PancakeMiner'  => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'Teddybear952'  => array(
        'prefix'    => '&b',
        'suffix'    => '&f',
    ),
);

What i want to do, is search the $line from server.log (it loops through lines) for a username above (array key) and return the array. so i can then parse $ret['prefix'] and $ret['suffix']

mc.php (the file) http://pastebin.com/9geyfuup
server.log (partial, the actual thing is 12,000 lines long, so i took a few lines from it) http://pastebin.com/DKz8YfgK

Body:
So you want to take 'TruDan', 'TruGaming', 'PancakeMiner', and 'Teddybear952' and see if they show up in a particular log file at all?

$names = array_keys($userconfig); // get the user names

$name_regex = implode('|', $names);   // produce a|b|c|d

... load your log file
foreach($lines as $line) {
   if (preg_match("/($names)/", $line, $matches)) { // search for /(a|b|c|d)/ in the string
       echo "found $matches[1] in $line";
       print_r($userconfig[$matches[1]]); // show the user's config data.
   }
}

Of course, this is simplistic. if there's any regex metacharacters in the username, it'll cause a syntax error in the regex, so you'd want to massage the names a bit before building the regex clause.


问:
Can I use double equal in JavaScript if one of the elements is a string?
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.

'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false
```

So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.

Is there any down side for my approach?

I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?

答:
If you use '10' == 10 , then the js interpreter must do a type conversion. This costs a  little performance.

If you are using code quality tools like sonarqube, you will get some 'hints' to fix it.

Body:
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.

'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false

So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.

Is there any down side for my approach?

I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?


问:
Confirm whether to write comments with xpath
Could you make an example with the site? I want to ignore the posts with comments and just click the ones without comments.

```
from selenium import webdriver
import time

path = "C:\chromed\chromedriver.exe"
driver = webdriver.Chrome(path) #path
'''

'''
driver.get("http://cineaste.co.kr/") #url
time.sleep(0.5)

postclick = driver.find_element_by_xpath("//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]") #로그인창 활성화
postclick.click()

driver.close()
```

I tried this, but there was an error.

```
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]"}
  (Session info: chrome=81.0.4044.138)
```

I want to click on a post that doesn't have any comments yet. And I want to skip posts with comments.
I'm still a beginner. Help me.

答:
The Element you are looking for is not available.
You need to recreate the Xpath. The Xpath you created is incorrect. See following image :-

Body:
Could you make an example with the site? I want to ignore the posts with comments and just click the ones without comments.

from selenium import webdriver
import time

path = "C:\chromed\chromedriver.exe"
driver = webdriver.Chrome(path) #path
'''

'''
driver.get("http://cineaste.co.kr/") #url
time.sleep(0.5)

postclick = driver.find_element_by_xpath("//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]") #로그인창 활성화
postclick.click()

driver.close()

I tried this, but there was an error.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]"}
  (Session info: chrome=81.0.4044.138)

I want to click on a post that doesn't have any comments yet. And I want to skip posts with comments.
I'm still a beginner. Help me.


问:
(Unity) How can I save all of the Options that i've added dynamically to a dropdown?
In Unity I have created an input field and buttons that dynamically add/remove Options to a Dropdown menu while the program is running. How can I save all of the Dropdown Options when I close the program, so that I can load the Options on next start up? To clarify, I don't need to save the Dropdown Option that is selected, I need to save all of the available Options.

Thank you for your help!

答:
If you're just saving strings, it's pretty easy and there are a few options.

If there are only a few, you could use PlayerPrefs

If there are more than a few, or you want to let the player edit them, save them to a text file in the StreamingAssets folder using JSONUtility. If you want to save images, you'd probably save them to the same place but the process would just be a bit more complicated to make sure you save the images along with the strings.

More info about saving persistent data between sessions here.


问:
AutoConfigure RestController Spring Boot
I have tried to find documentation on how to manually configure a RestController (i.e in a Configuation class). That means without using the RestController annotation. Considering all the other annotations, like mapping, pathvariables etc. is at all possible?  </p>

答:
A controller is essentially a component with a request mapping. See RequestMappingHandlerMapping.

    @Override
    protected boolean isHandler(Class<?> beanType) {
        return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
                AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
    }
```

<p>If you want to instantiate a "rest controller" through configuration, you can probably do so via the following:</p>

<pre class="lang-java prettyprint-override"><code>@Configuration
public class MyConfiguration {
   @Bean
   public MyController() {
      return new MyController();
   }
}
</code>```

@ResponseBody
public class MyController {
   @RequestMapping("/test")
   public String someEndpoint() {
      return "some payload";
   }
}
```

But I don't think you'll be able to configure the request mappings (path variables, etc) in the configuration though; at least I haven't seen an example nor figured out how.

Body:
A controller is essentially a component with a request mapping. See RequestMappingHandlerMapping.

    @Override
    protected boolean isHandler(Class<?> beanType) {
        return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
                AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
    }

If you want to instantiate a "rest controller" through configuration, you can probably do so via the following:

@Configuration
public class MyConfiguration {
   @Bean
   public MyController() {
      return new MyController();
   }
}

@ResponseBody
public class MyController {
   @RequestMapping("/test")
   public String someEndpoint() {
      return "some payload";
   }
}

But I don't think you'll be able to configure the request mappings (path variables, etc) in the configuration though; at least I haven't seen an example nor figured out how.


问:
Was there a good reason for redundant try catch code in original Microsoft Membership and Role Provider code?
I know that this is redundant (per Why does resharper say 'Catch clause with single 'throw' statement is redundant'?).

```<code>try
{
    bla bla bla
}
catch
{
    throw
}
</code>```

So, I'm going through the old Microsoft Membership and Role Provider code (made available since 2006 per http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx).  And, low and behold, the code is chock full of this redundant code.

Was there a good reason?

答: This is a lazy way to put a breakpoint on that throw line, without turning on any of the debugger features that break on all exceptions.

Body:
I know that this is redundant (per Why does resharper say 'Catch clause with single 'throw' statement is redundant'?).

try
{
    bla bla bla
}
catch
{
    throw
}

So, I'm going through the old Microsoft Membership and Role Provider code (made available since 2006 per http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx).  And, low and behold, the code is chock full of this redundant code.

Was there a good reason?


问:
Email reset password not working, however account confirmation works .NetCore
So I followed the instructions here: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio

My application works and sends out an account confirmation email using the Email service I set up.

However if I go to reset password, the identity service does not call the email service to send the email instructions. What am I doing wrong?

How can the identity service know how to use email to confirm account but can't use it to reset password?

For context

```<code> startup.cs

 // requires
 services.AddTransient<IEmailSender, EmailSender>();
 services.Configure<AuthMessageSenderOptions>(Configuration);

 EmailSender.cs

public class EmailSender:IEmailSender
{
    public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
    {
        Options = optionsAccessor.Value;
    }

    public AuthMessageSenderOptions Options { get; } //set only via Secret Manager

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Execute(Options.SendGridKey, subject, message, email);
    }

    public Task Execute(string apiKey, string subject, string message, string email)
    {
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("stackoverflow@blah.com", Options.SendGridUser),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(email));

        // Disable click tracking.
        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(false, false);

        return client.SendEmailAsync(msg);
    }
}
</code>```

答:
We ran into the same issue and discovered that while registration emails were being sent, password reset emails were not. In our case, it was because of two issues with the AspNetUsers table:

We didn't complete the email confirmation step, which sets the EmailConfirmed bool in the database to True, and

We had migrated the data over from an earlier version of ASP.NET Core where the two email fields, Email and NormalizedEmail were not set and were left null.

Once we populated the missing email fields, and ran the confirmation step—or manually changed the flag to True—the password reset emails started working.

Body:
So I followed the instructions here: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio

My application works and sends out an account confirmation email using the Email service I set up.

However if I go to reset password, the identity service does not call the email service to send the email instructions. What am I doing wrong?

How can the identity service know how to use email to confirm account but can't use it to reset password?

For context

 startup.cs

 // requires
 services.AddTransient<IEmailSender, EmailSender>();
 services.Configure<AuthMessageSenderOptions>(Configuration);

 EmailSender.cs

public class EmailSender:IEmailSender
{
    public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
    {
        Options = optionsAccessor.Value;
    }

    public AuthMessageSenderOptions Options { get; } //set only via Secret Manager

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Execute(Options.SendGridKey, subject, message, email);
    }

    public Task Execute(string apiKey, string subject, string message, string email)
    {
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("stackoverflow@blah.com", Options.SendGridUser),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(email));

        // Disable click tracking.
        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(false, false);

        return client.SendEmailAsync(msg);
    }
}


问:
Azure Synapse Analytics monitor rowgroup skipping
For reference i'm using a CCI table (Hash)
I'm looking for a solution to monitor if, for a query with a WHERE predicate on my Hash, Synapse is well skipping the invalid rowgroups. </p>

答:
For a Hash-distributed table Synapse will eliminate Distributions, not rowgroups.  It's the partition scheme and CCI order that control row group skipping.  And that should be evident in the execution plan.

For a CCI, each table has multiple (60) Distributions.  Each Distribution has one or more Partitions.  Each Partition has one or more Row Groups.  Each Row Group has up to 1 million rows.

For Heaps and Clustered Index tables it's the same, except each Partition has one Heap or Clustered Index.


问:
Normalize data before or after split of training and testing data?
I want to separate my data into train and test set, should I apply normalization over data before or after the split? Does it make any difference while building predictive model?</p>

答:
Ask yourself if your data will look different depending on whether you transform before or after your split. If you're doing a log2 transformation, the order doesn't matter because each value is transformed independently of the others. If you're scaling and centering your data, the order does matter because an outlier can drastically change the final distribution. You're allowing the test set to "spill over" and affect your training set, potentially causing overly optimistic performance measures.

For R uses, the caret package is good at handling test/train splits. You can add the argument preProcess = c("scale", "center") to the train function and it will automatically apply any transformation from the training data onto the test data.

Tl;dr - if the data is different depending on whether your normalize before or after your split, do it before


答:
It depends on the ocassion.

For example if you try to check if 9 == '9' it would return true, but they are in fact different, because one of then is a word(string) and the other is number(integer). In some of the cases that would make you suffer later.

The best scenario is to know what you are expecting it to be - is it a string, integer or something else and use the === or atleast check the type of the variable.

Title: Can I use double equal in JavaScript if one of the elements is a string?


问:
Symfony: send failed messages via email
I have a simple messanger config:

framework:
    messenger:
        failure_transport: failed
        transports:
            async:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                retry_strategy:
                    max_retries: 2
                    delay: 10000
            failed: 'doctrine://default?queue_name=failed'

        routing:
            someInterface: async
```

I would like to know about every message routed to failed transport f.e. system should send email notification to me when message is redirecting. My only idea is to periodically review messenger_messages table which contains messages stored in failed transport but imao it's not symfony-way solution. Do you know more clever solution for this feature?

I am using symfony/messenger with version 5.*

答:
I don't think it's possible to do it through configuration, but you create your custom middleware and send email by yourself. https://symfony.com/doc/current/messenger.html#middleware

You can check FailedMessageProcessingMiddleware for reference https://github.com/symfony/messenger/blob/master/Middleware/FailedMessageProcessingMiddleware.php

Title: Symfony: send failed messages via email

Body:
I have a simple messanger config:

framework:
    messenger:
        failure_transport: failed
        transports:
            async:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                retry_strategy:
                    max_retries: 2
                    delay: 10000
            failed: 'doctrine://default?queue_name=failed'

        routing:
            someInterface: async

I would like to know about every message routed to failed transport f.e. system should send email notification to me when message is redirecting. My only idea is to periodically review messenger_messages table which contains messages stored in failed transport but imao it's not symfony-way solution. Do you know more clever solution for this feature?

I am using symfony/messenger with version 5.*


问:
Convert basic array to PHP array
I have an array that I pull that looks like this:

[157966745,275000353,43192565,305328212]...

How do I go about taking that "string" and converting it to a PHP array which I can then manipulate.

答:
PHP explode is built just for this.

$result = explode(',', $input)

Title: Convert basic array to PHP array


问:
Firebase Firestore iOS Multiple Models
I am new to Firestore and am struggling to try to find examples of projects with a few layers on iOS. I want to utilize all Firestore has to offer.

I have a user setup that maps Quizzes to a user. (All works perfectly) Now I want to build my Quiz structure. A Quiz object that has Questions and these questions have Answers.

I have built it to a certain level but it feels hacky. Can anyone share their best practice knowledge with me? It would be greatly appreciated.

Work so far:

Firestore format: "/quizzes/idone/questions/idtwo/questions"

struct Quiz: Codable, Identifiable {
  @DocumentID var id: String?
  var title: String
  var score: Int?
  var completed: Bool
  @ServerTimestamp var createdTime: Timestamp?
  var userId: String?
  var questions: [Question]?
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>struct Question: Codable, Identifiable {
  @DocumentID var id: String?
  var title: String?
  var completed: Bool?
  //TODO: Answers
}</code>```

    do {
      var userQuiz = quiz
      userQuiz.userId = self.userId
        let questionOne = Question(title: "What day is it today?",
                                 imageName: "test.jpeg",
                                 completed: false)
        let questioTwo = Question(title: "What is the meaning of life?",
                                 imageName: "test.jpeg",
                                 completed: false)
      let _ = try db
            .collection("quizzes").addDocument(from: userQuiz) // Works perfect
            .collection("questions").addDocument(from: questionOne) // Here is the issue I can't add multiple questions.
    }
    catch {
      fatalError("Unable to encode quiz: \(error.localizedDescription).")
    }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  private func loadData() {
    if listenerRegistration != nil {
      listenerRegistration?.remove()
    }
    listenerRegistration = db.collection(quizzesPath)
      .whereField("userId", isEqualTo: self.userId)
      .order(by: "createdTime")
      .addSnapshotListener { (querySnapshot, error) in
        if let querySnapshot = querySnapshot {
          self.quizzes = querySnapshot.documents.compactMap { document -> Quiz? in
            try? document.data(as: Quiz.self)
          }
          //Todo: This is the main part I have a issue at. How do I consume my questions and mapp them to quizzes
          let questions = querySnapshot.documents.compactMap { document -> [Question]? in
            try? document.data(as: [Question].self)
          }
          //self.quizzes.questions = questions
        }
      }
  }</code>```

答:
If you would like to know best practices on data models and how to structure your data take a look at these two links [1] [2]. It also has videos as well that will be informative on getting you started with Firestore.

[1] https://firebase.google.com/docs/firestore/data-model

[2] https://firebase.google.com/docs/firestore/manage-data/structure-data

Title: Firebase Firestore iOS Multiple Models

Body:
I am new to Firestore and am struggling to try to find examples of projects with a few layers on iOS. I want to utilize all Firestore has to offer.

I have a user setup that maps Quizzes to a user. (All works perfectly) Now I want to build my Quiz structure. A Quiz object that has Questions and these questions have Answers.

I have built it to a certain level but it feels hacky. Can anyone share their best practice knowledge with me? It would be greatly appreciated.

Work so far:

Firestore format: "/quizzes/idone/questions/idtwo/questions"

struct Quiz: Codable, Identifiable {
  @DocumentID var id: String?
  var title: String
  var score: Int?
  var completed: Bool
  @ServerTimestamp var createdTime: Timestamp?
  var userId: String?
  var questions: [Question]?
}

struct Question: Codable, Identifiable {
  @DocumentID var id: String?
  var title: String?
  var completed: Bool?
  //TODO: Answers
}

    do {
      var userQuiz = quiz
      userQuiz.userId = self.userId
        let questionOne = Question(title: "What day is it today?",
                                 imageName: "test.jpeg",
                                 completed: false)
        let questioTwo = Question(title: "What is the meaning of life?",
                                 imageName: "test.jpeg",
                                 completed: false)
      let _ = try db
            .collection("quizzes").addDocument(from: userQuiz) // Works perfect
            .collection("questions").addDocument(from: questionOne) // Here is the issue I can't add multiple questions.
    }
    catch {
      fatalError("Unable to encode quiz: \(error.localizedDescription).")
    }

  private func loadData() {
    if listenerRegistration != nil {
      listenerRegistration?.remove()
    }
    listenerRegistration = db.collection(quizzesPath)
      .whereField("userId", isEqualTo: self.userId)
      .order(by: "createdTime")
      .addSnapshotListener { (querySnapshot, error) in
        if let querySnapshot = querySnapshot {
          self.quizzes = querySnapshot.documents.compactMap { document -> Quiz? in
            try? document.data(as: Quiz.self)
          }
          //Todo: This is the main part I have a issue at. How do I consume my questions and mapp them to quizzes
          let questions = querySnapshot.documents.compactMap { document -> [Question]? in
            try? document.data(as: [Question].self)
          }
          //self.quizzes.questions = questions
        }
      }
  }


问:
MongoError: Topology is closed, please connect seems to be related to MongoClient.close() and the client won't work while using it
This question here is closely related but the question and the answer are not very related at all. However, in the comments of that OP's post there is the difficulty of working with .close()... That is where the similarities end.

The issue comes from trying to create an api using the direct nodejs mongodb driver 3.9.  I have the client call in the controller because putting it in the server and calling to the client when needed constantly creates a "connect error" so here it is in the controller for full context.

whenever I use .close() in the collection client call it will run once and then every other call after that will cause an error Topology is closed.  So, for now I commented it out. I am wondering what is causing this and what might I being doing incorrectly causing this error?

The documentation per the driver states to use this and what the purpose is but it is breaking my api repeatedly.

const express = require('express');
const router = express.Router();

import { MongoClient, MongoCallback, MongoError, MongoNetworkError } from 'node_modules/mongodb';
// const MongoClient = require('node_modules/mongodb').MongoClient;
const dbName = 'HealthCheckup';
const documentName = 'userProfile';
const assert = require('assert');
const url = `mongodb+srv://UserDB:h7srvvvvvvvHFd8@vvvvvvvvvai-cvyrh.azure.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true});

const findUsers = (client, callback) => {
    // Get the documents collection
    const collection = client.collection(documentName);
    // Insert some documents
    collection.find({}).toArray( (err, result) => {
        // console.log('err **** -------- ', err);
        // console.log('Result -------- ', result);
        callback(err, result);
    });
}

const createUser = (client, callback, req) => {
    // Get the documents collection
    const collection = client.collection(documentName);
    // Insert some documents
    collection.insertOne({
        name: req.body.name,
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        tokenId: req.body.tokenId,
        userPhoto: req.body.userPhoto
    }, (err, result) => {
        // console.log('err **** -------- ', err);
        // console.log('Result -------- ', result);
        callback(err, result);
    });
}

// localhost:4021/user
router.get('/', (req, res) => {
    client.connect( err => {
        const collection = client.db(dbName);
        if (!err) {
            console.log("Connected successfully to server.");
        } else {
            console.log('Error in DB connection : ', JSON.stringify(err, undefined, 2));
        }
        findUsers(collection, (err, result) => {
            console.log('err 2222222 -------- ', err);
            console.log('Result 2222222 -------- ', result);
            if (!err) {
                res.send(result);
            } else {
                console.log('Error retreiving user ', JSON.stringify(err, undefined, 2))
            }
            console.log('BREAKPOINT 00000000000000000');
            // client.close();
        });
    });
});
```

答:
You are trying to close the client in a request handler, but your client is global.

If you want to have a global client, do not close it in request handlers.

If you want to close the client in request handlers, create the client in the handler of the same request.


问:
CMake cannot find OpenMP
I am trying to compile with OpenMP. My CMakeLists.txt contains the line

find_package(OpenMP REQUIRED)

and CMake errors out with

```<code>CMake Error at /opt/ros/groovy/share/catkin/cmake/catkinConfig.cmake:72 (find_package):
  Could not find a configuration file for package openmp.

  Set openmp_DIR to the directory containing a CMake configuration file for
  openmp.  The file will have one of the following names:

    openmpConfig.cmake
    openmp-config.cmake
</code>```

Checking my filesystem, I see that I have /usr/share/cmake-2.8/Modules/FindOpenMP.cmake but no openmpConfig.cmake or openmp-config.cmake. What do I need to do to fix this?

答:
You should install libomp with brew install libomp

i use macOS and it worked smoothly for me.

Title: CMake cannot find OpenMP

Body:
I am trying to compile with OpenMP. My CMakeLists.txt contains the line

find_package(OpenMP REQUIRED)

and CMake errors out with

CMake Error at /opt/ros/groovy/share/catkin/cmake/catkinConfig.cmake:72 (find_package):
  Could not find a configuration file for package openmp.

  Set openmp_DIR to the directory containing a CMake configuration file for
  openmp.  The file will have one of the following names:

    openmpConfig.cmake
    openmp-config.cmake

Checking my filesystem, I see that I have /usr/share/cmake-2.8/Modules/FindOpenMP.cmake but no openmpConfig.cmake or openmp-config.cmake. What do I need to do to fix this?


问:
Express / React - In production, my axios requests contains my index.html file in response and don't reach my express server api routes
I did some research and found similar posts with this problem but none of the solutions worked for me.

I've made a React app with create-react-app and then i've created a server.js file to have a Express Node server. I've followed some tutorials and it seems that i can pu my react app and my express server in the same app/build.

In local, everything is working, i reach my api routes. But when i deploy the build of my app on a server, all my axios requests responses are the index.html file off my app. What's the issue in my code that don't allow my axios requests to reach my api ?

Here's the code :

server.js

```<code>const connection = require("./conf");
const path = require("path");
const app = express();

app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);

app.post("/api/user", (req, res) => {
  const formData = req.body;
  connection.query("INSERT INTO user SET ?", formData, (err, results) => {
    if (err) {
      res.status(500).send("Error");
    } else {
      res.sendStatus(200);
    }
  });
});

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, ".build/index.html"));
});

app.listen(8080, () =>
  console.log("Express server is running on localhost:8080")
);
</code>```

Mail.js with axios

```<code>axios
  .post(
    "/api/user",
    {
      email: "xxx",
      name: "xxx"
    },
    { withCredentials: true }
  )
  .then((response) => {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

and the response from axios

```<code>{data: "<!doctype html><html lang="en"><head><meta charset…s/main.f398f833.chunk.js"></script></body></html>", status: 200, statusText: ""
</code>```

and in console i have the good url :

```<code>xhr.js:178 XHR finished loading: POST "https://www.mywebsite.com/api/user".
</code>```

If i put this url in my browser, i have a blank page, like when i put an url which is not in my front-end react router.

Thanks for the help !

答: Did you put proxy in package.json or set baseURL of axios</p>

Body:
I did some research and found similar posts with this problem but none of the solutions worked for me.

I've made a React app with create-react-app and then i've created a server.js file to have a Express Node server. I've followed some tutorials and it seems that i can pu my react app and my express server in the same app/build.

In local, everything is working, i reach my api routes. But when i deploy the build of my app on a server, all my axios requests responses are the index.html file off my app. What's the issue in my code that don't allow my axios requests to reach my api ?

Here's the code :

server.js

const connection = require("./conf");
const path = require("path");
const app = express();

app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);

app.post("/api/user", (req, res) => {
  const formData = req.body;
  connection.query("INSERT INTO user SET ?", formData, (err, results) => {
    if (err) {
      res.status(500).send("Error");
    } else {
      res.sendStatus(200);
    }
  });
});

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, ".build/index.html"));
});

app.listen(8080, () =>
  console.log("Express server is running on localhost:8080")
);

Mail.js with axios

axios
  .post(
    "/api/user",
    {
      email: "xxx",
      name: "xxx"
    },
    { withCredentials: true }
  )
  .then((response) => {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

and the response from axios

{data: "<!doctype html><meta charset…s/main.f398f833.chunk.js"></script>", status: 200, statusText: ""

and in console i have the good url :

xhr.js:178 XHR finished loading: POST "https://www.mywebsite.com/api/user".

If i put this url in my browser, i have a blank page, like when i put an url which is not in my front-end react router.

Thanks for the help !


问:
name 'doc2vec' is not defined
I am trying to use doc2vec for text classification but after importing when i am trying to use it inside a function its says doc2vec in not defined. Please help me to identify which all libraries should I be installing to use doc2vec.

here I have 2 columns called Action(Text or sentences) and Category(actual tags)

```<code>from gensim.models import Doc2Vec
import gensim
from gensim.models.doc2vec import TaggedDocument
def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
    return labeled
X_train, X_test, y_train, y_test = train_test_split(df.Action, df.Category, random_state=0, test_size=0.3)
X_train = label_sentences(X_train, 'Train')

Error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-66-d20e5f21684d> in <module>
----> 1 X_train = label_sentences(X_train, 'Train')

<ipython-input-53-bca3c695cfb6> in label_sentences(corpus, label_type)
      8     for i, v in enumerate(corpus):
      9         label = label_type + '_' + str(i)
---> 10         labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
     11     return labeled

NameError: name 'doc2vec' is not defined
</code>```

答:
You imported TaggedDocument and not doc2vec but you used it this way labeled.append(doc2vec.TaggedDocument(v.split(), [label]))

So just use TaggedDocument  directly or if you don’t want that, just import doc2vec from gensim.models import doc2vec

Title: name 'doc2vec' is not defined

Body:
I am trying to use doc2vec for text classification but after importing when i am trying to use it inside a function its says doc2vec in not defined. Please help me to identify which all libraries should I be installing to use doc2vec.

here I have 2 columns called Action(Text or sentences) and Category(actual tags)

from gensim.models import Doc2Vec
import gensim
from gensim.models.doc2vec import TaggedDocument
def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
    return labeled
X_train, X_test, y_train, y_test = train_test_split(df.Action, df.Category, random_state=0, test_size=0.3)
X_train = label_sentences(X_train, 'Train')

Error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-66-d20e5f21684d> in <module>
----> 1 X_train = label_sentences(X_train, 'Train')

<ipython-input-53-bca3c695cfb6> in label_sentences(corpus, label_type)
      8     for i, v in enumerate(corpus):
      9         label = label_type + '_' + str(i)
---> 10         labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
     11     return labeled

NameError: name 'doc2vec' is not defined


问:
AttributeError: can't set attribute,
I have this vgg model. Which I am using to extract an image features. But I am getting an attribute error: I can't seem to understand the error. I am using keras 2.2.4 and tensorflow 1.13.1 with python 3.7.3. I am using anaconda with spyder as IDE. </p>

```<code>
import numpy as np
import warnings

#tf.compat.v1.reset_default_graph()

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import GlobalMaxPooling2D
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras.preprocessing import image
from tensorflow.python.keras.utils import layer_utils , get_source_inputs
from tensorflow.python.keras.utils.data_utils import get_file
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.applications.imagenet_utils import decode_predictions
from tensorflow.python.keras.applications.imagenet_utils import preprocess_input
from keras_applications.imagenet_utils import _obtain_input_shape
#from keras.engine.topology import get_source_inputs

#from tensorflow.python.keras.utils.layer_utils import get_source_inputs

WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5'
WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

def VGG16(include_top=True, weights='imagenet',
          input_tensor=None, input_shape=None,
          pooling=None,
          classes=1000):

    if weights not in {'imagenet', None}:
        raise ValueError('The `weights` argument should be either '
                         '`None` (random initialization) or `imagenet` '
                         '(pre-training on ImageNet).')

    if weights == 'imagenet' and include_top and classes != 1000:
        raise ValueError('If using `weights` as imagenet with `include_top`'
                         ' as true, `classes` should be 1000')
    # Determine proper input shape
    input_shape = _obtain_input_shape(input_shape,
                                      default_size=224,
                                      min_size=48,
                                      data_format=K.image_data_format(),
                                      require_flatten=include_top)

    if input_tensor is None:
        img_input = Input(shape=input_shape)
    else:
        if not K.is_keras_tensor(input_tensor):
            img_input = Input(tensor=input_tensor, shape=input_shape)
        else:
            img_input = input_tensor
    # Block 1
    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)
    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)

    # Block 2
    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)

    # Block 3
    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)

    # Block 4
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)

    # Block 5
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)

    if include_top:
        # Classification block
        x = Flatten(name='flatten')(x)
        x = Dense(4096, activation='relu', name='fc1')(x)
        x = Dense(4096, activation='relu', name='fc2')(x)
        x = Dense(classes, activation='softmax', name='predictions')(x)
    else:
        if pooling == 'avg':
            x = GlobalAveragePooling2D()(x)
        elif pooling == 'max':
            x = GlobalMaxPooling2D()(x)

    # Ensure that the model takes into account
    # any potential predecessors of `input_tensor`.
    if input_tensor is not None:
        inputs = get_source_inputs(input_tensor)
    else:
        inputs = img_input
    # Create model.
    model = Model(inputs, x, name='vgg16')

    # load weights
    if weights == 'imagenet':
        if include_top:
            weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels.h5',
                                    WEIGHTS_PATH,
                                   )
        else:
            weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
                                    WEIGHTS_PATH_NO_TOP,
                                    cache_subdir='models')
        model.load_weights(weights_path)
        if K.backend() == 'theano':
            layer_utils.convert_all_kernels_in_model(model)

        if K.image_data_format() == 'channels_first':
            if include_top:
                maxpool = model.get_layer(name='block5_pool')
                shape = maxpool.output_shape[1:]
                dense = model.get_layer(name='fc1')
                layer_utils.convert_dense_weights_data_format(dense, shape, 'channels_first')

            if K.backend() == 'tensorflow':
                warnings.warn('You are using the TensorFlow backend, yet you '
                              'are using the Theano '
                              'image data format convention '
                              '(`image_data_format="channels_first"`). '
                              'For best performance, set '
                              '`image_data_format="channels_last"` in '
                              'your Keras config '
                              'at ~/.keras/keras.json.')
    model.layers.pop() # Get rid of the classification layer
    model.outputs = [model.layers[-1].output]
    model.layers[-1].outbound_nodes = [ ]
    return model```

</code>```

<p>I am getting the following error on the second last line of the code:</p>

```<code>File "/home/natsu/Final_code/vgg16.py", line 200, in VGG16

    model.layers[-1].outbound_nodes = []

  File "/home/natsu/anaconda3/envs/py-env/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py", line 1639, in __setattr__
    super(Layer, self).__setattr__(name, value)

AttributeError: can't set attribute```
</code>```

答:
I was able to execute your code successfully in tensorflow version 1.15 without any modifications.

I was able to execute your code successfully in tensorflow version 2.2.0 with minor modifications shown below -

Modify,

```<code>from tensorflow.python.keras.utils import layer_utils , get_source_inputs
</code>```

to

```<code>from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.keras.utils.layer_utils import get_source_inputs
</code>```

Can you please upgrade the tensorflow version and check if the error is fixed.

Hope this answers your question. Happy Learning.

Title: AttributeError: can't set attribute,

Body:
I have this vgg model. Which I am using to extract an image features. But I am getting an attribute error: I can't seem to understand the error. I am using keras 2.2.4 and tensorflow 1.13.1 with python 3.7.3. I am using anaconda with spyder as IDE.

import numpy as np
import warnings

#tf.compat.v1.reset_default_graph()

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import GlobalMaxPooling2D
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras.preprocessing import image
from tensorflow.python.keras.utils import layer_utils , get_source_inputs
from tensorflow.python.keras.utils.data_utils import get_file
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.applications.imagenet_utils import decode_predictions
from tensorflow.python.keras.applications.imagenet_utils import preprocess_input
from keras_applications.imagenet_utils import _obtain_input_shape
#from keras.engine.topology import get_source_inputs

#from tensorflow.python.keras.utils.layer_utils import get_source_inputs

WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5'
WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

def VGG16(include_top=True, weights='imagenet',
          input_tensor=None, input_shape=None,
          pooling=None,
          classes=1000):

    if weights not in {'imagenet', None}:
        raise ValueError('The `weights` argument should be either '
                         '`None` (random initialization) or `imagenet` '
                         '(pre-training on ImageNet).')

    if weights == 'imagenet' and include_top and classes != 1000:
        raise ValueError('If using `weights` as imagenet with `include_top`'
                         ' as true, `classes` should be 1000')
    # Determine proper input shape
    input_shape = _obtain_input_shape(input_shape,
                                      default_size=224,
                                      min_size=48,
                                      data_format=K.image_data_format(),
                                      require_flatten=include_top)

    if input_tensor is None:
        img_input = Input(shape=input_shape)
    else:
        if not K.is_keras_tensor(input_tensor):
            img_input = Input(tensor=input_tensor, shape=input_shape)
        else:
            img_input = input_tensor
    # Block 1
    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)
    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)

    # Block 2
    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)

    # Block 3
    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)

    # Block 4
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)

    # Block 5
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)

    if include_top:
        # Classification block
        x = Flatten(name='flatten')(x)
        x = Dense(4096, activation='relu', name='fc1')(x)
        x = Dense(4096, activation='relu', name='fc2')(x)
        x = Dense(classes, activation='softmax', name='predictions')(x)
    else:
        if pooling == 'avg':
            x = GlobalAveragePooling2D()(x)
        elif pooling == 'max':
            x = GlobalMaxPooling2D()(x)

    # Ensure that the model takes into account
    # any potential predecessors of `input_tensor`.
    if input_tensor is not None:
        inputs = get_source_inputs(input_tensor)
    else:
        inputs = img_input
    # Create model.
    model = Model(inputs, x, name='vgg16')

    # load weights
    if weights == 'imagenet':
        if include_top:
            weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels.h5',
                                    WEIGHTS_PATH,
                                   )
        else:
            weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
                                    WEIGHTS_PATH_NO_TOP,
                                    cache_subdir='models')
        model.load_weights(weights_path)
        if K.backend() == 'theano':
            layer_utils.convert_all_kernels_in_model(model)

        if K.image_data_format() == 'channels_first':
            if include_top:
                maxpool = model.get_layer(name='block5_pool')
                shape = maxpool.output_shape[1:]
                dense = model.get_layer(name='fc1')
                layer_utils.convert_dense_weights_data_format(dense, shape, 'channels_first')

            if K.backend() == 'tensorflow':
                warnings.warn('You are using the TensorFlow backend, yet you '
                              'are using the Theano '
                              'image data format convention '
                              '(`image_data_format="channels_first"`). '
                              'For best performance, set '
                              '`image_data_format="channels_last"` in '
                              'your Keras config '
                              'at ~/.keras/keras.json.')
    model.layers.pop() # Get rid of the classification layer
    model.outputs = [model.layers[-1].output]
    model.layers[-1].outbound_nodes = [ ]
    return model```

</code></pre>

<p>I am getting the following error on the second last line of the code:</p>

<pre><code>File "/home/natsu/Final_code/vgg16.py", line 200, in VGG16

    model.layers[-1].outbound_nodes = []

  File "/home/natsu/anaconda3/envs/py-env/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py", line 1639, in __setattr__
    super(Layer, self).__setattr__(name, value)

AttributeError: can't set attribute```

Body:
I was able to execute your code successfully in tensorflow version 1.15 without any modifications.

I was able to execute your code successfully in tensorflow version 2.2.0 with minor modifications shown below -

Modify,

from tensorflow.python.keras.utils import layer_utils , get_source_inputs

to

from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.keras.utils.layer_utils import get_source_inputs

Can you please upgrade the tensorflow version and check if the error is fixed.

Hope this answers your question. Happy Learning.


问:
How to get 'line-dasharray' value from geojson for mapbox GL
I am trying to get the value through ['get', 'line-dasharray'] but getting an error

Here is my code

```<code>var data = {
          'type': 'FeatureCollection',
          'features': [
 {
              'type': 'Feature',
              'geometry': {
                'type': 'LineString',
                'coordinates': []
              },
              'properties': {
                'route_id': 300,
                'route_url': 'http://test.com/file.gpx',
                'line-color': '#426d7e',
                'line-width':     3,
                'line-opacity':   1,
                'line-dasharray': [5, 2]
              },
            },
]
    }

// some code

              map.addSource('locations-rote', {
                type: 'geojson',
                data: data,
                generateId: true
              });

map.addLayer({
                  'id': 'route-coordinates',
                  'type': 'line',
                  'source': 'locations-rote',
                  'layout': {
                    'line-join': 'round',
                    'line-cap': 'round'
                  },
                  'paint': {
                    'line-color': ['get', 'line-color'],
                    'line-width': ['get', 'line-width'],
                    'line-opacity': ['get', 'line-opacity'],
                    'line-dasharray': ['get', 'line-dasharray']
                  }
                });

</code>```

I try to use an array expression - https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#types-array but also get an error. Tell me how to solve the problem.

答:
Although you didn't specify what the error is that you are getting, it is likely the case that you are seeing something similar to:

```<code>Error: layers.route-coordinates.paint.line-dasharray: data expressions not supported
</code>```

As indicated in the SDK support for the line-dasharray documentation here, this is because data-driven styling (i.e. using an expression to determine values for the property with information derived from your source data) is not yet supported on GL JS for the line-dasharray property.

If you'd like to style the line dashes differently based on different properties, you could instead create a few different layers referencing this source data by applying filters.

Body:
I am trying to get the value through ['get', 'line-dasharray'] but getting an error

Here is my code

var data = {
          'type': 'FeatureCollection',
          'features': [
 {
              'type': 'Feature',
              'geometry': {
                'type': 'LineString',
                'coordinates': []
              },
              'properties': {
                'route_id': 300,
                'route_url': 'http://test.com/file.gpx',
                'line-color': '#426d7e',
                'line-width':     3,
                'line-opacity':   1,
                'line-dasharray': [5, 2]
              },
            },
]
    }

// some code

              map.addSource('locations-rote', {
                type: 'geojson',
                data: data,
                generateId: true
              });

map.addLayer({
                  'id': 'route-coordinates',
                  'type': 'line',
                  'source': 'locations-rote',
                  'layout': {
                    'line-join': 'round',
                    'line-cap': 'round'
                  },
                  'paint': {
                    'line-color': ['get', 'line-color'],
                    'line-width': ['get', 'line-width'],
                    'line-opacity': ['get', 'line-opacity'],
                    'line-dasharray': ['get', 'line-dasharray']
                  }
                });

I try to use an array expression - https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#types-array but also get an error. Tell me how to solve the problem.

Body:
Although you didn't specify what the error is that you are getting, it is likely the case that you are seeing something similar to:

Error: layers.route-coordinates.paint.line-dasharray: data expressions not supported

As indicated in the SDK support for the line-dasharray documentation here, this is because data-driven styling (i.e. using an expression to determine values for the property with information derived from your source data) is not yet supported on GL JS for the line-dasharray property.

If you'd like to style the line dashes differently based on different properties, you could instead create a few different layers referencing this source data by applying filters.


问:
How do I change the color of radio buttons?
I mean, a radio button itself consists of a round shape and a dot at the center (when the button is selected). What I want to change is the color of both. Can this be done using CSS? </p>

答:
I builded another fork of @klewis' code sample to demonstrate some playing with pure css and gradients by using :before/:after pseudo elements and a hidden radio input button.

HTML:

```<code>sample radio buttons:
<div style="background:lightgrey;">
    <span class="radio-item">
        <input type="radio" id="ritema" name="ritem" class="true" value="ropt1" checked="checked">
        <label for="ritema">True</label>
    </span>

    <span class="radio-item">
        <input type="radio" id="ritemb" name="ritem" class="false" value="ropt2">
        <label for="ritemb">False</label>
    </span>
</div>
</code>```

:

CSS:

```<code>.radio-item input[type='radio'] {
    visibility: hidden;
    width: 20px;
    height: 20px;
    margin: 0 5px 0 5px;
    padding: 0;
}
    .radio-item input[type=radio]:before {
        position: relative;
        margin: 4px -25px -4px 0;
        display: inline-block;
        visibility: visible;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        border: 2px inset rgba(150,150,150,0.75);
        background: radial-gradient(ellipse at top left, rgb(255,255,255) 0%, rgb(250,250,250) 5%, rgb(230,230,230) 95%, rgb(225,225,225) 100%);
        content: "";
    }
        .radio-item input[type=radio]:checked:after {
            position: relative;
            top: 0;
            left: 9px;
            display: inline-block;
            visibility: visible;
            border-radius: 6px;
            width: 12px;
            height: 12px;
            background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            content: "";
        }
            .radio-item input[type=radio].true:checked:after {
                background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            }
            .radio-item input[type=radio].false:checked:after {
                background: radial-gradient(ellipse at top left, rgb(255,225,200) 0%, rgb(250,200,150) 5%, rgb(200,25,0) 95%, rgb(100,25,0) 100%);
            }
.radio-item label {
    display: inline-block;
    height: 25px;
    line-height: 25px;
    margin: 0;
    padding: 0;
}
</code>```

preview:
https://www.codeply.com/p/y47T4ylfib

Body:
I builded another fork of @klewis' code sample to demonstrate some playing with pure css and gradients by using :before/:after pseudo elements and a hidden radio input button.

HTML:

sample radio buttons:
<div style="background:lightgrey;">
    <span class="radio-item">
        <input type="radio" id="ritema" name="ritem" class="true" value="ropt1" checked="checked">
        <label for="ritema">True</label>
    </span>

    <span class="radio-item">
        <input type="radio" id="ritemb" name="ritem" class="false" value="ropt2">
        <label for="ritemb">False</label>
    </span>
</div>

:

CSS:

.radio-item input[type='radio'] {
    visibility: hidden;
    width: 20px;
    height: 20px;
    margin: 0 5px 0 5px;
    padding: 0;
}
    .radio-item input[type=radio]:before {
        position: relative;
        margin: 4px -25px -4px 0;
        display: inline-block;
        visibility: visible;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        border: 2px inset rgba(150,150,150,0.75);
        background: radial-gradient(ellipse at top left, rgb(255,255,255) 0%, rgb(250,250,250) 5%, rgb(230,230,230) 95%, rgb(225,225,225) 100%);
        content: "";
    }
        .radio-item input[type=radio]:checked:after {
            position: relative;
            top: 0;
            left: 9px;
            display: inline-block;
            visibility: visible;
            border-radius: 6px;
            width: 12px;
            height: 12px;
            background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            content: "";
        }
            .radio-item input[type=radio].true:checked:after {
                background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            }
            .radio-item input[type=radio].false:checked:after {
                background: radial-gradient(ellipse at top left, rgb(255,225,200) 0%, rgb(250,200,150) 5%, rgb(200,25,0) 95%, rgb(100,25,0) 100%);
            }
.radio-item label {
    display: inline-block;
    height: 25px;
    line-height: 25px;
    margin: 0;
    padding: 0;
}

preview:
https://www.codeply.com/p/y47T4ylfib


问:
Why does an exception from an FFI appear to occur, but results in an empty lefts list?
First, I don't have an easy to reproduce example on hand, as the code is calling out to a MATLAB engine, which requires a license. It may be possible to construct a similar example, just using C, though. I have the following snippet from a test:

  ei1 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
  putStrLn $ assert (isRight ei1) "  Can clearVar once"
  clearVar eng foopi
  ei2 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
  putStrLn $ assert (isLeft ei2) $
    " Can't clearVar twice: " <> (show $ lefts [ei2])
  putStrLn "  Finished testClearVar"
```

<p>This results in the output:</p>

```  Can clearVar once
Error using save
Variable 'foopi' not found.

 Can't clearVar twice: []
  Finished testClearVar
```

<p>The confusing bit is this expression, since the assertion appears to succeed (meaning that <code>ei2</code> is a <code>Left</code> value, but when calling <code>lefts [ei2]</code>, no Left values are found):</p>

<pre class="lang-hs prettyprint-override"><code>  putStrLn $ assert (isLeft ei2) $
    " Can't clearVar twice: " <> (show $ lefts [ei2])
</code>```

答:
If you look closely at documentation of assert you will find:

Assertions can normally be turned on or off with a compiler flag (for GHC, assertions are normally on unless optimisation is turned on with -O or the -fignore-asserts option is given). When assertions are turned off, the first argument to assert is ignored, and the second argument is returned as the result.

I assume this is a regular package you are working on and not just a file you are compiling manually with ghc. By default cabal will compile a project with -O, which means your asserts are simply ignored. What you need is either -O0 or -fno-ignore-asserts flag added. But what I would recommend is just don't rely on assert at all.

Body:
First, I don't have an easy to reproduce example on hand, as the code is calling out to a MATLAB engine, which requires a license. It may be possible to construct a similar example, just using C, though. I have the following snippet from a test:

  ei1 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
  putStrLn $ assert (isRight ei1) "  Can clearVar once"
  clearVar eng foopi
  ei2 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
  putStrLn $ assert (isLeft ei2) $
    " Can't clearVar twice: " <> (show $ lefts [ei2])
  putStrLn "  Finished testClearVar"

This results in the output:

  Can clearVar once
Error using save
Variable 'foopi' not found.

 Can't clearVar twice: []
  Finished testClearVar

The confusing bit is this expression, since the assertion appears to succeed (meaning that ei2 is a Left value, but when calling lefts [ei2], no Left values are found):

  putStrLn $ assert (isLeft ei2) $
    " Can't clearVar twice: " <> (show $ lefts [ei2])


问:
How to fix "Invalid beam file or no abstract code" error when debugging in Erlang/OTP?
I'm trying to simply use the debugger, however any method given in the docs causes Monitor > Module > Interpret > *.beam to return an error: ** Invalid beam file or no abstract code: "/path/z12.beam".

The methods to generate debug info I tried are:

Linux shell erlc +debug_info z12.erl

Erlang shell  > c(z12, [debug_info]).

Directly in the file compile:file(z12, [debug_info]).

However none of them seems to work. Is there a way to fix this?

答: Instead of selecting .beam file try with .erl file it would work. </p>