问:
TypeError: 'in <string>' requires string as left operand, not method PYTHON
When trying to run my code, I am presented with a TypeError.
It states: TypeError:'in'requires string as left operand, not method.

I am not sure what this means exactly, or how to fix it.

The code the error is created in is:

```<code>from tkinter import *
from tkinter import messagebox

def saveCustomer() :

    ClientID = ClientIDVar.get()
    ClientID = ClientID.ljust(50)
    Surname = SurnameVar.get()
    Surname = Surname.ljust(50)
    Forename = ForenameVar.get()
    Forename = Forename.ljust(50)
    Age = AgeVar.get()
    Age = Age.ljust(50)
    Gender = GenderVar.get()
    Gender = Gender.ljust(50)

    #lengthcheck
    ClientID = ClientIDVar.get()
    if len(ClientID) > 5 :
        messagebox.showerror("Error","Too many characters in ClientID")
        return
    Surname = SurnameVar.get()
    if len(Surname) > 20 :
        messagebox.showerror("Error","Too many characters in Surname")
        return
    Forename = ForenameVar.get()
    if len(Forename) > 15 :
        messagebox.showerror("Error","Too many characters in Forename")
        return
    Age = AgeVar.get()
    if len(Age) > 2 :
        messagebox.showerror("Error","Too many characters in Age")
        return
    Gender = GenderVar.get()
    if len(Gender) > 2 :
        messagebox.showerror("Error","Too many characters in Gender")
        return
    #presencecheck
    if ClientID == "":
        messagebox.showerror("Error","Please enter characters into ClientID")
        return
    if Surname == "":
        messagebox.showerror("Error","Please enter characters into Surname")
        return
    if Forename == "":
        messagebox.showerror("Error","Please enter characters into Forename")
        return
    if Age == "":
       messagebox.showerror("Error","Please enter characters into Age")
        return
    if Gender == "":
        messagebox.showerror("Error","Please enter characters into Gender")
        return
    #rangecheck
    if (int(Age) < 18) or (int(Age) > 99):
        messagebox.showerror("Error","Please enter an age between 18 and 99")
        return
    #typecheck
    if not ClientID.isnumeric():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into ClientID")
        return
    if not Surname.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Surname")
        return
    if not Forename.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Forename")
        return
    if not Age.isnumeric():
        messagebox.showerror("Error","Please enter numerical values into Age")
        return
    if not Gender.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into Gender")
        return

    #open the file to append - if it's not there it'll be created
    fileObject = open("Customers.txt","a")
    # write to the file with a newline character at the end
    fileObject.write(ClientID + Surname + Forename + Age + Gender + "\n")
    fileObject.close()

    return

def searchCustomer() :
    Found = "N"
    ClientID = ClientIDVar.get
    # try opening the file for reading
    try:
        fileObject=open("Customers.txt","r")

    # if it's not there then say
    except IOError:
        messagebox.showerror("Error","No file to read")

    # if we did open it then let's carry on!
    else:
        while True:

            recordVar=fileObject.readline()
            # Python keeps reading till EOF then returns a blank
            if recordVar=="":
                fileObject.close()
                break

            if ClientID in recordVar[0:50] and not ClientID=="" :
                Found = "T"
                messagebox.showinfo("Information",str(RecordVar))
                break

    if Found == "F":
        messagebox.showerror("Error","No Customer found.")
    return

def makeWindow():
    #declared my globals here as this is the 1st routine called
    # the other routines have to be in front of this one as they get called by it
    # and the parser would get upset if they weren't there

    global ClientIDVar, SurnameVar, ForenameVar, AgeVar, GenderVar

    #here's my window
    win = Tk()
    win.wm_title("FitnessCentre")
    #split into two sections then further split into a grid
    frame1=Frame(win)
    frame1.pack()

    Label(frame1, text="Fitness Leisure Centre", font=("Helvetica 12             bold")).grid(row=0, column=0)

    Label(frame1, text="ClientID").grid(row=1, column=0, sticky=W)
    ClientIDVar=StringVar()
    title= Entry(frame1, textvariable=ClientIDVar)
    title.grid(row=1,column=1,sticky=W)

    Label(frame1, text="Surname").grid(row=2, column=0, sticky=W)
    SurnameVar=StringVar()
    genre= Entry(frame1, textvariable=SurnameVar)
    genre.grid(row=2,column=1,sticky=W)

    Label(frame1, text="Forename").grid(row=3, column=0, sticky=W)
    ForenameVar=StringVar()
    director= Entry(frame1, textvariable=ForenameVar)
    director.grid(row=3,column=1,sticky=W)

    Label(frame1, text="Age").grid(row=4, column=0, sticky=W)
    AgeVar=StringVar()
    leadactor= Entry(frame1, textvariable=AgeVar)
    leadactor.grid(row=4,column=1,sticky=W)

    Label(frame1, text="Gender").grid(row=5, column=0, sticky=W)
    GenderVar=StringVar()
    duration= Entry(frame1, textvariable=GenderVar)
    duration.grid(row=5,column=1,sticky=W)

    frame2 = Frame(win)
    frame2.pack()

    # build my buttons in the other frame then pack them side by side
    b1= Button(frame2, text=" Save ", command=saveCustomer)
    b2= Button(frame2, text=" Search ", command=searchCustomer)
    b1.pack(side=LEFT); b2.pack(side=LEFT)

    return win

#main program!
win = makeWindow()
win.mainloop()
</code>```

The complete error message I received was:

```<code>Exception in Tkinter callback
Traceback (most recent call last):

if ClientID in recordVar[0:50] and not ClientID=="" :
TypeError: 'in <string>' requires string as left operand, not method
</code>```

答:
You can't use an method to test an in comparison, you have to compare with a string:

```<code>if ClientID in recordVar[0:50] and not ClientID=="" :
</code>```

The error that you get are clearly explaining this to you:

```<code>TypeError. It states: TypeError:'in'requires string as left operand, not method.
</code>```

Body:
When trying to run my code, I am presented with a TypeError.
It states: TypeError:'in'requires string as left operand, not method.

I am not sure what this means exactly, or how to fix it.

The code the error is created in is:

from tkinter import *
from tkinter import messagebox

def saveCustomer() :

    ClientID = ClientIDVar.get()
    ClientID = ClientID.ljust(50)
    Surname = SurnameVar.get()
    Surname = Surname.ljust(50)
    Forename = ForenameVar.get()
    Forename = Forename.ljust(50)
    Age = AgeVar.get()
    Age = Age.ljust(50)
    Gender = GenderVar.get()
    Gender = Gender.ljust(50)

    #lengthcheck
    ClientID = ClientIDVar.get()
    if len(ClientID) > 5 :
        messagebox.showerror("Error","Too many characters in ClientID")
        return
    Surname = SurnameVar.get()
    if len(Surname) > 20 :
        messagebox.showerror("Error","Too many characters in Surname")
        return
    Forename = ForenameVar.get()
    if len(Forename) > 15 :
        messagebox.showerror("Error","Too many characters in Forename")
        return
    Age = AgeVar.get()
    if len(Age) > 2 :
        messagebox.showerror("Error","Too many characters in Age")
        return
    Gender = GenderVar.get()
    if len(Gender) > 2 :
        messagebox.showerror("Error","Too many characters in Gender")
        return
    #presencecheck
    if ClientID == "":
        messagebox.showerror("Error","Please enter characters into ClientID")
        return
    if Surname == "":
        messagebox.showerror("Error","Please enter characters into Surname")
        return
    if Forename == "":
        messagebox.showerror("Error","Please enter characters into Forename")
        return
    if Age == "":
       messagebox.showerror("Error","Please enter characters into Age")
        return
    if Gender == "":
        messagebox.showerror("Error","Please enter characters into Gender")
        return
    #rangecheck
    if (int(Age) < 18) or (int(Age) > 99):
        messagebox.showerror("Error","Please enter an age between 18 and 99")
        return
    #typecheck
    if not ClientID.isnumeric():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into ClientID")
        return
    if not Surname.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Surname")
        return
    if not Forename.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Forename")
        return
    if not Age.isnumeric():
        messagebox.showerror("Error","Please enter numerical values into Age")
        return
    if not Gender.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into Gender")
        return

    #open the file to append - if it's not there it'll be created
    fileObject = open("Customers.txt","a")
    # write to the file with a newline character at the end
    fileObject.write(ClientID + Surname + Forename + Age + Gender + "\n")
    fileObject.close()

    return

def searchCustomer() :
    Found = "N"
    ClientID = ClientIDVar.get
    # try opening the file for reading
    try:
        fileObject=open("Customers.txt","r")

    # if it's not there then say
    except IOError:
        messagebox.showerror("Error","No file to read")

    # if we did open it then let's carry on!
    else:
        while True:

            recordVar=fileObject.readline()
            # Python keeps reading till EOF then returns a blank
            if recordVar=="":
                fileObject.close()
                break

            if ClientID in recordVar[0:50] and not ClientID=="" :
                Found = "T"
                messagebox.showinfo("Information",str(RecordVar))
                break

    if Found == "F":
        messagebox.showerror("Error","No Customer found.")
    return

def makeWindow():
    #declared my globals here as this is the 1st routine called
    # the other routines have to be in front of this one as they get called by it
    # and the parser would get upset if they weren't there

    global ClientIDVar, SurnameVar, ForenameVar, AgeVar, GenderVar

    #here's my window
    win = Tk()
    win.wm_title("FitnessCentre")
    #split into two sections then further split into a grid
    frame1=Frame(win)
    frame1.pack()

    Label(frame1, text="Fitness Leisure Centre", font=("Helvetica 12             bold")).grid(row=0, column=0)

    Label(frame1, text="ClientID").grid(row=1, column=0, sticky=W)
    ClientIDVar=StringVar()
    title= Entry(frame1, textvariable=ClientIDVar)
    title.grid(row=1,column=1,sticky=W)

    Label(frame1, text="Surname").grid(row=2, column=0, sticky=W)
    SurnameVar=StringVar()
    genre= Entry(frame1, textvariable=SurnameVar)
    genre.grid(row=2,column=1,sticky=W)

    Label(frame1, text="Forename").grid(row=3, column=0, sticky=W)
    ForenameVar=StringVar()
    director= Entry(frame1, textvariable=ForenameVar)
    director.grid(row=3,column=1,sticky=W)

    Label(frame1, text="Age").grid(row=4, column=0, sticky=W)
    AgeVar=StringVar()
    leadactor= Entry(frame1, textvariable=AgeVar)
    leadactor.grid(row=4,column=1,sticky=W)

    Label(frame1, text="Gender").grid(row=5, column=0, sticky=W)
    GenderVar=StringVar()
    duration= Entry(frame1, textvariable=GenderVar)
    duration.grid(row=5,column=1,sticky=W)

    frame2 = Frame(win)
    frame2.pack()

    # build my buttons in the other frame then pack them side by side
    b1= Button(frame2, text=" Save ", command=saveCustomer)
    b2= Button(frame2, text=" Search ", command=searchCustomer)
    b1.pack(side=LEFT); b2.pack(side=LEFT)

    return win

#main program!
win = makeWindow()
win.mainloop()

The complete error message I received was:

Exception in Tkinter callback
Traceback (most recent call last):

if ClientID in recordVar[0:50] and not ClientID=="" :
TypeError: 'in <string>' requires string as left operand, not method

Body:
You can't use an method to test an in comparison, you have to compare with a string:

if ClientID in recordVar[0:50] and not ClientID=="" :

The error that you get are clearly explaining this to you:

TypeError. It states: TypeError:'in'requires string as left operand, not method.


来源: stackexchange

问:
Gradle: Changing configuration of external dependency
We're in the situation where we update commons-collections from version 3 to version 4. As they've changed the group id to commons-collections4 we will end up having 2 versions of commons-collection in the classpath. The version 3 and version 4.
For our development the version 4 should be used. The version 3 will come in through external dependencies so if we have like:

```<code>compile ("org.hibernate:hibernate-entitymanager:3.5.6-Final")
</code>```

the version 3, which will come in through hibernate-entitymanager, will also be available at compile time. So the developers could use it.

Is there a way to say "commons-collections 3 should now be considered as runtime dependency when it comes through hibernate-entitymanager"?

We're using Gradle 3.5.

答:
Not sure there is a proper way exist to achieve this, however what if you force all version of commons3 to be replaced with commons4 at compile configuration, and additionally define a runtime only annotation?

```<code>configurations.compile {
    resolutionStrategy.force 'commons4',
}

dependencies {
    runtime('commons3')
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We're in the situation where we update commons-collections from version 3 to version 4. As they've changed the group id to commons-collections4 we will end up having 2 versions of commons-collection in the classpath. The version 3 and version 4.
For our development the version 4 should be used. The version 3 will come in through external dependencies so if we have like:

compile ("org.hibernate:hibernate-entitymanager:3.5.6-Final")

the version 3, which will come in through hibernate-entitymanager, will also be available at compile time. So the developers could use it.

Is there a way to say "commons-collections 3 should now be considered as runtime dependency when it comes through hibernate-entitymanager"?

We're using Gradle 3.5.

Body:
Not sure there is a proper way exist to achieve this, however what if you force all version of commons3 to be replaced with commons4 at compile configuration, and additionally define a runtime only annotation?

configurations.compile {
    resolutionStrategy.force 'commons4',
}

dependencies {
    runtime('commons3')
}


问:
laravel displaying path which matches business_id
I am allowing business to upload images. Everything is saved into database and the only thing I need to do is retrieve  images that match business_id:

So now I need to browse throught business_id and if it's matching, output all images.

```<code>function displayBusiness($id) {
    $business = Business::find($id);
    $address = Address::find($id);
    $session = session()->put('key', $id);
    $session = session()->get('key');
    $retrieve_gallery = Gallery::where('business_id', '=' ,$session)->firstOrFail();
    return view('displayBusiness', compact('business', 'address', 'gallery'));
}
</code>```

In session variable I am storing a business id from business table. I want to match that session variable with each business_id in database and return compact 'gallery' so I can use it's path in view:

```<code><img class="images" src="{{ asset($gallery->path) }}" />
</code>```

However I get $gallery is not defined. How can that be fixed?

答:
I think it's because you didn't create a $gallery variable before you call it on compact().

So when you do

```<code>compact('business', 'address', 'gallery')
</code>```

It's like doing

```<code>['business' => $business, 'address' => $address];
</code>```

Note that compact() will not issue a warning if a value is undefined (see the docs for compact function, first user contribution note :http://php.net/manual/fr/function.compact.php#101775).

As a result, $gallery is indeed undefined in your exemple.

So changing $retrieve_gallery to $gallery should solve that particular problem you mention.

Body:
I am allowing business to upload images. Everything is saved into database and the only thing I need to do is retrieve  images that match business_id:

So now I need to browse throught business_id and if it's matching, output all images.

function displayBusiness($id) {
    $business = Business::find($id);
    $address = Address::find($id);
    $session = session()->put('key', $id);
    $session = session()->get('key');
    $retrieve_gallery = Gallery::where('business_id', '=' ,$session)->firstOrFail();
    return view('displayBusiness', compact('business', 'address', 'gallery'));
}

In session variable I am storing a business id from business table. I want to match that session variable with each business_id in database and return compact 'gallery' so I can use it's path in view:

path) }}" />

However I get $gallery is not defined. How can that be fixed?

Body:
I think it's because you didn't create a $gallery variable before you call it on compact().

So when you do

compact('business', 'address', 'gallery')

It's like doing

['business' => $business, 'address' => $address];

Note that compact() will not issue a warning if a value is undefined (see the docs for compact function, first user contribution note :http://php.net/manual/fr/function.compact.php#101775).

As a result, $gallery is indeed undefined in your exemple.

So changing $retrieve_gallery to $gallery should solve that particular problem you mention.


问:
Use INDEX MATCH to find greater than/equal to value
I've been searching online and in Excel Help but cannot find whether this is possible.

Given a list of numbers, values and a search term, I need to find the value whereby the value is greater than or equal to the search term.  See the example:

Excel returns Red but it should return Orange because 15 is greater than 10.

Other desired result examples would be:

5 = Red (or N/A)

25 = Yellow

63 = Violet

15434 = Violet (or N/A)

I realise that if I sort the list in descending order and use -1 for the MATCH [match_type] argument, then it works okay, but, the list is over 1,000 rows and is far easier to read in ascending order.

答:
Another method of doing this is to place the numbers and colours into a table, order numbers by highest to smallest and use the formula below:</p>

```<code>=INDEX(B4:B10,MATCH(B1,A4:A10,-1))
</code>```

Body:
Another method of doing this is to place the numbers and colours into a table, order numbers by highest to smallest and use the formula below:

=INDEX(B4:B10,MATCH(B1,A4:A10,-1))


问:
Importing json that was serialized by JSON is failing
So I have an object with some fields...

```<code>protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;
</code>```

Which gets serialized to JSON like this:

```<code>public void serialize(){
    Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
    String json = gson.toJson(this);

    try {
        FileWriter writer = new FileWriter(this.relativePathAndFileName);
        writer.write (json);
        writer.close();
    } catch (IOException e) {
        logger.error("Error while trying to write myAlert to json: ", e);
    }
}
</code>```

Later when I need to read in this json file, I try to do so like this:

```<code>try {
        for (File f : alertConfigFiles) {
            Gson gson = new Gson();
            JsonReader reader = new JsonReader(new FileReader(f));
            Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> myMap = gson.fromJson(reader, type);
            Alert tempAlert = new Alert(myMap);
            myAlerts.add(tempAlert);
            logger.debug("Imported: " + f.toString());
        }
</code>```

The error that I'm getting is:

```<code>Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.
</code>```

The JSON inside the file is something to the effect of:

```<code> {
 "name": "Logs Per Host - past 24 hours",
 "relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
 "next_Run": "2017-06-07T22:24:56.682-04:00",
 "hosts": [
    "app-12c",
    "app1-18",
    "wp-01",
    "app-02",
    "wp-02",
    "cent-04",
    "app-06",
    "app-05"
  ]
  }
</code>```

It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.

Can anyone offer some advice on how to get my import working without issues?

答:
try to keep it simple. Using maps and so on, is a way to have issues.
Here is a working code to deserialise / serialise :

```<code>package com.rizze.beans.labs.sof;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.google.gson.Gson;

public class SOFGson {

    public String json = "{  \"name\": \"Logs Per Host - past 24 hours\", \"relativePathAndFileName\": \"./Elk-Reporting/Alerts/logs_per_host24h.json\", \"next_Run\": \"2017-06-07T22:24:56.682-04:00\", \"hosts\": [ \"bos-qa-app-12c\", \"bos-qa-app1-18\", \"bos-qa-wp-01\", \"bos-lt-app-02\", \"bos-qa-wp-02\", \"bos-dev-cent-04.americanwell.com\", \"bos-qa-app-06\", \"bos-qa-app-05\" ]}";

    public class MyObj{
        protected String name;
        protected String relativePathAndFileName;
        protected String next_Run;
        protected String[] hosts;
    }

    @Test
    public void test() {

        Gson gson = new Gson();
        MyObj obj = gson.fromJson(json, MyObj.class);
        assertTrue(obj!=null);
        assertTrue(obj.hosts.length==8);
        System.out.println(gson.toJson(obj));

    }

}
</code>```

here is the class in gist : https://gist.github.com/jeorfevre/7b32a96d4ddc4af68e40bf95f63f2c26

Body:
So I have an object with some fields...

protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;

Which gets serialized to JSON like this:

public void serialize(){
    Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
    String json = gson.toJson(this);

    try {
        FileWriter writer = new FileWriter(this.relativePathAndFileName);
        writer.write (json);
        writer.close();
    } catch (IOException e) {
        logger.error("Error while trying to write myAlert to json: ", e);
    }
}

Later when I need to read in this json file, I try to do so like this:

try {
        for (File f : alertConfigFiles) {
            Gson gson = new Gson();
            JsonReader reader = new JsonReader(new FileReader(f));
            Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> myMap = gson.fromJson(reader, type);
            Alert tempAlert = new Alert(myMap);
            myAlerts.add(tempAlert);
            logger.debug("Imported: " + f.toString());
        }

The error that I'm getting is:

Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.

The JSON inside the file is something to the effect of:

 {
 "name": "Logs Per Host - past 24 hours",
 "relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
 "next_Run": "2017-06-07T22:24:56.682-04:00",
 "hosts": [
    "app-12c",
    "app1-18",
    "wp-01",
    "app-02",
    "wp-02",
    "cent-04",
    "app-06",
    "app-05"
  ]
  }

It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.

Can anyone offer some advice on how to get my import working without issues?

Body:
try to keep it simple. Using maps and so on, is a way to have issues.
Here is a working code to deserialise / serialise :

package com.rizze.beans.labs.sof;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.google.gson.Gson;

public class SOFGson {

    public String json = "{  \"name\": \"Logs Per Host - past 24 hours\", \"relativePathAndFileName\": \"./Elk-Reporting/Alerts/logs_per_host24h.json\", \"next_Run\": \"2017-06-07T22:24:56.682-04:00\", \"hosts\": [ \"bos-qa-app-12c\", \"bos-qa-app1-18\", \"bos-qa-wp-01\", \"bos-lt-app-02\", \"bos-qa-wp-02\", \"bos-dev-cent-04.americanwell.com\", \"bos-qa-app-06\", \"bos-qa-app-05\" ]}";

    public class MyObj{
        protected String name;
        protected String relativePathAndFileName;
        protected String next_Run;
        protected String[] hosts;
    }

    @Test
    public void test() {

        Gson gson = new Gson();
        MyObj obj = gson.fromJson(json, MyObj.class);
        assertTrue(obj!=null);
        assertTrue(obj.hosts.length==8);
        System.out.println(gson.toJson(obj));

    }

}

here is the class in gist : https://gist.github.com/jeorfevre/7b32a96d4ddc4af68e40bf95f63f2c26


问:
Why is not allowing spread operator in React Native component property assignment a performance optimization?
In a React Native component if the spread operator is used in the props assignment, an error, "In this environment the target of assign MUST be an object. This error is a performance optimization and not spec compliant." is thrown.

For example, in render function

```<code>const { style } = props;
  return (
    <View style={{borderWidth: 1, ...style}}>
</code>```

gives

meanwhile

```<code>const { style } = props;
  return (
    <View style={{borderWidth: 1, paddingLeft: 1}}>
</code>```

works. Why does the spread syntax affect performance?

答:
According to the accepted answer on this question.
You cannot use ... in a style definition because StyleSheet.create() doesn't return a regular javascript object.

However, you can use ... during the initialization of a StyleSheet, i.e.

```<code>const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject,
        top:null,
    }
})
</code>```

To solve your issue, you should use flatten:

```<code>const { style } = props;
StyleSheet.flatten([style, {borderWidth: 1}])
</code>```

Body:
In a React Native component if the spread operator is used in the props assignment, an error, "In this environment the target of assign MUST be an object. This error is a performance optimization and not spec compliant." is thrown.

For example, in render function

const { style } = props;
  return (
    <View style={{borderWidth: 1, ...style}}>

gives

meanwhile

const { style } = props;
  return (
    <View style={{borderWidth: 1, paddingLeft: 1}}>

works. Why does the spread syntax affect performance?

Body:
According to the accepted answer on this question.
You cannot use ... in a style definition because StyleSheet.create() doesn't return a regular javascript object.

However, you can use ... during the initialization of a StyleSheet, i.e.

const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject,
        top:null,
    }
})

To solve your issue, you should use flatten:

const { style } = props;
StyleSheet.flatten([style, {borderWidth: 1}])


问:
calling a web method from clientside using jquery ajax method - not calling method rather going into pageload
I click my edit button,it enters button click function in javascript.When ajax() is executed  the control goes to page load of WebForm rather than directly calling update() of webform which I'm mentioning as [ url: "WebForm1.aspx/update",] in ajax().Why not my update function is invoked ??
    I'm having master page for my webform and the button is an asp:control</p>

```<code>This is my javascript
$(document).ready(function () {

    $("input[id*='edit']").click(function () {
        var userdata = {};
        userdata["Name"]="Saran";
        var DTO = { 'userdata' : userdata};
        $.ajax({
            type: "POST",
            contenttype: "application/json; charset=utf-8",
            url: "WebForm1.aspx/update",
            data: JSON.stringify(DTO),
            datatype: "json",
            success: function (result) {
                //do something
                alert("SUCCESS = " + result);
                console.log(result);
            },

            error: function (xmlhttprequest, textstatus, errorthrown) {
                alert(" conection to the server failed ");
                console.log("error: " + errorthrown);
            }
        });//end of $.ajax()

        return false;
    });//eof button click
});

and my webform looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Payoda.Assignments.BusinessLayer;

namespace Payoda.Assignments.LoginApplication
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        [WebMethod]
        public static string update(string userdata)
        {
            return "success";
        }
    }
}

my aspx page looks like this

<%@ Page Title="" Language="C#" MasterPageFile="~/MyMasterPage.Master" AutoEventWireup="true" CodeBehind="TrialPage.aspx.cs" Inherits="Application.TrialPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/TrialScript.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Contents" runat="server">
    <asp:Button ID="editLink" runat="server" Text="MY BUTTON" />
</asp:Content>
</code>```

答: You should use a regular html input instead of asp:button</p>

Body:
I click my edit button,it enters button click function in javascript.When ajax() is executed  the control goes to page load of WebForm rather than directly calling update() of webform which I'm mentioning as [ url: "WebForm1.aspx/update",] in ajax().Why not my update function is invoked ??
    I'm having master page for my webform and the button is an asp:control

This is my javascript
$(document).ready(function () {

    $("input[id*='edit']").click(function () {
        var userdata = {};
        userdata["Name"]="Saran";
        var DTO = { 'userdata' : userdata};
        $.ajax({
            type: "POST",
            contenttype: "application/json; charset=utf-8",
            url: "WebForm1.aspx/update",
            data: JSON.stringify(DTO),
            datatype: "json",
            success: function (result) {
                //do something
                alert("SUCCESS = " + result);
                console.log(result);
            },

            error: function (xmlhttprequest, textstatus, errorthrown) {
                alert(" conection to the server failed ");
                console.log("error: " + errorthrown);
            }
        });//end of $.ajax()

        return false;
    });//eof button click
});

and my webform looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Payoda.Assignments.BusinessLayer;

namespace Payoda.Assignments.LoginApplication
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        [WebMethod]
        public static string update(string userdata)
        {
            return "success";
        }
    }
}

my aspx page looks like this

<%@ Page Title="" Language="C#" MasterPageFile="~/MyMasterPage.Master" AutoEventWireup="true" CodeBehind="TrialPage.aspx.cs" Inherits="Application.TrialPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Contents" runat="server">
    <asp:Button ID="editLink" runat="server" Text="MY BUTTON" />
</asp:Content>


问:
TensorFlow random_shuffle_queue is closed and has insufficient elements
I'm reading batch of images by getting idea here from tfrecords(converted by this)

My images are cifar images, [32, 32, 3] and as you can see while reading and passing images the shapes are normal (batch_size=100)

the 2 most notable problems stated in the log, as far as I know is

Shape of 12228, which I don't know from where I get this. All my tensors are either in shape [32, 32, 3] or [None, 3072]

Running out of sample

Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

How can I solve this?

Logs:

```<code>1- image shape is  TensorShape([Dimension(3072)])
1.1- images batch shape is  TensorShape([Dimension(100), Dimension(3072)])
2- images shape is  TensorShape([Dimension(100), Dimension(3072)])

W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72abc89a0 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72ab9d080 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa7285e55a0 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72aadb080 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72ad499a0 Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
     [[Node: input/shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/shuffle_batch/n)]]
Traceback (most recent call last):
  File "/Users/HANEL/Documents/my_cifar_train.py", line 110, in <module>
    tf.app.run()
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 11, in run
    sys.exit(main(sys.argv))
  File "/Users/HANEL/my_cifar_train.py", line 107, in main
    train()
  File "/Users/HANEL/my_cifar_train.py", line 76, in train
    _, loss_value = sess.run([train_op, loss])
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 345, in run
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 419, in _do_run
    e.code)
tensorflow.python.framework.errors.OutOfRangeError: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
     [[Node: input/shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/shuffle_batch/n)]]
Caused by op u'input/shuffle_batch', defined at:
  File "/Users/HANEL/my_cifar_train.py", line 110, in <module>
    tf.app.run()
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 11, in run
    sys.exit(main(sys.argv))
  File "/Users/HANEL/my_cifar_train.py", line 107, in main
    train()
  File "/Users/HANEL/my_cifar_train.py", line 39, in train
    images, labels = my_input.inputs()
  File "/Users/HANEL/my_input.py", line 157, in inputs
    min_after_dequeue=200)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 453, in shuffle_batch
    return queue.dequeue_many(batch_size, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 245, in dequeue_many
    self._queue_ref, n, self._dtypes, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/gen_data_flow_ops.py", line 319, in _queue_dequeue_many
    timeout_ms=timeout_ms, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
    op_def=op_def)
  File "/Users
/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in __init__
    self._traceback =

_extract_stack()
</code>```

答:
You're likely processing the parsed TFRecord example wrong. E.g. trying to reshape a tensor to an incompatible size. You can debug using a tf_record_iterator to confirm the data you're reading is stored the way you think it is:</p>

```<code>import tensorflow as tf
import numpy as np

tfrecords_filename = '/path/to/some.tfrecord'
record_iterator = tf.python_io.tf_record_iterator(path=tfrecords_filename)

for string_record in record_iterator:
    # Parse the next example
    example = tf.train.Example()
    example.ParseFromString(string_record)

    # Get the features you stored (change to match your tfrecord writing code)
    height = int(example.features.feature['height']
                                 .int64_list
                                 .value[0])

    width = int(example.features.feature['width']
                                .int64_list
                                .value[0])

    img_string = (example.features.feature['image_raw']
                                  .bytes_list
                                  .value[0])
    # Convert to a numpy array (change dtype to the datatype you stored)
    img_1d = np.fromstring(img_string, dtype=np.float32)
    # Print the image shape; does it match your expectations?
    print(img_1d.shape)
</code>```

Body:
I'm reading batch of images by getting idea here from tfrecords(converted by this)

My images are cifar images, [32, 32, 3] and as you can see while reading and passing images the shapes are normal (batch_size=100)

the 2 most notable problems stated in the log, as far as I know is

Shape of 12228, which I don't know from where I get this. All my tensors are either in shape [32, 32, 3] or [None, 3072]

Running out of sample

Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

How can I solve this?

Logs:

1- image shape is  TensorShape([Dimension(3072)])
1.1- images batch shape is  TensorShape([Dimension(100), Dimension(3072)])
2- images shape is  TensorShape([Dimension(100), Dimension(3072)])

W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72abc89a0 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72ab9d080 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa7285e55a0 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72aadb080 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72ad499a0 Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
     [[Node: input/shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/shuffle_batch/n)]]
Traceback (most recent call last):
  File "/Users/HANEL/Documents/my_cifar_train.py", line 110, in <module>
    tf.app.run()
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 11, in run
    sys.exit(main(sys.argv))
  File "/Users/HANEL/my_cifar_train.py", line 107, in main
    train()
  File "/Users/HANEL/my_cifar_train.py", line 76, in train
    _, loss_value = sess.run([train_op, loss])
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 345, in run
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 419, in _do_run
    e.code)
tensorflow.python.framework.errors.OutOfRangeError: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
     [[Node: input/shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/shuffle_batch/n)]]
Caused by op u'input/shuffle_batch', defined at:
  File "/Users/HANEL/my_cifar_train.py", line 110, in <module>
    tf.app.run()
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 11, in run
    sys.exit(main(sys.argv))
  File "/Users/HANEL/my_cifar_train.py", line 107, in main
    train()
  File "/Users/HANEL/my_cifar_train.py", line 39, in train
    images, labels = my_input.inputs()
  File "/Users/HANEL/my_input.py", line 157, in inputs
    min_after_dequeue=200)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 453, in shuffle_batch
    return queue.dequeue_many(batch_size, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 245, in dequeue_many
    self._queue_ref, n, self._dtypes, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/gen_data_flow_ops.py", line 319, in _queue_dequeue_many
    timeout_ms=timeout_ms, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
    op_def=op_def)
  File "/Users
/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in __init__
    self._traceback =

_extract_stack()

Body:
You're likely processing the parsed TFRecord example wrong. E.g. trying to reshape a tensor to an incompatible size. You can debug using a tf_record_iterator to confirm the data you're reading is stored the way you think it is:

import tensorflow as tf
import numpy as np

tfrecords_filename = '/path/to/some.tfrecord'
record_iterator = tf.python_io.tf_record_iterator(path=tfrecords_filename)

for string_record in record_iterator:
    # Parse the next example
    example = tf.train.Example()
    example.ParseFromString(string_record)

    # Get the features you stored (change to match your tfrecord writing code)
    height = int(example.features.feature['height']
                                 .int64_list
                                 .value[0])

    width = int(example.features.feature['width']
                                .int64_list
                                .value[0])

    img_string = (example.features.feature['image_raw']
                                  .bytes_list
                                  .value[0])
    # Convert to a numpy array (change dtype to the datatype you stored)
    img_1d = np.fromstring(img_string, dtype=np.float32)
    # Print the image shape; does it match your expectations?
    print(img_1d.shape)


问:
Had only one public subnet to VPC, and added NAT gateway to that public subnet instance, but i'm not able access the instance using NAT ip address
I had only one public subnet to VPC,and added NAT gateway to that public subnet, but i'm not able access the instance using NAT ip address.

@1)I'm able to ping the instance, with public Ip address(added icmp to security group), but by using NAT elastic IP address i'm not able to ping.

@2)Does NAT is applicable for single public subnet or not.
    My goal is to translate the ip address attached to public subnet instance.

答:
Make sure you have:

Internet Gateway for your VPC (docs).

A public IPv4 for your instance.

NAT Gateway (docs) is used for services inside a private subnet (which is inside a VPC) to send requests from inside the subnet to internet. The source address being the Elastic IP.

Internet Gateway is used for all the VPC to establish a basic level of internet connectivity. It takes care of routing to your EC2 instances that have a public IP.


问:
How to backup a Web.config before Installing with VS MSI Installer
I am using a regular Visual Studio Setup Project to deploy my ASP.NET application. I need to handle the case of an existing web.config existing in the target directory. When one is found, it needs to be renamed before the install takes place. If this does not happen, the new web.config will not overwrite the old.

How can I get my custom action to rename the old web.config BEFORE the files being installed are copied?

So far I have tried by deriving from System.Configuration.Install.Installer and overriding the OnBeforeInstall, Install and Commit. It seems that all of these methods take place after the new files are copied into the target directory.

答: Do it in the Committing event. You said you tried to override 'Commit' but there is two commit events; Committing and Committed. The first occurs before the installers property commits its install, and the latter occurs after.</p>

OwnerDisplayName: Bob

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bbetances


问:
Is importing a file good in Python
I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function.

My question is that in terms of running time on a machine which technique would be better :- importing the complete file and running the function or copying the function as it is and run it from same package.

I know it won't matter in a large sense but I want to learn it in the sense that if we are making a large project is it better to import a complete file in Python or just add the function in the current namespace.....

答: If the two modules are unrelated except for that common function, you may wish to consider extracting that function (and maybe other things that are related to that function) into a third module.</p>

Title: Is importing a file good in Python


问:
String startswith a particular text
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

```<code>inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)
</code>```

答:
In pandas working with arrays, so need numpy.where with boolean mask created by str.contains with ^ for starts of string or use str.startswith:

```<code>inf["Engagements"] = np.where(inf["Tweet"].str.contains('^RT @'),
                              0,
                              inf["Favorite_Count"] + inf["Retweet_Count"])
</code>```

Sample:

```<code>inf["Engagements"] = np.where(inf["Tweet"].str.contains('^RT @'),
                              0,
                              inf["Favorite_Count"] + inf["Retweet_Count"])

print (inf)
   Favorite_Count  Retweet_Count     Tweet  Engagements
0               1              2  RT @ ddd            0
1               4              0        dd            4
2               5              7  dds RT @           12
</code>```

```<code>inf["Engagements"] = np.where(inf["Tweet"].str.startswith('RT @'),
                              0,
                              inf["Favorite_Count"] + inf["Retweet_Count"])

print (inf)
   Favorite_Count  Retweet_Count     Tweet  Engagements
0               1              2  RT @ ddd            0
1               4              0        dd            4
2               5              7  dds RT @           12
</code>```

Title: String startswith a particular text

Body:
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)

Body:
In pandas working with arrays, so need numpy.where with boolean mask created by str.contains with ^ for starts of string or use str.startswith:

inf["Engagements"] = np.where(inf["Tweet"].str.contains('^RT @'),
                              0,
                              inf["Favorite_Count"] + inf["Retweet_Count"])

Sample:

inf["Engagements"] = np.where(inf["Tweet"].str.contains('^RT @'),
                              0,
                              inf["Favorite_Count"] + inf["Retweet_Count"])

print (inf)
   Favorite_Count  Retweet_Count     Tweet  Engagements
0               1              2  RT @ ddd            0
1               4              0        dd            4
2               5              7  dds RT @           12

inf["Engagements"] = np.where(inf["Tweet"].str.startswith('RT @'),
                              0,
                              inf["Favorite_Count"] + inf["Retweet_Count"])

print (inf)
   Favorite_Count  Retweet_Count     Tweet  Engagements
0               1              2  RT @ ddd            0
1               4              0        dd            4
2               5              7  dds RT @           12


问:
Cubic Root of Pandas DataFrame
I understand how to take cubic root of both positive and negative numbers. But when trying to use apply-lambda method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be wrong with the code:

```<code>sample[columns]=sample[columns].apply(lambda x: (-1)*np.power(-x,1./3) if x<0 else np.power(x,1./3))
</code>```

答:
Try :</p>

```<code>sample[columns]=sample[columns]**(1/3)
</code>```

Title: Cubic Root of Pandas DataFrame

Body:
I understand how to take cubic root of both positive and negative numbers. But when trying to use apply-lambda method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be wrong with the code:

sample[columns]=sample[columns].apply(lambda x: (-1)*np.power(-x,1./3) if x<0 else np.power(x,1./3))

Body:
Try :

sample[columns]=sample[columns]**(1/3)


问:
Passing input text back to parent from component
I am using an auto expanding text input field (Link) and I am creating it as a component. My question is when the text is changed how do I pass the value of the data back to the parent? I want to be able to submit the input via the parent so I was thinking of storing the input value in the parents state.

Parent

Calling the child component by using <InputExpand />

```<code>render() {

    const { navigate } = this.props.navigation;

    console.log("Rendering");

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="MESSAGE DETAILS" backButton={true} showNewMessage={true} />
            </View>
            <View style={styles.contentWrapper}>
                <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow}
                        enableEmptySections={true}
                        style={styles.listWrapper}
                    />
            </View>
            <View style={styles.footerBar}>
                    <View style={styles.footerBtnContainer}></View>
                    <View style={styles.footerInputContainer}>
                        <InputExpand />
                    </View>
                    <View style={styles.footerBtnContainer}>
                        <Image source={require('../../images/icons/IconSend.png')} style={{width: 20, height: 20}}/>
                    </View>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }
</code>```

Component - (Child)

```<code>import React, { Component } from 'react'

const {
  TextInput,
  StyleSheet,
} = require('react-native');

export default class AutoExpandingTextInput extends React.Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={(event) => {
          this.setState({
            text: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height,
          });
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
        placeholder={"Type a message..."}
        placeholderTextColor={"#fff"}
      />
    );
  }
}

var styles = StyleSheet.create({
  default: {
    color: "#fff",
    fontSize: 10,
    fontFamily: "Avenir-Light",
  },
});
</code>```

答:
Yes, that is exactly what you should do. You create a handler in the parent state and pass it into the child component as a prop.

// parent component

// assuming a property inputText exists in the state
// and use arrow function to preserve the context of `this` to be of the parent class.
onChangeTextHandler = (e) => {
  this.setState({
    // get the value from TextInput onChangeText event
    inputText: e.value,
  })
}

render() {

    const { navigate } = this.props.navigation;

    console.log("Rendering");

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="MESSAGE DETAILS" backButton={true} showNewMessage={true} />
            </View>
            <View style={styles.contentWrapper}>
                <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow}
                        enableEmptySections={true}
                        style={styles.listWrapper}
                    />
            </View>
            <View style={styles.footerBar}>
                    <View style={styles.footerBtnContainer}></View>
                    <View style={styles.footerInputContainer}>
                        <InputExpand onChangeTextHandler= {this.onChangeTextHandler}/>
                    </View>
                    <View style={styles.footerBtnContainer}>
                        <Image source={require('../../images/icons/IconSend.png')} style={{width: 20, height: 20}}/>
                    </View>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }

// Child Component
import React, { Component } from 'react'

const {
  TextInput,
  StyleSheet,
} = require('react-native');

export default class AutoExpandingTextInput extends React.Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    const { onChangeTextHandler } = this.props;
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={(event) => {
          // set the state of parent component here...
          onChangeTextHandler(event.nativeEvent.text);
          this.setState({
            text: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height,
          });
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
        placeholder={"Type a message..."}
        placeholderTextColor={"#fff"}
      />
    );
  }
}

var styles = StyleSheet.create({
  default: {
    color: "#fff",
    fontSize: 10,
    fontFamily: "Avenir-Light",
  },
});
reactjs react-native```

Body:
I am using an auto expanding text input field (Link) and I am creating it as a component. My question is when the text is changed how do I pass the value of the data back to the parent? I want to be able to submit the input via the parent so I was thinking of storing the input value in the parents state.

Parent

Calling the child component by using <InputExpand />

render() {

    const { navigate } = this.props.navigation;

    console.log("Rendering");

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="MESSAGE DETAILS" backButton={true} showNewMessage={true} />
            </View>
            <View style={styles.contentWrapper}>
                <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow}
                        enableEmptySections={true}
                        style={styles.listWrapper}
                    />
            </View>
            <View style={styles.footerBar}>
                    <View style={styles.footerBtnContainer}></View>
                    <View style={styles.footerInputContainer}>
                        <InputExpand />
                    </View>
                    <View style={styles.footerBtnContainer}>
                        <Image source={require('../../images/icons/IconSend.png')} style={{width: 20, height: 20}}/>
                    </View>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }

Component - (Child)

import React, { Component } from 'react'

const {
  TextInput,
  StyleSheet,
} = require('react-native');

export default class AutoExpandingTextInput extends React.Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={(event) => {
          this.setState({
            text: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height,
          });
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
        placeholder={"Type a message..."}
        placeholderTextColor={"#fff"}
      />
    );
  }
}

var styles = StyleSheet.create({
  default: {
    color: "#fff",
    fontSize: 10,
    fontFamily: "Avenir-Light",
  },
});


问:
Angular2 - What folder for custom CSS / JS files?
I have to include a set of CSS and JS files in my angular2 application.

What is the correct folder in order to have them included when I do the build?

Should I have to put them inside SRC\Assets or under SRC\myFolder ?

Once defined it, how do I have to include them inside my app.component.html and how to configure <base href="/"> properly?

Thanks to support

答:
I am using webpack and in my application, I have placed them in src/assets folder now I can just use it like this

```<code><img class="photo-icon" src="/assets/img/user-default.png">
</code>```

You can make separate folders for javascript, images and stylesheets etc. in your assets folder and append in the path.

Body:
I am using webpack and in my application, I have placed them in src/assets folder now I can just use it like this

<img class="photo-icon" src="/assets/img/user-default.png">

You can make separate folders for javascript, images and stylesheets etc. in your assets folder and append in the path.


问:
Working on rails, i have text fields and text areas to receive text, but it shows the validation error "Topic cannot be empty"
After typing in topic and details in the appropriate text field and area, it still shows "validation error" "Topic cannot be empty". what is the problem? I cannot seem to figure it out.

```<code>This is the task partial
_task.html.erb:

 <li id="task-<%= task.id %>">
      <%= link_to gravatar_for(task.user, size: 50), task.user %>
      <span class="task"><%= link_to task.user.name, task.user %></span>
      <span class="topiclabel">Title:</span>
      <span class="topic"style=color:black> <%= task.topic %></span>
      <span class="detailslabel">Details: </span>
      <span class="detail"><%= task.detail %></span>
      <span class="timestamp">
        Posted <%= time_ago_in_words(task.created_at) %> ago.
      </span>
</li>

Schema:

ActiveRecord::Schema.define(version: 20170526194708) do

  create_table "stages", force: :cascade do |t|
    t.text     "topic"
    t.datetime "duration"
    t.text     "detail"
    t.integer  "task_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["task_id"], name: "index_stages_on_task_id"
    t.index ["user_id", "created_at"], name: "index_stages_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_stages_on_user_id"
  end

  create_table "tasks", force: :cascade do |t|
    t.text     "topic"
    t.integer  "member"
    t.text     "detail"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id", "created_at"], name: "index_tasks_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_tasks_on_user_id"
  end

routes.rb:

 resources :tasks,          only: [:create, :destroy]

task.rb
class Task < ApplicationRecord
  belongs_to :user
  has_many :stages
  default_scope -> { order(created_at: :desc) }
   validates :user_id, presence: true
   validates :topic, presence: true, length: { maximum: 140 }
   validates :detail, presence: true, length: { maximum: 140 }

end
</code>```

Project_pages_controller.rb:

```<code>def home
    if logged_in?
      @task = current_user.tasks.build
end

_task_form.html.erb:

<%= form_for(@task) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :topic, placeholder: "Compose new task..." %>
    <%= f.text_area :detail, placeholder: "Write task details..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

This is the show page
</code>```

show.html.erb

```<code>  <div class="col-md-8">
    <% if @user.tasks.any? %>
      <% if @user.stages.any? %>
      <h3>Tasks (<%= @user.tasks.count %>)</h3>
      <ol class="tasks">
        <%= render @tasks %>
        <%= render @stages %>
      </ol>
      <%= will_paginate @tasks %>
       <% end %>
    <% end %>
  </div>
</code>```

This is my controller;

```<code>class TasksController < ApplicationController
    include TasksHelper
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    @task = current_user.tasks.build(task_params)
    if @task.save
      flash[:success] = "Task created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'workshareapp_pages/home'
    end
  end

  def destroy
  end

  private

    def task_params
      params.require(:task).permit(:detail)
    end

end
</code>```

答:
You are missing the :topic field in your permit, which is why it's not being processed.</p>

```<code>def task_params
  params.require(:task).permit(:detail, :topic)
end
</code>```

Body:
After typing in topic and details in the appropriate text field and area, it still shows "validation error" "Topic cannot be empty". what is the problem? I cannot seem to figure it out.

This is the task partial
_task.html.erb:

 <li id="task-<%= task.id %>">
      <%= link_to gravatar_for(task.user, size: 50), task.user %>
      <%= link_to task.user.name, task.user %>
      Title:
       <%= task.topic %>
      Details:
      <%= task.detail %>

        Posted <%= time_ago_in_words(task.created_at) %> ago.

Schema:

ActiveRecord::Schema.define(version: 20170526194708) do

  create_table "stages", force: :cascade do |t|
    t.text     "topic"
    t.datetime "duration"
    t.text     "detail"
    t.integer  "task_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["task_id"], name: "index_stages_on_task_id"
    t.index ["user_id", "created_at"], name: "index_stages_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_stages_on_user_id"
  end

  create_table "tasks", force: :cascade do |t|
    t.text     "topic"
    t.integer  "member"
    t.text     "detail"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id", "created_at"], name: "index_tasks_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_tasks_on_user_id"
  end

routes.rb:

 resources :tasks,          only: [:create, :destroy]

task.rb
class Task < ApplicationRecord
  belongs_to :user
  has_many :stages
  default_scope -> { order(created_at: :desc) }
   validates :user_id, presence: true
   validates :topic, presence: true, length: { maximum: 140 }
   validates :detail, presence: true, length: { maximum: 140 }

end

Project_pages_controller.rb:

def home
    if logged_in?
      @task = current_user.tasks.build
end

_task_form.html.erb:

<%= form_for(@task) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_field :topic, placeholder: "Compose new task..." %>
    <%= f.text_area :detail, placeholder: "Write task details..." %>

  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

This is the show page

show.html.erb

    <% if @user.tasks.any? %>
      <% if @user.stages.any? %>

Tasks (<%= @user.tasks.count %>)

        <%= render @tasks %>
        <%= render @stages %>

      <%= will_paginate @tasks %>
       <% end %>
    <% end %>

This is my controller;

class TasksController < ApplicationController
    include TasksHelper
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    @task = current_user.tasks.build(task_params)
    if @task.save
      flash[:success] = "Task created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'workshareapp_pages/home'
    end
  end

  def destroy
  end

  private

    def task_params
      params.require(:task).permit(:detail)
    end

end

Body:
You are missing the :topic field in your permit, which is why it's not being processed.

def task_params
  params.require(:task).permit(:detail, :topic)
end


问:
Remove dakuten/handakuten in Java (aka ten-ten, ぱ→は)
Many Japanese hiragana and kana have a dakuten and a handakuten variant.

Example: は becomes ば or ぱ (notice the ゛ and ゜ parts)

Question: How to remove these from a String, in Java?

For instance, I want はばぱハバパ1aあア亜 to become はははハハハ1aあア亜.

Performance is important.

Context: Matching content with a legacy system.

答:
Characters with (han)dakuten can be decomposed into the base kana and a combining mark, Java has the Normalizer class for that in java.text.

```<code>String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD);
</code>```

Then the combining (han)dakuten marks can be removed with replace or replaceAll, for example

```<code>String noVoicingMarks = decomposed.replace("\u3099", "").replace("\u309A", "");
</code>```

Or (a bit faster in my tests)

```<code>String noVoicingMarks = decomposed.replaceAll("\u3099|\u309A", "");
</code>```

Body:
Characters with (han)dakuten can be decomposed into the base kana and a combining mark, Java has the Normalizer class for that in java.text.

String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD);

Then the combining (han)dakuten marks can be removed with replace or replaceAll, for example

String noVoicingMarks = decomposed.replace("\u3099", "").replace("\u309A", "");

Or (a bit faster in my tests)

String noVoicingMarks = decomposed.replaceAll("\u3099|\u309A", "");


问:
Good OO practice + Should we implement complicated logic in subclasses for sake of OO?
I have an Employee classified into two ( domestic and international ).
I have another class Refund, which is used to refund employees.
I have a class called Bank account used by Refund class to Refund.

Now my immediate design looks like this:

Employee interface, with 2 sub-types domestic and international.

Refund class takes in Bank in constructor.

A rough pseudocode of Refund class

```<code>Class Refund

    Refund( bank account )

   Public class Refund( employee ) {

         If (employee is domestic) {
             Pay to bank
             Account for taxes
        } else {
           do currency conversion
           Pay to bank
           Call some 3rd party to do taxation
       }
    }
}
</code>```

Now here is my question:

How can I replace Refund class with object oriented design, which is extensible and I don’t need to use if-else ?

Immediate option is to shift refund functionality into Employee class and individual subtypes can then do their own logic for refund. BUT-  does it make sense to complicate employee class with Refund logic ( which deservers its own modular class given it’s complex functions ) ?

答: To keep the OO design and make it extensible, without shifting the functionality to the Employee class, perhaps you just add attributes to the employee class such as employee type (domestic / international) as well as a refund type, which you could then use the now extendable Refund class to make particular types of refunds?</p>

Body:
I have an Employee classified into two ( domestic and international ).
I have another class Refund, which is used to refund employees.
I have a class called Bank account used by Refund class to Refund.

Now my immediate design looks like this:

Employee interface, with 2 sub-types domestic and international.

Refund class takes in Bank in constructor.

A rough pseudocode of Refund class

Class Refund

    Refund( bank account )

   Public class Refund( employee ) {

         If (employee is domestic) {
             Pay to bank
             Account for taxes
        } else {
           do currency conversion
           Pay to bank
           Call some 3rd party to do taxation
       }
    }
}

Now here is my question:

How can I replace Refund class with object oriented design, which is extensible and I don’t need to use if-else ?

Immediate option is to shift refund functionality into Employee class and individual subtypes can then do their own logic for refund. BUT-  does it make sense to complicate employee class with Refund logic ( which deservers its own modular class given it’s complex functions ) ?


问:
error executing a script in oracle
i am trying create a boolean function in oracle. But i get the following error:

Line: 3
Column: 20

Error: PLS-00103: Encountered the symbol "("

This is the code i want execute:

```<code>        CREATE OR REPLACE Function ART.prueba
        (
        p_cuser  in varchar(20)
        ) return boolean is

            l_mstat swt500.m_stat%type := null;
            l_factu  swt500.f_actu%type  := null;
        Begin
            Select m_stat , f_actu
               into l_mstat, l_factu
             from swt500
           where  c_empr = 59
              and  c_user  = p_cuser
              and  c_codi = 401
              and  t_codi = 'PR';
        return true;

        End;
        /
</code>```

Can somebody help me?

答:
Varchar and varchar2 as a parameter don't need to specify the size, lose the "(20)" in the parameter.</p>

```<code>CREATE OR REPLACE Function ART.prueba
        (
        p_cuser  in varchar
        ) return boolean is

            l_mstat swt500.m_stat%type := null;
            l_factu  swt500.f_actu%type  := null;
        Begin
            Select m_stat , f_actu
               into l_mstat, l_factu
             from swt500
           where  c_empr = 59
              and  c_user  = p_cuser
              and  c_codi = 401
              and  t_codi = 'PR';
        return true;

        End;
        /
</code>```

Title: error executing a script in oracle

Body:
i am trying create a boolean function in oracle. But i get the following error:

Line: 3
Column: 20

Error: PLS-00103: Encountered the symbol "("

This is the code i want execute:

        CREATE OR REPLACE Function ART.prueba
        (
        p_cuser  in varchar(20)
        ) return boolean is

            l_mstat swt500.m_stat%type := null;
            l_factu  swt500.f_actu%type  := null;
        Begin
            Select m_stat , f_actu
               into l_mstat, l_factu
             from swt500
           where  c_empr = 59
              and  c_user  = p_cuser
              and  c_codi = 401
              and  t_codi = 'PR';
        return true;

        End;
        /

Can somebody help me?

Body:
Varchar and varchar2 as a parameter don't need to specify the size, lose the "(20)" in the parameter.

CREATE OR REPLACE Function ART.prueba
        (
        p_cuser  in varchar
        ) return boolean is

            l_mstat swt500.m_stat%type := null;
            l_factu  swt500.f_actu%type  := null;
        Begin
            Select m_stat , f_actu
               into l_mstat, l_factu
             from swt500
           where  c_empr = 59
              and  c_user  = p_cuser
              and  c_codi = 401
              and  t_codi = 'PR';
        return true;

        End;
        /


问:
Where is the error in this? ( access query)
```<code>SELECT [02d1_NTS_Report_Structure].Nation, [02d1_NTS_Report_Structure].Region,
    [02d1_NTS_Report_Structure].Territory, [02d1_NTS_Report_Structure].Zone,
    iif ([02d1_NTS_Report_Structure].Zone="-",
        iff ([02d1_NTS_Report_Structure].Territory="-",
            iff ([02d1_NTS_Report_Structure].Region="-",
                [02d1_NTS_Report_Structure].Nation,
                [02d1_NTS_Report_Structure].Region),
        [02d1_NTS_Report_Structure].Territory),
    [02d1_NTS_Report_Structure].Zone)
FROM 02d1_NTS_Report_Structure;
</code>```

答:
The only thing I can see is that you probably should put brackets around your table name:</p>

```<code>SELECT [02d1_NTS_Report_Structure].Nation,
[02d1_NTS_Report_Structure].Region,
[02d1_NTS_Report_Structure].Territory,
[02d1_NTS_Report_Structure].Zone,
IIF([02d1_NTS_Report_Structure].Zone="-",
    IIF([02d1_NTS_Report_Structure].Territory="-",
       IIF([02d1_NTS_Report_Structure].Region="-",
           [02d1_NTS_Report_Structure].Nation,
           [02d1_NTS_Report_Structure].Region),
        [02d1_NTS_Report_Structure].Territory),
     [02d1_NTS_Report_Structure].Zone)
    FROM [02d1_NTS_Report_Structure];
</code>```

Body:
The only thing I can see is that you probably should put brackets around your table name:

SELECT [02d1_NTS_Report_Structure].Nation,
[02d1_NTS_Report_Structure].Region,
[02d1_NTS_Report_Structure].Territory,
[02d1_NTS_Report_Structure].Zone,
IIF([02d1_NTS_Report_Structure].Zone="-",
    IIF([02d1_NTS_Report_Structure].Territory="-",
       IIF([02d1_NTS_Report_Structure].Region="-",
           [02d1_NTS_Report_Structure].Nation,
           [02d1_NTS_Report_Structure].Region),
        [02d1_NTS_Report_Structure].Territory),
     [02d1_NTS_Report_Structure].Zone)
    FROM [02d1_NTS_Report_Structure];


问:
Limit of socket connection in Node JS
I use socket server with my love Node JS.

It is very perfect.

But i have a important question.

How many connection i can accept in node js?

Is there any limit for get connection?

答: Atleat 200K connection can accept in node js </p>

Title: Limit of socket connection in Node JS


问:
How to setup minheight for svg element in ui resizable widget?
How to setup minimum height for resizable svg element. i can setup minimum height for resizable widget but not for the content inside div. i have dynamic svg element instead of div. right now for example i have shown as div instead of svg element.

```<code> $('#resize').resizable({
helper: "ui-resizable-helper",
  minHeight:150,
 grid: [10, 10]
  });
</code>```

https://jsfiddle.net/gs3xpxhr/3/

答:
https://jsfiddle.net/gs3xpxhr/4/</p>

```<code> $('#resize').resizable({
helper: "ui-resizable-helper",
grid: [10, 10],
minHeight:150
});
</code>```

Body:
How to setup minimum height for resizable svg element. i can setup minimum height for resizable widget but not for the content inside div. i have dynamic svg element instead of div. right now for example i have shown as div instead of svg element.

 $('#resize').resizable({
helper: "ui-resizable-helper",
  minHeight:150,
 grid: [10, 10]
  });

https://jsfiddle.net/gs3xpxhr/3/

Body:
https://jsfiddle.net/gs3xpxhr/4/

 $('#resize').resizable({
helper: "ui-resizable-helper",
grid: [10, 10],
minHeight:150
});


问:
force gcc to compile when stack-overflow is detected
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

```<code>#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI
</code>```

and obviously the compiler didnt like that.

答:
That error message is not saying that you're going to run out of stack, though you will. It's saying that the number is too big to represent in size_t.  Make sure you're compiling for a 64-bit target.

Furthermore, don't do that.  If you need to allocate gigantic amounts of RAM, do it with malloc, not the stack.  Or, better yet, with mmap.

Body:
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI

and obviously the compiler didnt like that.


问:
button link with font awesome not working
I've tried re-coding it different ways and I'm not sure why it's not working. I'm trying to make a button that when pressed will send the user to Github all while having a font awesome icon.</p>

```<code> <a href="https://github.com/"> <button type="submit"><i class="fa fa-github"
    aria-hidden="true">GitHub</i></a>
</code>```

答:
So because I was writing this in codepen I had to add a target="_blank" to open the page in a new tab and that fixed the issue.

Thank you for the help

Body:
I've tried re-coding it different ways and I'm not sure why it's not working. I'm trying to make a button that when pressed will send the user to Github all while having a font awesome icon.

  <button type="submit">GitHub


问:
what is the use of #attribute in html5 using angular2
I'm new at angular 2. I want to know, what is #something. What it is for?
for example:

```<code><div #something></div>
</code>```

答:
is used to declare a local variable.

You can use it to assign some value that you might want to use

```<code><div #something="localVar"> </div>
</code>```

Body:
is used to declare a local variable.

You can use it to assign some value that you might want to use

<div #something="localVar"> </div>


问:
using -replace to remove a string with special characters from cells in a csv
I have a CSV file like:

```<code>"localpath"
"C:\Users\calabresel"
"C:\Users\goslinep"
"C:\Users\deangelisr"
"C:\Users\bannont"
"C:\Users\goodwind"
</code>```

I am looking for a way to isolate just the username from each field.  I will then query the AD to determine if each user is disabled or enabled.  I haven't been able to figure out how to get just the last piece though.  My idea was to use -replace to replace the identical string with null like this:

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\Users\", ""}
</code>```

That came back with invalid regular expression pattern errors though which I assumed was a result of the target string containing special characters (the backslashes).  I then started looking for a way to get powershell to take the \ literally instead.  That lead me to try this:

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace [Regex]::Escape("C:\\Users\\"), ""}
</code>```

and this

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\\Users\\", ""}
</code>```

both of those methods stop the invalid regular expression errors and just return me a fresh line without complaining.  however when I print the $txt variable it is empty...

I'm certain I am approaching this problem from the wrong angle and/or with improper syntax but I could use some guidance as I just started working with powershell a week ago.

any help provided would be greatly appreciated.

答:
The reason why you aren't getting anything back into $txt is that you update a property of $_ but don't return $_.

Assuming that you want to use the regex rather than Split-Path

```<code>$txt = import-csv C:\temp\test.csv | % {
    $_.localpath = $_.localpath -replace "C:\\Users\\", ""
    $_
}
</code>```

Or

```<code>$txt = import-csv C:\temp\test.csv | % {
    $_.localpath -replace "C:\\Users\\", ""
}
</code>```

Body:
I have a CSV file like:

"localpath"
"C:\Users\calabresel"
"C:\Users\goslinep"
"C:\Users\deangelisr"
"C:\Users\bannont"
"C:\Users\goodwind"

I am looking for a way to isolate just the username from each field.  I will then query the AD to determine if each user is disabled or enabled.  I haven't been able to figure out how to get just the last piece though.  My idea was to use -replace to replace the identical string with null like this:

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\Users\", ""}

That came back with invalid regular expression pattern errors though which I assumed was a result of the target string containing special characters (the backslashes).  I then started looking for a way to get powershell to take the \ literally instead.  That lead me to try this:

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace [Regex]::Escape("C:\\Users\\"), ""}

and this

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\\Users\\", ""}

both of those methods stop the invalid regular expression errors and just return me a fresh line without complaining.  however when I print the $txt variable it is empty...

I'm certain I am approaching this problem from the wrong angle and/or with improper syntax but I could use some guidance as I just started working with powershell a week ago.

any help provided would be greatly appreciated.

Body:
The reason why you aren't getting anything back into $txt is that you update a property of $_ but don't return $_.

Assuming that you want to use the regex rather than Split-Path

$txt = import-csv C:\temp\test.csv | % {
    $_.localpath = $_.localpath -replace "C:\\Users\\", ""
    $_
}

Or

$txt = import-csv C:\temp\test.csv | % {
    $_.localpath -replace "C:\\Users\\", ""
}


问:
Comparing array value with object
Would be really grateful for any help. Im pretty new to javascript and cant figure out how to solve this problem that I am having. Basically I have 2 arrays. One contains an object with an id value and a corresponding group value. The second array contains only the id. I would like to compare the ids of both the arrays and if they match I would like to extract the corresponding group value.

E.g.

a = [1,2,3,4,5];

b = [{1:group1},{2:group2},{3:group3}];

If id in a matches id in b then print out the id's group value

```<code>var a = [];
var b = [];
var c = {};

if (condition) {
   c  = {id:group}
   b.push(c)

}

if (condition) {
   a.push(id)

}

for (var i = 0; i < a.length; i++) {
   //If id value in a exists in b, get id's corresponding group value from b
}
</code>```

答:
An alternative solution:</p>

```<code><script>
a = [
    1, // index 0
    2, // index 1
    3, // index 2
    4, // index 3
    5  // index 4
];

b = [
    {1:'group1'}, // index [0][1]
    {2:'group2'}, // index [1][2]
    {3:'group3'} // index [2][3]
];

// If id in a matches id in b then print out the id's group value
var i = 1;
for (var key in b) {
    var bKeys = Object.keys(b[key]);

    if(bKeys[0] == a[key]) {
        console.log(b[key][i]);
    }

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

Title: Comparing array value with object

Body:
Would be really grateful for any help. Im pretty new to javascript and cant figure out how to solve this problem that I am having. Basically I have 2 arrays. One contains an object with an id value and a corresponding group value. The second array contains only the id. I would like to compare the ids of both the arrays and if they match I would like to extract the corresponding group value.

E.g.

a = [1,2,3,4,5];

b = [{1:group1},{2:group2},{3:group3}];

If id in a matches id in b then print out the id's group value

var a = [];
var b = [];
var c = {};

if (condition) {
   c  = {id:group}
   b.push(c)

}

if (condition) {
   a.push(id)

}

for (var i = 0; i < a.length; i++) {
   //If id value in a exists in b, get id's corresponding group value from b
}

Body:
An alternative solution:

<script>
a = [
    1, // index 0
    2, // index 1
    3, // index 2
    4, // index 3
    5  // index 4
];

b = [
    {1:'group1'}, // index [0][1]
    {2:'group2'}, // index [1][2]
    {3:'group3'} // index [2][3]
];

// If id in a matches id in b then print out the id's group value
var i = 1;
for (var key in b) {
    var bKeys = Object.keys(b[key]);

    if(bKeys[0] == a[key]) {
        console.log(b[key][i]);
    }

  i++;
}
</script>


问:
Get li value from ul filled by JavaScript
I have filled some "ul"s directly in HTML e.g.

```<code><button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
    <span class="caret"></span></button>
        <ul class="dropdown-menu" id="measure">
            <li><a href="#">volume</a></li>
            <li><a href="#">netSentiment</a></li>
            <li><a href="#">authors</a></li>
        </ul>
</code>```

and had no trouble reading the selected value by

```<code>$('#measure li').on('click', function(){
    $(this).text();
});
</code>```

Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:

Something like

```<code>$('#projectId').append('<li><a href="#">' + projects[i].name + '</a></li>');
</code>```

The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.

答:
What you need is Binding for dynamically created elements

$('#measure').on('click', 'li', function(){
    alert($(this).text());
});

$('#measure').append('
abc
');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <span class="caret"></span></button>
        <ul class="dropdown-menu" id="measure">
            <li>volume</li>
            <li>netSentiment</li>
            <li>authors</li>
        </ul></code>```

Here i have created abc li using jquery but still on clicking it, it gives alert just like other li.

Body:
I have filled some "ul"s directly in HTML e.g.

<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
    </button>

volume

netSentiment

authors

and had no trouble reading the selected value by

$('#measure li').on('click', function(){
    $(this).text();
});

Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:

Something like

$('#projectId').append('
' + projects[i].name + '
');

The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.

Body:
What you need is Binding for dynamically created elements

$('#measure').on('click', 'li', function(){
    alert($(this).text());
});

$('#measure').append('<li><a href="#">abc</a></li>');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <span class="caret"></span></button>
        <ul class="dropdown-menu" id="measure">
            <li><a href="#">volume</a></li>
            <li><a href="#">netSentiment</a></li>
            <li><a href="#">authors</a></li>
        </ul>

Here i have created abc li using jquery but still on clicking it, it gives alert just like other li.


问:
How do I Iterate the below equation to determine the roots
Previous Question

How to determine the best way to iterate through a loop for a sigma for the below equation using the code.

```<code>import statistics as stats
import warnings
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import scipy.stats
import sympy
from scipy import stats as st
from itertools import islice, count
import itertools

def func_shape_factor(vi, k):
k_list = []  # other name
for vi in np.nditer(vi, flags=['buffered'], op_dtypes=['float64']):
    # k initial guess of 1.5, changable
    k = 1.5
    k = (np.nan_to_num((np.sum((vi) ** (k) * np.log(vi)) / np.sum((vi) ** \
        (k)) - ((np.sum(np.log(vi)) / len(vi))))))
    k_list.append(k)  # append k to the list of ks
return np.array(k)  # cast it to an array after the loop.
</code>```

答:
The exception happens because concatenate is a NumPy function not a numpy.ndarray method. So you have to call it as:

```<code>np.concatenate(arrays)
</code>```

However it doesn't really make sense in your code because you already re-assigned k in the inner-loop. You probably want to append to the k-list so you need different variable names:

```<code>def func_shape_factor(vi, k):
    k_list = []  # other name
    for vi in np.nditer(vi, flags=['buffered'], op_dtypes=['float64']):
        # k initial guess of 1.5, changable
        k = 1.5
        k = (np.nan_to_num((np.sum((vi) ** (k) * np.log(vi)) / np.sum((vi) ** (k)) - ((np.sum(np.log(vi)) / len(vi))))))
        k_list.append(k)  # append k to the list of ks
    return np.array(k)  # cast it to an array after the loop.
</code>```

Not sure if that still does what you need though.

Body:
Previous Question

How to determine the best way to iterate through a loop for a sigma for the below equation using the code.

import statistics as stats
import warnings
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import scipy.stats
import sympy
from scipy import stats as st
from itertools import islice, count
import itertools

def func_shape_factor(vi, k):
k_list = []  # other name
for vi in np.nditer(vi, flags=['buffered'], op_dtypes=['float64']):
    # k initial guess of 1.5, changable
    k = 1.5
    k = (np.nan_to_num((np.sum((vi) ** (k) * np.log(vi)) / np.sum((vi) ** \
        (k)) - ((np.sum(np.log(vi)) / len(vi))))))
    k_list.append(k)  # append k to the list of ks
return np.array(k)  # cast it to an array after the loop.

Body:
The exception happens because concatenate is a NumPy function not a numpy.ndarray method. So you have to call it as:

np.concatenate(arrays)

However it doesn't really make sense in your code because you already re-assigned k in the inner-loop. You probably want to append to the k-list so you need different variable names:

def func_shape_factor(vi, k):
    k_list = []  # other name
    for vi in np.nditer(vi, flags=['buffered'], op_dtypes=['float64']):
        # k initial guess of 1.5, changable
        k = 1.5
        k = (np.nan_to_num((np.sum((vi) ** (k) * np.log(vi)) / np.sum((vi) ** (k)) - ((np.sum(np.log(vi)) / len(vi))))))
        k_list.append(k)  # append k to the list of ks
    return np.array(k)  # cast it to an array after the loop.

Not sure if that still does what you need though.


问:
Importing Function From Unmanaged DLL in C# Application
I need to import a function that I wrote in C++, and is now compiled into a DLL, into my C# application.  Everything builds without errors or warnings, but when I step through the code the first function call into the DLL throws an Exception with a message of "Unable to find an entry point named 'CreateScanEngine" in DLL 'WMIQuery.dll'."  The function is declared like so in my C# application:

```<code>internal static class WMIQuery
{
    [DllImport("WMIQuery.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
    internal static extern void CreateScanEngine();
}
</code>```

Dependency Walker shows the function there in the DLL as such:

Ordinal: 1(0x0001)

  Hint: 0(0x0000)

  Function ^: void CreateScanEngine(void)

  Entry Point: 0x00001860

Dependency Walker also shows these errors/warnings for the DLL:

Error: At least one required implicit or forwarded dependency was not found.

  Warning: At least one delay-load dependency module was not found.

  Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

Will this make a difference?  Also, I tried adding the DLL as a reference to the C# project, and I got this error:

A reference to [my DLL] could not be added.  Please make sure that the file is accessible, and that it is a valid assembly or COM component.

Does anyone know what I'm doing wrong?  Thanks.

答:
How are you declaring CreateScanEngine in your C++ code?

Try changing to:

```<code>extern "C" __declspec(dllexport) void __stdcall CreateScanEngine();
</code>```

Body:
I need to import a function that I wrote in C++, and is now compiled into a DLL, into my C# application.  Everything builds without errors or warnings, but when I step through the code the first function call into the DLL throws an Exception with a message of "Unable to find an entry point named 'CreateScanEngine" in DLL 'WMIQuery.dll'."  The function is declared like so in my C# application:

internal static class WMIQuery
{
    [DllImport("WMIQuery.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
    internal static extern void CreateScanEngine();
}

Dependency Walker shows the function there in the DLL as such:

Ordinal: 1(0x0001)

  Hint: 0(0x0000)

  Function ^: void CreateScanEngine(void)

  Entry Point: 0x00001860

Dependency Walker also shows these errors/warnings for the DLL:

Error: At least one required implicit or forwarded dependency was not found.

  Warning: At least one delay-load dependency module was not found.

  Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

Will this make a difference?  Also, I tried adding the DLL as a reference to the C# project, and I got this error:

A reference to [my DLL] could not be added.  Please make sure that the file is accessible, and that it is a valid assembly or COM component.

Does anyone know what I'm doing wrong?  Thanks.

Body:
How are you declaring CreateScanEngine in your C++ code?

Try changing to:

extern "C" __declspec(dllexport) void __stdcall CreateScanEngine();