问:
dropdownlist always returns first value even with EnableViewState set to true
My dropdown list control always returns the first item on postback, I've tried every solution i've come across but to no avail.
Bascially, I have two data classes that are simply containers for data.
ConnectedRobots (representing connected robot with its controller's version, its IP address and some other properties), and MiseAJour (representing a single available update with its version and some other details describing it).
These two classes are then used to create objects representing each connected robot or update available. I'm then creating a List of update versions to use it as a data source for each Dropdown list.
as shown in the picture below :

Click to view

Here's the piece of code reflecting this view (Default.aspx) :

```<code> <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationTest.WebForm1" Theme="Theme1"  EnableEventValidation="false" EnableViewState="true"%>

    ...
<body>
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
...
<div style="width:100%;">
    <table class="table table-hover">
        <thead>
            <tr>
            <th class="auto-style1">Référence Robot/Version Contrôleur</th>
            <th class="auto-style1">Pays/Adresse IP</th>
            <th class="auto-style1">Etat</th>
            <th class="auto-style1">Versions des contrôleurs disponibles</th>
            <th class="auto-style1">Planification</th>
            <th>MAJ</th>
            </tr>
        </thead>
        <tbody>
            <asp:Repeater ID="repCRobots" runat="server" EnableViewState="true">
                <ItemTemplate>
                    <tr>
                    <td>
                        <asp:Label ID="lblReferenceRobot" runat="server" Text='<%# Eval("ReferenceRobot") + " / " %> ' />
                        <asp:Label ID="lblVersionControleur" runat="server" Font-Bold="true" Text='<%# Eval("VersionControleur") %>'/>
                    </td>
                    <td>
                        <asp:Label ID="lblPays" runat="server" Text='<%# Eval("Pays") + " / " %> ' />
                        <asp:Label ID="lblIPRobot" runat="server" Font-Bold="true" Text='<%# Eval("IPRobot") %>'/>
                    </td>
                    <td>
                        <asp:Label ID="lblEtat" runat="server" Font-Bold="true" Text='<%# Eval("Etat") %>'/>
                    </td>
                    <td>
                        <asp:DropDownList ID="VersionsMAJs" runat="server" CssClass="bg-primary" EnableViewState="true" OnSelectedIndexChanged="VersionsMAJs_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
                    </td>
                    <td>
                        <span style="padding: 0px 10px 10px 10px">
                        <cc1:TimeSelector ID="TimeSelector1" runat="server" DisplayButtons="false"  Font-Bold="true" BackColor="#cce6ff" BorderStyle="Dotted" CssClass="bg-info" BorderColor="White"></cc1:TimeSelector>
                        </span>
                     </td>
                     <td>
                         <asp:CheckBox ID='SelectMAJ' runat="server"/>
                         <asp:HiddenField ID="HiddenCheckBox" Value='<% #Eval("ReferenceRobot")%>' runat="server" />
                     </td>
                     </tr>
                 </ItemTemplate>
             </asp:Repeater>
         </tbody>
     </table>

 <asp:Button ID="MAJButton" runat="server" Text="Mettre à jour" CssClass="btn btn-success btn-lg btn-block"/>
</div>
</code>```

And the code behind is the following :

```<code>public partial class WebForm1 : System.Web.UI.Page
{
    protected List<MiseAJour> ListeMAJs;
    protected List<string> ListeVersionsMAJs;
    protected List<ConnectedRobots> ListeRobotsConnectes;
    protected List<string> ListeRefRobots;
    protected DropDownList ddlVersionMAJ;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            GetConnectedRobots();
            Repeater repCRobots = this.FindControl("repCRobots") as Repeater;
            repCRobots.DataSource = ListeRobotsConnectes;
            repCRobots.DataBind();
            foreach (RepeaterItem item in repCRobots.Items)
            {
                ddlVersionMAJ = item.FindControl("VersionsMAJs") as DropDownList;
                ddlVersionMAJ.DataSource = ListeVersionsMAJs;
                ddlVersionMAJ.DataBind();
            }
        }

    }

    private void GetConnectedRobots()
    {
        WebserviceRobots ws = new WebserviceRobots();
        string[] delimiters = new string[] { "|", "||" };
        string connectedRobots = ws.getConnectedRobots();
        string majsDetails = ws.getMajsDetails();
        string[] connectedRobotsInfos = connectedRobots.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
        string[] majsInfos = majsDetails.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
        ListeRobotsConnectes = new List<ConnectedRobots>();
        ListeRefRobots = new List<string>();
        ListeMAJs = new List<MiseAJour>();
        ListeVersionsMAJs = new List<string>();

        for (int i = 0; i < majsInfos.Length - 1; i += 3)
        {
            ListeMAJs.Add(new MiseAJour() { VersionMAJ = majsInfos[i], DetailsMAJ = majsInfos[i + 1], Commentaires = majsInfos[i + 2] });
        }

        ListeVersionsMAJs = ListeMAJs.Select(v => v.VersionMAJ).ToList();

        for (int i = 0; i < connectedRobotsInfos.Length - 1; i += 5)
        {
            ListeRobotsConnectes.Add(new ConnectedRobots() { ReferenceRobot = connectedRobotsInfos[i], VersionControleur = connectedRobotsInfos[i + 1], IPRobot = connectedRobotsInfos[i + 2], Pays = connectedRobotsInfos[i + 3], Etat = connectedRobotsInfos[i + 4], VersionsMAJ = ListeVersionsMAJs });
        }

        ListeRefRobots = ListeRobotsConnectes.Select(r => r.ReferenceRobot).ToList();

    }

    protected void VersionsMAJs_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dll = (DropDownList)sender;
        string test = dll.SelectedValue;
    }
</code>```

the GetConnectedRobots() method is used to retrieve both update versions, and connected robots using a web service and couple of dynamically generated xml files.
On selectedIndexChanged, I should get the selected value or so I thought. SelectedValue always returns the first element of the dropdown list. What am I doing wrong?
I do have EnableViewState="true" for persistence between postbacks.
I am open to all kinds of answers, even if it means restructuring the whole code,
Thank you for your answers,

答:
So I resolved the issue after almost going insane, the problem weirdly enough was with getMajDetails() implemented in the WebserviceRobots. This method is used to deserialise an XML document containing updates versions and some other informations, and to return a string with these elements seprated by | character. However, it seems like XDocument automatically adds new line char at the end of each element, resulting in a string similar to this one :

1.7.1940\r\n| Détails concernant le MAJ 1.7\r\n| Commentaires 1.7\r\n||2.0.2542\r\n| Détails concernant le MAJ 2.0\r\n| Commentaires 2.0\r\n||1.8.2495\r\n| Détails concernant le MAJ 1.8\r\n| Commentaires 1.8\r\n||

So, each ListeVersionsMAJs element ends up with \r\n at the end. and When this list is used to populate the dorpdown list, it causses it to behave the way it did (returning the first value at each postback). the solution was to remove \r\n .
I have no explanation as to why this is happening, testing the dropdown list with a List of strings initialized with fixed string values with new line char at the end of each value resulted in the same odd behavior.
So if anyone could clear this up, it would be much appreciate it.

Body:
My dropdown list control always returns the first item on postback, I've tried every solution i've come across but to no avail.
Bascially, I have two data classes that are simply containers for data.
ConnectedRobots (representing connected robot with its controller's version, its IP address and some other properties), and MiseAJour (representing a single available update with its version and some other details describing it).
These two classes are then used to create objects representing each connected robot or update available. I'm then creating a List of update versions to use it as a data source for each Dropdown list.
as shown in the picture below :

Click to view

Here's the piece of code reflecting this view (Default.aspx) :

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationTest.WebForm1" Theme="Theme1"  EnableEventValidation="false" EnableViewState="true"%>

    ...

<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
...

            Référence Robot/Version Contrôleur
            Pays/Adresse IP
            Etat
            Versions des contrôleurs disponibles
            Planification
            MAJ

            <asp:Repeater ID="repCRobots" runat="server" EnableViewState="true">
                <ItemTemplate>

                        <asp:Label ID="lblReferenceRobot" runat="server" Text='<%# Eval("ReferenceRobot") + " / " %> ' />
                        <asp:Label ID="lblVersionControleur" runat="server" Font-Bold="true" Text='<%# Eval("VersionControleur") %>'/>

                        <asp:Label ID="lblPays" runat="server" Text='<%# Eval("Pays") + " / " %> ' />
                        <asp:Label ID="lblIPRobot" runat="server" Font-Bold="true" Text='<%# Eval("IPRobot") %>'/>

                        <asp:Label ID="lblEtat" runat="server" Font-Bold="true" Text='<%# Eval("Etat") %>'/>

                        <asp:DropDownList ID="VersionsMAJs" runat="server" CssClass="bg-primary" EnableViewState="true" OnSelectedIndexChanged="VersionsMAJs_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>

                        <cc1:TimeSelector ID="TimeSelector1" runat="server" DisplayButtons="false"  Font-Bold="true" BackColor="#cce6ff" BorderStyle="Dotted" CssClass="bg-info" BorderColor="White"></cc1:TimeSelector>

                         <asp:CheckBox ID='SelectMAJ' runat="server"/>
                         <asp:HiddenField ID="HiddenCheckBox" Value='<% #Eval("ReferenceRobot")%>' runat="server" />

                 </ItemTemplate>
             </asp:Repeater>

 <asp:Button ID="MAJButton" runat="server" Text="Mettre à jour" CssClass="btn btn-success btn-lg btn-block"/>

And the code behind is the following :

public partial class WebForm1 : System.Web.UI.Page
{
    protected List<MiseAJour> ListeMAJs;
    protected List<string> ListeVersionsMAJs;
    protected List<ConnectedRobots> ListeRobotsConnectes;
    protected List<string> ListeRefRobots;
    protected DropDownList ddlVersionMAJ;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            GetConnectedRobots();
            Repeater repCRobots = this.FindControl("repCRobots") as Repeater;
            repCRobots.DataSource = ListeRobotsConnectes;
            repCRobots.DataBind();
            foreach (RepeaterItem item in repCRobots.Items)
            {
                ddlVersionMAJ = item.FindControl("VersionsMAJs") as DropDownList;
                ddlVersionMAJ.DataSource = ListeVersionsMAJs;
                ddlVersionMAJ.DataBind();
            }
        }

    }

    private void GetConnectedRobots()
    {
        WebserviceRobots ws = new WebserviceRobots();
        string[] delimiters = new string[] { "|", "||" };
        string connectedRobots = ws.getConnectedRobots();
        string majsDetails = ws.getMajsDetails();
        string[] connectedRobotsInfos = connectedRobots.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
        string[] majsInfos = majsDetails.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
        ListeRobotsConnectes = new List<ConnectedRobots>();
        ListeRefRobots = new List<string>();
        ListeMAJs = new List<MiseAJour>();
        ListeVersionsMAJs = new List<string>();

        for (int i = 0; i < majsInfos.Length - 1; i += 3)
        {
            ListeMAJs.Add(new MiseAJour() { VersionMAJ = majsInfos[i], DetailsMAJ = majsInfos[i + 1], Commentaires = majsInfos[i + 2] });
        }

        ListeVersionsMAJs = ListeMAJs.Select(v => v.VersionMAJ).ToList();

        for (int i = 0; i < connectedRobotsInfos.Length - 1; i += 5)
        {
            ListeRobotsConnectes.Add(new ConnectedRobots() { ReferenceRobot = connectedRobotsInfos[i], VersionControleur = connectedRobotsInfos[i + 1], IPRobot = connectedRobotsInfos[i + 2], Pays = connectedRobotsInfos[i + 3], Etat = connectedRobotsInfos[i + 4], VersionsMAJ = ListeVersionsMAJs });
        }

        ListeRefRobots = ListeRobotsConnectes.Select(r => r.ReferenceRobot).ToList();

    }

    protected void VersionsMAJs_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dll = (DropDownList)sender;
        string test = dll.SelectedValue;
    }

the GetConnectedRobots() method is used to retrieve both update versions, and connected robots using a web service and couple of dynamically generated xml files.
On selectedIndexChanged, I should get the selected value or so I thought. SelectedValue always returns the first element of the dropdown list. What am I doing wrong?
I do have EnableViewState="true" for persistence between postbacks.
I am open to all kinds of answers, even if it means restructuring the whole code,
Thank you for your answers,


来源: stackexchange

问:
Window xp and java 8
I am making a project by java 8 but I'm confusing about can window xp run java 8 project as well, and I don't know if I use new resources of java 8, will it work in window xp like work in window 10? =)), Thanks!</p>

答: The supported platforms are here and windows XP is not present there. I would not risk it as hotspot most probably relies on system calls that might not be present in xp

ContentLicense: CC BY-SA 3.0

Title: Window xp and java 8


问:
editText get text kotlin
How to get editText in kotlin and display with toast.

```<code>var editTextHello = findViewById(R.id.editTextHello)
</code>```

I tried this but shows object

```<code>Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()
</code>```

答:
use  editTextHello.text

```<code>  Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
</code>```

ContentLicense: CC BY-SA 4.0

Title: editText get text kotlin

Body:
How to get editText in kotlin and display with toast.

var editTextHello = findViewById(R.id.editTextHello)

I tried this but shows object

Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()

Body:
use  editTextHello.text

  Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()


问:
Spring @Autowire on non-setter methods
I just came across some samples where the @Autowire is used on non-setter methods.

```<code>@Autowired
public void doSomething(MyType t){
     System.out.println(t);
}
</code>```

how will i call this method ? like objectReference.doSomething(); does the parameter is not required while calling these methods ?

when do we use @Autowire on non-setter methods

can anybody share some samples on the same ?

答:
spring doc says clearly, @Autowired can be applied on Constructors, Fields, Setters and Arbitrary methods with arbitrary names and/or multiple arguments.

come to your questions, think of doSomething(<>) is an arbitrary method, which should be invoked by container not yourself.
Have a look at this thread

Title: Spring @Autowire on non-setter methods

Body:
I just came across some samples where the @Autowire is used on non-setter methods.

@Autowired
public void doSomething(MyType t){
     System.out.println(t);
}

how will i call this method ? like objectReference.doSomething(); does the parameter is not required while calling these methods ?

when do we use @Autowire on non-setter methods

can anybody share some samples on the same ?


问:
How can I get Mercurial to list all tracked files that are tracked as symlinks?
I would like to have Mercurial list all tracked files in the repo that are supposed to be symlinks.  I can get a list of tracked symlinks that are symlinks in the working copy with hg files "set:symlink()", but that doesn't capture the tracked symlinks that aren't symlinks in the working copy.

What I want instead is a command that looks at the tracked file's properties in the manifest and tells me if the symlink bit is set.  I've tried to use hg manifest -v, which the documentation says will "print file permissions, symlink and executable bits". I've tried that, but the symlinks are indistinguishable from non-link files whose executable bit is set.  I get lots of:

```<code>755 * path/to/file
</code>```

If I try to use the leading markers (hg manifest -v | grep '755 *'), the files I want are listed, but I also get lots of false positives.

Background: Adding and committing symbolic links seems to work for us, but Mercurial is refusing to create the symlinks when someone else pulls those changesets.  I understand why Mercurial is refusing: we run afoul of an undocumented rule.  So now we end up with files where the symlinks are supposed to be, and the content of the file is the path to which the symlink is supposed to point.  If I can get Mercurial to tell me which files are supposed to be symlinks, I can easily replace the files with the appropriate links.

Thank you!

Edit: In my repository, the symlinks had not been committed properly due to a bug in the client, which is why hg manifest -v wasn't showing the committed files as links.

答:
To assess which files changed from symlink to 'normal files', you could try to throw some bash at it and compare the output of the fileset of the modified and unmodified versions. Maybe something like

```<code>diff <(hg files "set:symlink()" -r.) <(hg files "set:symlink()")
</code>```

Example:

In a repository where eeg-link was added, foo22-link changed to a normal file and foo edited (and foo-link kept pointing at it):

```<code>$ hg diff
diff --git a/eeg-link b/eeg-link
new file mode 120000
--- /dev/null
+++ b/eeg-link
@@ -0,0 +1,1 @@
+eeg
\ No newline at end of file
diff --git a/foo b/foo
--- a/foo
+++ b/foo
@@ -1,2 +1,3 @@
foo is boo!
And this change, too!
+And even this.
diff --git a/foo22-link b/foo22-link
old mode 120000
new mode 100644
--- a/foo22-link
+++ b/foo22-link
@@ -1,1 +1,1 @@
-foo22
\ No newline at end of file
+This is no symlink anymore
</code>```

we get a nice and clean output of

```<code>$ diff <(hg files "set:symlink()" -r.) <(hg files "set:symlink()")
0a1
> eeg-link
2d2
< foo22-link
</code>```

showing the newly-added symlinks (eeg-link) and the removed symlink (foo22-link).

Body:
I would like to have Mercurial list all tracked files in the repo that are supposed to be symlinks.  I can get a list of tracked symlinks that are symlinks in the working copy with hg files "set:symlink()", but that doesn't capture the tracked symlinks that aren't symlinks in the working copy.

What I want instead is a command that looks at the tracked file's properties in the manifest and tells me if the symlink bit is set.  I've tried to use hg manifest -v, which the documentation says will "print file permissions, symlink and executable bits". I've tried that, but the symlinks are indistinguishable from non-link files whose executable bit is set.  I get lots of:

755 * path/to/file

If I try to use the leading markers (hg manifest -v | grep '755 *'), the files I want are listed, but I also get lots of false positives.

Background: Adding and committing symbolic links seems to work for us, but Mercurial is refusing to create the symlinks when someone else pulls those changesets.  I understand why Mercurial is refusing: we run afoul of an undocumented rule.  So now we end up with files where the symlinks are supposed to be, and the content of the file is the path to which the symlink is supposed to point.  If I can get Mercurial to tell me which files are supposed to be symlinks, I can easily replace the files with the appropriate links.

Thank you!

Edit: In my repository, the symlinks had not been committed properly due to a bug in the client, which is why hg manifest -v wasn't showing the committed files as links.

Body:
To assess which files changed from symlink to 'normal files', you could try to throw some bash at it and compare the output of the fileset of the modified and unmodified versions. Maybe something like

diff <(hg files "set:symlink()" -r.) <(hg files "set:symlink()")

Example:

In a repository where eeg-link was added, foo22-link changed to a normal file and foo edited (and foo-link kept pointing at it):

$ hg diff
diff --git a/eeg-link b/eeg-link
new file mode 120000
--- /dev/null
+++ b/eeg-link
@@ -0,0 +1,1 @@
+eeg
\ No newline at end of file
diff --git a/foo b/foo
--- a/foo
+++ b/foo
@@ -1,2 +1,3 @@
foo is boo!
And this change, too!
+And even this.
diff --git a/foo22-link b/foo22-link
old mode 120000
new mode 100644
--- a/foo22-link
+++ b/foo22-link
@@ -1,1 +1,1 @@
-foo22
\ No newline at end of file
+This is no symlink anymore

we get a nice and clean output of

$ diff <(hg files "set:symlink()" -r.) <(hg files "set:symlink()")
0a1
> eeg-link
2d2
< foo22-link

showing the newly-added symlinks (eeg-link) and the removed symlink (foo22-link).


问:
Java: XML to Object (or Array)
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

```<code>DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
</code>```

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

答:
Use XStream.

Object to XML

```<code>Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
</code>```

The resulting XML looks like this:

```<code><person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>
</code>```

XML to Object

```<code>Person newJoe = (Person)xstream.fromXML(xml);
</code>```

Also see

Reference

Simple

ContentLicense: CC BY-SA 2.5

Title: Java: XML to Object (or Array)

Body:
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

Body:
Use XStream.

Object to XML

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);

The resulting XML looks like this:

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>

XML to Object

Person newJoe = (Person)xstream.fromXML(xml);

Also see

Reference

Simple


问:
Add line at the beginning and end of a file in python
Good, I have the following code:

```<code>numList = [6, 7, 8, 10, 15, 18, 31, 35, 51, 54]

with open('/home/user/test.nft') as f:
    lines = f.readlines()

for i, l in enumerate(lines):
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            if "oifname bond1.%d" %num in l:
                f = open('inet-filter-chain-vlan%d_in.nft' %num, 'a')
            else:
                f = open('inet-filter-chain-vlan%d_out.nft' %num, 'a')

            f.write(l)
            f.close()
            break
</code>```

I want to add a line at the beginning and end of the generated files in the if: inet-filter-chain-vlan% d_in.nft and inet-filter-chain-vlan% d_out.nft.

For example, the contents of the inet-filter-chain-vlan20_in.nft file should be:

Custom line for file 20

......content...........

Custom line for file 20

答:
You need to cache which files you are writing to.

This can be done in a simple manner with a set,

Why not use with open(...) as f: again too?

```<code>fileset = set()
for i, l in enumerate(lines):
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            in_out = 'in' if "oifname bond1.%d" %num in l else 'out'
            filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out)
            with open(filename, 'a') as f:
                # the first time we open a file, output the custom line
                if filename not in fileset:
                    custom_string="Custom line for %s\n" % filename
                    f.write(custom_string)
                    fileset.add(filename)
                f.write(l)
            break
# now we need to write the final line in each file
for filename in fileset:
    with open(filename, 'a') as f:
        custom_string="Custom line for %s\n" % filename
        f.write(custom_string)
</code>```

There are other ways to do this, but this is simple and doesn't leave the files open, which has an overhead in opening and closing the files often (for each line) but doesn't potentially open many files.

If you want to keep the files open for write performace, I suggest using bare opens, use a dict (keyed by filename) to store the file references, then close them after writing the final line. It should look something like:

```<code>filedict = {}
for i, l in enumerate(lines):
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            in_out = 'in' if "oifname bond1.%d" %num in l else 'out'
            filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out)
                # the first time we open a file, output the custom line
                f = filedict.get(filename)
                if f is None:
                    custom_string="Custom line for %s\n" % filename
                    f = open(filename, 'a')
                    f.write(custom_string)
                    filedict[filename] = f
                f.write(l)
            break
# now we need to write the final line in each file
for filename, f in filedict:
    custom_string="Custom line for %s\n" % filename
    f.write(custom_string)
    f.close()
</code>```

Body:
Good, I have the following code:

numList = [6, 7, 8, 10, 15, 18, 31, 35, 51, 54]

with open('/home/user/test.nft') as f:
    lines = f.readlines()

for i, l in enumerate(lines):
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            if "oifname bond1.%d" %num in l:
                f = open('inet-filter-chain-vlan%d_in.nft' %num, 'a')
            else:
                f = open('inet-filter-chain-vlan%d_out.nft' %num, 'a')

            f.write(l)
            f.close()
            break

I want to add a line at the beginning and end of the generated files in the if: inet-filter-chain-vlan% d_in.nft and inet-filter-chain-vlan% d_out.nft.

For example, the contents of the inet-filter-chain-vlan20_in.nft file should be:

Custom line for file 20

......content...........

Custom line for file 20

Body:
You need to cache which files you are writing to.

This can be done in a simple manner with a set,

Why not use with open(...) as f: again too?

fileset = set()
for i, l in enumerate(lines):
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            in_out = 'in' if "oifname bond1.%d" %num in l else 'out'
            filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out)
            with open(filename, 'a') as f:
                # the first time we open a file, output the custom line
                if filename not in fileset:
                    custom_string="Custom line for %s\n" % filename
                    f.write(custom_string)
                    fileset.add(filename)
                f.write(l)
            break
# now we need to write the final line in each file
for filename in fileset:
    with open(filename, 'a') as f:
        custom_string="Custom line for %s\n" % filename
        f.write(custom_string)

There are other ways to do this, but this is simple and doesn't leave the files open, which has an overhead in opening and closing the files often (for each line) but doesn't potentially open many files.

If you want to keep the files open for write performace, I suggest using bare opens, use a dict (keyed by filename) to store the file references, then close them after writing the final line. It should look something like:

filedict = {}
for i, l in enumerate(lines):
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            in_out = 'in' if "oifname bond1.%d" %num in l else 'out'
            filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out)
                # the first time we open a file, output the custom line
                f = filedict.get(filename)
                if f is None:
                    custom_string="Custom line for %s\n" % filename
                    f = open(filename, 'a')
                    f.write(custom_string)
                    filedict[filename] = f
                f.write(l)
            break
# now we need to write the final line in each file
for filename, f in filedict:
    custom_string="Custom line for %s\n" % filename
    f.write(custom_string)
    f.close()


问:
How to get user_mentions info in Twitter API
I've parsed a json file and now I want to see the mentions that every tweet has received.

Looking at the structure I see is in $entities$user_mentions but all I get there in NULL values.
As I see in https://dev.twitter.com/overview/api/entities, there is also hashtag, media, url... and all them retrieve NULL values.

I've tried several functions but non of them have worked for me:

mentions<- subset(data, !is.null(data$entities))

```<code>mentions<- sapply(data, function(x) if (is.null(x$entities$user_mentions)) NA else  x$entities$user_mentions$id_str)
</code>```

I'd appreciate some help on how can I manage this info
Thank you

EDIT: So, after parsing with parse_stream() I want to work with the column
 mentions_user_id

```<code>dput(head(json_data2[, c(5,23:26)]))
structure(list(text = c("RT @SteveBlogs1: Diane Abbott when she heard the #GeneralElection announcement. ",
"RT @DrHughHarvey: Worried that 18-24 yr olds will vote against you in your snap election? No probs, just hold it in the middle of exam seas…",
"There goes @JonnElledge taking my inner monologue and publishing it in New @NewStatesman again.. ",
"RT @Channel4News: Theresa May has repeatedly said that there would be no election until 2020. Today she “reluctantly” decided to call… ",
"RT @charlottechurch: Theresa May is full of <f0><U+009F><U+0092><U+00A9><f0><U+009F><U+0092><U+00A9><f0><U+009F><U+0092><U+00A9>",
"RT @Jim_Watford: Here comes the Labour battle bus. #GeneralElection "
), mentions_screen_name = c("SteveBlogs1", "DrHughHarvey", "JonnElledge NewStatesman",
"Channel4News", "charlottechurch", "Jim_Watford"), mentions_user_id = c("2796723891",
"2324111390", "21862223 19906615", "14569869", "167711000", "44941453"
), symbols = c(NA, NA, NA, NA, NA, NA), hashtags = c("GeneralElection",
NA, NA, NA, NA, "GeneralElection")), .Names = c("text", "mentions_screen_name",
"mentions_user_id", "symbols", "hashtags"), row.names = c(NA,
6L), class = "data.frame")
</code>```

The point now it's that I need to do a sapply for a later graph but It doesn't work because of the next error:

ment<- sapply(data, function(x) if (is.null(x$mentions_user_id)) NA else x$mentions_user_id)

Error: '$ operator is invalid for atomic vectors'

I've tried also:
men_ids<- sapply(data2, function(x) if (is.null(x[mentions_user_id])) NA else  x[mentions_user_id])

Error in FUN(X[[i]], ...) : object 'mentions_user_id' not found

And doesn't work either. I know there are several links about this but still...

It's a data frame.If I convert it to a list jdlist <- as.list(data2)
then is.recursive(men_ids) gives TRUE which means it should works but again same error when sapply.

答:
Here's a quick example:</p>

```<code>library(rtweet)
r <- search_tweets("#rstats")
r[c(3:5,8),c("mentions_screen_name", "text")]
#     mentions_screen_name                                                                                text
# 3               DataCamp      RT @DataCamp: Algorithmic Trading in R, tutorial & tips here - U5KQzE8rJI #Algotrading #rstats PNxQ8OSquX
# 4                   <NA>                  Cheat Sheet of Machine Learning and Python (and Math) Cheat Sheets | ymj4bu8pCB | #rstats #python #datascience
# 5              Rbloggers                                             RT @Rbloggers: How to Install R Ubuntu 16.04 Xenial xNk51T5E6F #rstats #DataScience
# 8 DataScienceLA earlconf RT @DataScienceLA: Slides for my talk at @earlconf #EARLConf2017 are here xYDWKnR3tM #rstats #machinelearning U9k…
</code>```

Body:
I've parsed a json file and now I want to see the mentions that every tweet has received.

Looking at the structure I see is in $entities$user_mentions but all I get there in NULL values.
As I see in https://dev.twitter.com/overview/api/entities, there is also hashtag, media, url... and all them retrieve NULL values.

I've tried several functions but non of them have worked for me:

mentions<- subset(data, !is.null(data$entities))

mentions<- sapply(data, function(x) if (is.null(x$entities$user_mentions)) NA else  x$entities$user_mentions$id_str)

I'd appreciate some help on how can I manage this info
Thank you

EDIT: So, after parsing with parse_stream() I want to work with the column
 mentions_user_id

dput(head(json_data2[, c(5,23:26)]))
structure(list(text = c("RT @SteveBlogs1: Diane Abbott when she heard the #GeneralElection announcement. ",
"RT @DrHughHarvey: Worried that 18-24 yr olds will vote against you in your snap election? No probs, just hold it in the middle of exam seas…",
"There goes @JonnElledge taking my inner monologue and publishing it in New @NewStatesman again.. ",
"RT @Channel4News: Theresa May has repeatedly said that there would be no election until 2020. Today she “reluctantly” decided to call… ",
"RT @charlottechurch: Theresa May is full of <f0><f0><f0>",
"RT @Jim_Watford: Here comes the Labour battle bus. #GeneralElection "
), mentions_screen_name = c("SteveBlogs1", "DrHughHarvey", "JonnElledge NewStatesman",
"Channel4News", "charlottechurch", "Jim_Watford"), mentions_user_id = c("2796723891",
"2324111390", "21862223 19906615", "14569869", "167711000", "44941453"
), symbols = c(NA, NA, NA, NA, NA, NA), hashtags = c("GeneralElection",
NA, NA, NA, NA, "GeneralElection")), .Names = c("text", "mentions_screen_name",
"mentions_user_id", "symbols", "hashtags"), row.names = c(NA,
6L), class = "data.frame")

The point now it's that I need to do a sapply for a later graph but It doesn't work because of the next error:

ment<- sapply(data, function(x) if (is.null(x$mentions_user_id)) NA else x$mentions_user_id)

Error: '$ operator is invalid for atomic vectors'

I've tried also:
men_ids<- sapply(data2, function(x) if (is.null(x[mentions_user_id])) NA else  x[mentions_user_id])

Error in FUN(X[[i]], ...) : object 'mentions_user_id' not found

And doesn't work either. I know there are several links about this but still...

It's a data frame.If I convert it to a list jdlist <- as.list(data2)
then is.recursive(men_ids) gives TRUE which means it should works but again same error when sapply.

Body:
Here's a quick example:

library(rtweet)
r <- search_tweets("#rstats")
r[c(3:5,8),c("mentions_screen_name", "text")]
#     mentions_screen_name                                                                                text
# 3               DataCamp      RT @DataCamp: Algorithmic Trading in R, tutorial &amp; tips here - U5KQzE8rJI #Algotrading #rstats PNxQ8OSquX
# 4                   <NA>                  Cheat Sheet of Machine Learning and Python (and Math) Cheat Sheets | ymj4bu8pCB | #rstats #python #datascience
# 5              Rbloggers                                             RT @Rbloggers: How to Install R Ubuntu 16.04 Xenial xNk51T5E6F #rstats #DataScience
# 8 DataScienceLA earlconf RT @DataScienceLA: Slides for my talk at @earlconf #EARLConf2017 are here xYDWKnR3tM #rstats #machinelearning U9k…


问:
Can I register Orchard resources in an HtmlHelper?
I am aware that this violates the MVC principle and best practices.

I have a whole bunch of custom Angular components that each take a whole bunch of optional parameters and each require a different remote stylesheet and javascript file. I would like to render these with an HtmlHelper without having to manually include the right resources everywhere I use them.

I was hoping that this would do the trick but it doesn't

public static class HtmlExtensions
{
    private static IResourceManager _resourceManager;

    // Executed in the Activated method of an OrchardShellEvents implementation
    public static void SetResourceManager(IResourceManager resourceManager)
    {
        _resourceManager = resourceManager;
    }

    public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component)
    {
        // Require the resources
        var _styleRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Style");
        var _scriptRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Script");

        _styleRegister.Require(component.StyleSheet).AtHead();

        if (!string.IsNullOrEmpty(component.Script))
        {
            _scriptRegister.Require(component.Script).AtFoot();
        }

        // Create tag
        var tag = new TagBuilder(component.Tag);
        tag.MergeAttributes(component.Parameters);

        return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
    }
}
```

<p>I could use an arbitrary Shape as a helper, something like:</p>

<pre class="lang-cs prettyprint-override"><code>@Display(New.Angular(Model: new CustomAngularComponent(...)))
</code>```

but a helper with strongly typed parameters feels a lot better.

答:
This comment on another Orchard question tipped me off. As it turns out, simply injecting Work<IResourceManager> and using it directly was enough to make my setup work. Please note that this does not conform to best MVC practices, by doing this I sacrifice maintainability in favor of readability.

public static class HtmlExtensions
{
    private static Work<IResourceManager> _resourceManager;

    // Executed in the Activated method of an OrchardShellEvents implementation
    public static void SetResourceManager(Work<IResourceManager> resourceManager)
    {
        _resourceManager = resourceManager;
    }

    public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component)
    {
        // Require the resources
        _resourceManager.Value.Require("stylesheet", component.StyleSheet).AtHead();

        if (!string.IsNullOrEmpty(component.Script))
        {
            _resourceManager.Value.Require("script", component.Script).AtFoot();
        }

        // Create tag
        var tag = new TagBuilder(component.Tag);
        tag.MergeAttributes(component.Parameters);

        return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
    }
}
```

Body:
I am aware that this violates the MVC principle and best practices.

I have a whole bunch of custom Angular components that each take a whole bunch of optional parameters and each require a different remote stylesheet and javascript file. I would like to render these with an HtmlHelper without having to manually include the right resources everywhere I use them.

I was hoping that this would do the trick but it doesn't

public static class HtmlExtensions
{
    private static IResourceManager _resourceManager;

    // Executed in the Activated method of an OrchardShellEvents implementation
    public static void SetResourceManager(IResourceManager resourceManager)
    {
        _resourceManager = resourceManager;
    }

    public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component)
    {
        // Require the resources
        var _styleRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Style");
        var _scriptRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Script");

        _styleRegister.Require(component.StyleSheet).AtHead();

        if (!string.IsNullOrEmpty(component.Script))
        {
            _scriptRegister.Require(component.Script).AtFoot();
        }

        // Create tag
        var tag = new TagBuilder(component.Tag);
        tag.MergeAttributes(component.Parameters);

        return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
    }
}

I could use an arbitrary Shape as a helper, something like:

@Display(New.Angular(Model: new CustomAngularComponent(...)))

but a helper with strongly typed parameters feels a lot better.


问:
informatica power center. find dependency view in repository metadata
I have a question about informatica metadata, and i will be glad for any advices.

We can rightclick on any workflow in Informatica power center and choose
"Dependencies". After it, we see the window, where we can choose, what dependent objects we want to see.

When we press "OK", appears "VIEW Dependencies" window with list of dependent objects and info about them (object_name, object_type, timestamp, status, etc).
Does anybody know, how to select this list from informatica metadata repository tables? Or may be somebody know the way, how can i extract this select from power center designer.

I know about separeted views with mappings, sources, targets, etc, but may be you know, how to get exactly the same data, as on this window.

Thank you for any help

答:
We can check the dependencies through querying the Informatica repository Metadata tables. But for that we need to know the oracle connection details in which the metadata tables are resided(Mostly Informatica admins knows about the connection). If we get the connection details we can check the below tables:
OPB_MAPPING,
OPB_SUBJECT,
OPB_WIDGET(for transformations),
OPB_TASK,
OPB_WFLOW_RUN etc

Below is the sample SQL query that shows the names of all the Folders in the repository and the mappings contained in them along with last saved date, mapping version number and versioning comments, if any.

```<code>SELECT
  S.SUBJ_NAME FOLDER,
  M.MAPPING_NAME MAPPING,
  M.VERSION_NUMBER VERSION_NUMBER,
  CASE WHEN M.IS_VALID = 1 THEN 'YES' ELSE 'NO' END IS_VALID,
  M.LAST_SAVED SAVED_ON,
  M.CHECKOUT_USER_ID,
  M.COMMENTS
FROM OPB_MAPPING M, OPB_SUBJECT S
WHERE M.SUBJECT_ID = S.SUBJ_ID
AND is_visible = 1
ORDER BY 1, 2, 3;
</code>```

Body:
We can check the dependencies through querying the Informatica repository Metadata tables. But for that we need to know the oracle connection details in which the metadata tables are resided(Mostly Informatica admins knows about the connection). If we get the connection details we can check the below tables:
OPB_MAPPING,
OPB_SUBJECT,
OPB_WIDGET(for transformations),
OPB_TASK,
OPB_WFLOW_RUN etc

Below is the sample SQL query that shows the names of all the Folders in the repository and the mappings contained in them along with last saved date, mapping version number and versioning comments, if any.

SELECT
  S.SUBJ_NAME FOLDER,
  M.MAPPING_NAME MAPPING,
  M.VERSION_NUMBER VERSION_NUMBER,
  CASE WHEN M.IS_VALID = 1 THEN 'YES' ELSE 'NO' END IS_VALID,
  M.LAST_SAVED SAVED_ON,
  M.CHECKOUT_USER_ID,
  M.COMMENTS
FROM OPB_MAPPING M, OPB_SUBJECT S
WHERE M.SUBJECT_ID = S.SUBJ_ID
AND is_visible = 1
ORDER BY 1, 2, 3;


问:
Both parameterized and sharing recources test in googletest
Using googletest framework  I try to create an inherited fixture class in order to make a both parameterized and sharing recources test.

```<code>class FixtDBadminConnShared : public ::testing::Test {
  public:
    static void SetUpTestCase() {
      shared_conn_ = new ::DB::DB_connection();
    }
    static void TearDownTestCase() {
      delete shared_conn_;
    }
    static ::DB::DB_connection * shared_conn_;
    };
::DB::DB_connection * FixtDBadminConnShared::shared_conn_ = nullptr;

class FixtDBadminConnExec :public FixtDBadminConnShared, public ::testing::TestWithParam<string>
  {
  protected:
    using FixtDBadminConnShared::SetUpTestCase;
    using FixtDBadminConnShared::TearDownTestCase;

    void SetUp() override {
      query_ = GetParam();
    }
    string query_;
  };
</code>```

Trying to call the test:

```<code>TEST_P(FixtDBadminConnExec, SelectWithoutParam) {
 //do smth
}
INSTANTIATE_TEST_CASE_P(QueriesOrbital0param, FixtDBadminConnExec,
::testing::Values( string{ "SELECT * from my_table;" }));
</code>```

I get the next error

```<code>Error   C2594   'return': ambiguous conversions from 'FixtDBadminConnExec_SelectWithoutParam_Test *' to 'testing::Test *'   gtest_mytest    e:\libs\googletest\googletest\include\gtest\internal\gtest-param-util.h 415
</code>```

Here is a part of gtest-param-util.h with 415 line on  return new TestClass():

```<code>template <class TestClass>
class ParameterizedTestFactory : public TestFactoryBase {
 public:
  typedef typename TestClass::ParamType ParamType;
  explicit ParameterizedTestFactory(ParamType parameter) :
      parameter_(parameter) {}
  virtual Test* CreateTest() {
    TestClass::SetParam(&parameter_);
    return new TestClass();
  }

 private:
  const ParamType parameter_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
};
</code>```

So, I guess that problem could be also that I want to use both a parameterized test (TEST_P macros) and a test with shared resources (TEST_F macros ). How can I do it, if can?

答: Your problem here is that TestWithParam<> inherits from testing::Test and there is an ambiguous conversion. Instead, inherit from WithParamInterface<></p>

Body:
Using googletest framework  I try to create an inherited fixture class in order to make a both parameterized and sharing recources test.

class FixtDBadminConnShared : public ::testing::Test {
  public:
    static void SetUpTestCase() {
      shared_conn_ = new ::DB::DB_connection();
    }
    static void TearDownTestCase() {
      delete shared_conn_;
    }
    static ::DB::DB_connection * shared_conn_;
    };
::DB::DB_connection * FixtDBadminConnShared::shared_conn_ = nullptr;

class FixtDBadminConnExec :public FixtDBadminConnShared, public ::testing::TestWithParam<string>
  {
  protected:
    using FixtDBadminConnShared::SetUpTestCase;
    using FixtDBadminConnShared::TearDownTestCase;

    void SetUp() override {
      query_ = GetParam();
    }
    string query_;
  };

Trying to call the test:

TEST_P(FixtDBadminConnExec, SelectWithoutParam) {
 //do smth
}
INSTANTIATE_TEST_CASE_P(QueriesOrbital0param, FixtDBadminConnExec,
::testing::Values( string{ "SELECT * from my_table;" }));

I get the next error

Error   C2594   'return': ambiguous conversions from 'FixtDBadminConnExec_SelectWithoutParam_Test *' to 'testing::Test *'   gtest_mytest    e:\libs\googletest\googletest\include\gtest\internal\gtest-param-util.h 415

Here is a part of gtest-param-util.h with 415 line on  return new TestClass():

template <class TestClass>
class ParameterizedTestFactory : public TestFactoryBase {
 public:
  typedef typename TestClass::ParamType ParamType;
  explicit ParameterizedTestFactory(ParamType parameter) :
      parameter_(parameter) {}
  virtual Test* CreateTest() {
    TestClass::SetParam(&parameter_);
    return new TestClass();
  }

 private:
  const ParamType parameter_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
};

So, I guess that problem could be also that I want to use both a parameterized test (TEST_P macros) and a test with shared resources (TEST_F macros ). How can I do it, if can?


问:
Why does the "+" operator consider the number as string when added
Why does the + operator consider the number as string when added

Ex :

```<code>'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"
</code>```

答:
+ will only add two numbers if it has a number on the left hand side and a number on the right hand side.

```<code>'3' + 4 + 5;
</code>```

First '3' + 4 has a string on the left hand side. So it converts the right hand side to a string and concatenates them.

Second '34' + 5 has a string on the left hand side. So it converts the right hand side to a string and concatenates them.

```<code>3 + 4 + '5';
</code>```

First 3 + 4 has a number on both sides, so it adds them. Second 7 + '5' has a string on the right hand side, so it converts the left hand side to a string and concatenates them.

Body:
Why does the + operator consider the number as string when added

Ex :

'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"

Body:
+ will only add two numbers if it has a number on the left hand side and a number on the right hand side.

'3' + 4 + 5;

First '3' + 4 has a string on the left hand side. So it converts the right hand side to a string and concatenates them.

Second '34' + 5 has a string on the left hand side. So it converts the right hand side to a string and concatenates them.

3 + 4 + '5';

First 3 + 4 has a number on both sides, so it adds them. Second 7 + '5' has a string on the right hand side, so it converts the left hand side to a string and concatenates them.


问:
Linked jQuery document not responding
I am currently trying to build a image slider for a website. I have written all of the code required for this to work yet I have having trouble making the jQuery respond or work within the HTML document.

The HTML of the page is:

var currentIndex = 0,
  items = $('.container div'),
  itemsAmt = items.length;

function cycleItems() {
  var item = $('.container div').eq(currentIndex);
  items.hide();
  item.css('display', 'inline-block');
}

var autoSlide = setInterval(function() {
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
}, 3000);

$('.next').click(function() {
  clearInterval(autoSlide);
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
});

$('.prev').click(function() {
  clearInterval(autoSlide);
  currentIndex -= 1;
  if (currentIndex < 0) {
    currentIndex = itemsAmt - 1;
  }
  cycleItems();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  max-width: 400px;
  background-color: black;
  margin: 0 auto;
  text-align: center;
  position: relative;
}

.container div {
  background-color: white;
  width: 100%;
  display: inline-block;
  display: none;
}

.container img {
  width: 100%;
  height: auto;
}

button {
  position: absolute;
}

.next {
  right: 5px;
}

.prev {
  left: 5px;
}</code>```

  <link rel="stylesheet" type="text/css" href="./css/sliderstyle.css">

    <button class="next">Next</button>
    <button class="prev">Previous</button>

```

答:
Use document ready</p>

```<code>// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
});
</code>```

Title: Linked jQuery document not responding

Body:
I am currently trying to build a image slider for a website. I have written all of the code required for this to work yet I have having trouble making the jQuery respond or work within the HTML document.

The HTML of the page is:

var currentIndex = 0,
  items = $('.container div'),
  itemsAmt = items.length;

function cycleItems() {
  var item = $('.container div').eq(currentIndex);
  items.hide();
  item.css('display', 'inline-block');
}

var autoSlide = setInterval(function() {
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
}, 3000);

$('.next').click(function() {
  clearInterval(autoSlide);
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
});

$('.prev').click(function() {
  clearInterval(autoSlide);
  currentIndex -= 1;
  if (currentIndex < 0) {
    currentIndex = itemsAmt - 1;
  }
  cycleItems();
});

.container {
  max-width: 400px;
  background-color: black;
  margin: 0 auto;
  text-align: center;
  position: relative;
}

.container div {
  background-color: white;
  width: 100%;
  display: inline-block;
  display: none;
}

.container img {
  width: 100%;
  height: auto;
}

button {
  position: absolute;
}

.next {
  right: 5px;
}

.prev {
  left: 5px;
}

  <link rel="stylesheet" type="text/css" href="./css/sliderstyle.css">

    <button class="next">Next</button>
    <button class="prev">Previous</button>

Body:
Use document ready

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
});


问:
What is the fastest way to compare two sets in Java?
I am trying to optimize a piece of code which compares elements of list.

Eg.

```<code>public void compare(Set<Record> firstSet, Set<Record> secondSet){
    for(Record firstRecord : firstSet){
        for(Record secondRecord : secondSet){
            // comparing logic
        }
    }
}
</code>```

Please take into account that the number of records in sets will be high.

Thanks

Shekhar

答:
I think method reference with equals method can be used. We assume that the object type without a shadow of a doubt has its own comparison method. Plain and simple example is here,</p>

```<code>Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));

Set<String> set2 = new HashSet<>();
set2.addAll(Arrays.asList("hanks","leo","bale"));

Predicate<Set> pred = set::equals;
boolean result = pred.test(set2);
System.out.println(result);   // true
</code>```

Body:
I am trying to optimize a piece of code which compares elements of list.

Eg.

public void compare(Set<Record> firstSet, Set<Record> secondSet){
    for(Record firstRecord : firstSet){
        for(Record secondRecord : secondSet){
            // comparing logic
        }
    }
}

Please take into account that the number of records in sets will be high.

Thanks

Shekhar

Body:
I think method reference with equals method can be used. We assume that the object type without a shadow of a doubt has its own comparison method. Plain and simple example is here,

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));

Set<String> set2 = new HashSet<>();
set2.addAll(Arrays.asList("hanks","leo","bale"));

Predicate<Set> pred = set::equals;
boolean result = pred.test(set2);
System.out.println(result);   // true


问:
How to send notification between two application
I want to send push notification from Device "A" with Application "A" to Device "B" with application "B" how I can achieve that?

Any help will be appreciated.

can I use firebase with that?

With parse I can define that with number like :

```<code>ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("phone", "1234567890");
ParsePush push = new ParsePush();
push.setQuery(query);
push.sendPushInBackground();
</code>```

how can I achieve that in other cases ?

答: No, because package name will be different for two application. You cannot use same google-services.json file in both application if you are using FCM.</p>

Body:
I want to send push notification from Device "A" with Application "A" to Device "B" with application "B" how I can achieve that?

Any help will be appreciated.

can I use firebase with that?

With parse I can define that with number like :

ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("phone", "1234567890");
ParsePush push = new ParsePush();
push.setQuery(query);
push.sendPushInBackground();

how can I achieve that in other cases ?


问:
Flask doesn't print to console
I'm new to flask, and I'm trying to add print info to debug server side code.
When launch my flask app with debug=True, i can't get any info print to console

I tried to use logging instead, but no success.
So how to debug flask program with console.

```<code>@app.route('/getJSONResult', methods=['GET', 'POST'])
def getJSONResult():

    if request.method == 'POST':
        uut = request.form['uut']
        notes = request.form['notes']
        temperature = request.form['temperature']

        logging.info("enter getJSONReuslt")
        print('enter getJSONReuslt')
        filter_by_query = {k: v for k, v in {
            'uut': uut, 'notes': notes, 'temperature': temperature}.items() if v != ""}
        s = session.query(UUT_TEST_INFO).filter_by(**filter_by_query).first()
        return jsonify(s.serialize)

if __name__ == '__main__':
    app.secret_key = ''.join(random.choice(
        string.ascii_uppercase + string.digits) for x in range(32))
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /qyer HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:51] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:21:58] "POST /getJSONResult HTTP/1.1" 500 -
</code>```

I fixed server side 500 error issue, now request get 200 code, and console displays following info

```<code>$ python project.py
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
WARNING:werkzeug: * Debugger is active!
INFO:werkzeug: * Debugger pin code: 158-624-607
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:33] "GET /qyer HTTP/1.1" 200 -
INFO:root:Enter getJSONResult
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:43] "POST /getJSONResult HTTP/1.1" 200 -
</code>```

Still no info from print command

答:
By default the level for logging is warning. So you won't see a logging message of level DEBUG. To fix this just enable debug logging with the basicConfig() function of the logging module:

```<code>import logging
logging.basicConfig(level=logging.DEBUG)
</code>```

Title: Flask doesn't print to console

Body:
I'm new to flask, and I'm trying to add print info to debug server side code.
When launch my flask app with debug=True, i can't get any info print to console

I tried to use logging instead, but no success.
So how to debug flask program with console.

@app.route('/getJSONResult', methods=['GET', 'POST'])
def getJSONResult():

    if request.method == 'POST':
        uut = request.form['uut']
        notes = request.form['notes']
        temperature = request.form['temperature']

        logging.info("enter getJSONReuslt")
        print('enter getJSONReuslt')
        filter_by_query = {k: v for k, v in {
            'uut': uut, 'notes': notes, 'temperature': temperature}.items() if v != ""}
        s = session.query(UUT_TEST_INFO).filter_by(**filter_by_query).first()
        return jsonify(s.serialize)

if __name__ == '__main__':
    app.secret_key = ''.join(random.choice(
        string.ascii_uppercase + string.digits) for x in range(32))
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /qyer HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:51] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:21:58] "POST /getJSONResult HTTP/1.1" 500 -

I fixed server side 500 error issue, now request get 200 code, and console displays following info

$ python project.py
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
WARNING:werkzeug: * Debugger is active!
INFO:werkzeug: * Debugger pin code: 158-624-607
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:33] "GET /qyer HTTP/1.1" 200 -
INFO:root:Enter getJSONResult
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:43] "POST /getJSONResult HTTP/1.1" 200 -

Still no info from print command

Body:
By default the level for logging is warning. So you won't see a logging message of level DEBUG. To fix this just enable debug logging with the basicConfig() function of the logging module:

import logging
logging.basicConfig(level=logging.DEBUG)


问:
Angular 2 models: interface vs classes
I have a login/registration module and I want to write a model for them.

I would use interfaces, but I need to have one predefined value.

And I was wondering - should I put the predefined out as a constant (it won't be changed, altered) and use interfaces. Or write it as classes (as currently)

Currently, I wrote two separate classes - registration.model.ts, login.model.ts, could I be able to abstract to use only one model? (example: user.model.ts)

Some examples:

```<code>export class LoginUser {
  constructor(
    private email,
    private password,

    // I need to have it, backend expects it to be sent
    private connection = 'Username-Password-Authentication'
  ) { }
}

export class RegistrateUser {
  constructor(
    public name: string,
    public lastName: string,
    public email: string,
    public password: string,

    // I need to have it, backend expects it to be sent
    private connection = 'Username-Password-Authentication'
  ) { }
}
</code>```

答:
just came across your question & was investigating the same thing.

With reference to the Angular 2 Style docs here, the 'guideline' is to NOT implement an interface on the premise that a class alone can:

Act as an interface (if you use the implements keyword instead of the extends keyword)

Be smaller than a class-implementing-interface

As a rule of thumb:

Angular Guidelines > Typescript Guidelines (in the case of Angular 2 projects).

Hope this helps you out! :)

Title: Angular 2 models: interface vs classes

Body:
I have a login/registration module and I want to write a model for them.

I would use interfaces, but I need to have one predefined value.

And I was wondering - should I put the predefined out as a constant (it won't be changed, altered) and use interfaces. Or write it as classes (as currently)

Currently, I wrote two separate classes - registration.model.ts, login.model.ts, could I be able to abstract to use only one model? (example: user.model.ts)

Some examples:

export class LoginUser {
  constructor(
    private email,
    private password,

    // I need to have it, backend expects it to be sent
    private connection = 'Username-Password-Authentication'
  ) { }
}

export class RegistrateUser {
  constructor(
    public name: string,
    public lastName: string,
    public email: string,
    public password: string,

    // I need to have it, backend expects it to be sent
    private connection = 'Username-Password-Authentication'
  ) { }
}


问:
Direct way of telling ifelse to ignore NA
As explained here when the test condition in ifelse(test, yes, no) is NA, the evaluation is also NA. Hence the following returns...

```<code>df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1",
    ifelse(df$b==1, "b==1",
        ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA
</code>```

... instead of the desired

```<code>#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

As suggested by Cath, I can circumvent this problem by formally specifying that the test condition should not include NA:

```<code>ifelse(df$a==1 &  !is.na(df$a), "a==1",
    ifelse(df$b==1 & !is.na(df$b), "b==1",
        ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))
</code>```

However, as akrun also noted, this solution becomes rather lengthy with increasing number of columns.

A workaround would be to first replace all NAs with a value not present in the data.frame (e.g, 2 in this case):

```<code>df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(2, 2, 1, 1, 2, 2),
                 c = c(rep(2, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1",
    ifelse(df_noNA$b==1, "b==1",
        ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs? Or is writing a function for & !is.na the most direct way?

```<code>ignorena <- function(column) {
        column ==1 & !is.na(column)
}
ifelse(ignorena(df$a), "a==1",
    ifelse(ignorena(df$b), "b==1",
        ifelse(ignorena(df$c), "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

答:
We can do this more efficiently without nested ifelse loops.  For the first dataset, we create a logical matrix (!is.na(df)) for non-NA elements, get the column index of the maximum value i.e. TRUE for each row, use that index to get the column names and paste with ==1

```<code>paste0(names(df)[max.col(!is.na(df))], "==1")
#[1] "a==1" "a==1" "b==1" "b==1" "c==1" "c==1"
</code>```

If there are rows with only NAs

```<code>v1 <- names(df)[max.col(!is.na(df)) * NA^!rowSums(!is.na(df))]
i1 <- !is.na(v1)
v1[i1] <- paste0(v1[i1], "==1")
</code>```

and for the second dataset as there are no NAs, we can directly compare with 1 to get a logical matrix, do the same step as before

```<code>paste0(names(df_noNA)[max.col(df_noNA == 1)], "==1")
#[1] "a==1" "a==1" "b==1" "b==1" "c==1" "c==1"
</code>```

Body:
As explained here when the test condition in ifelse(test, yes, no) is NA, the evaluation is also NA. Hence the following returns...

df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1",
    ifelse(df$b==1, "b==1",
        ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA

... instead of the desired

#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

As suggested by Cath, I can circumvent this problem by formally specifying that the test condition should not include NA:

ifelse(df$a==1 &  !is.na(df$a), "a==1",
    ifelse(df$b==1 & !is.na(df$b), "b==1",
        ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))

However, as akrun also noted, this solution becomes rather lengthy with increasing number of columns.

A workaround would be to first replace all NAs with a value not present in the data.frame (e.g, 2 in this case):

df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(2, 2, 1, 1, 2, 2),
                 c = c(rep(2, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1",
    ifelse(df_noNA$b==1, "b==1",
        ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs? Or is writing a function for & !is.na the most direct way?

ignorena <- function(column) {
        column ==1 & !is.na(column)
}
ifelse(ignorena(df$a), "a==1",
    ifelse(ignorena(df$b), "b==1",
        ifelse(ignorena(df$c), "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

Body:
We can do this more efficiently without nested ifelse loops.  For the first dataset, we create a logical matrix (!is.na(df)) for non-NA elements, get the column index of the maximum value i.e. TRUE for each row, use that index to get the column names and paste with ==1

paste0(names(df)[max.col(!is.na(df))], "==1")
#[1] "a==1" "a==1" "b==1" "b==1" "c==1" "c==1"

If there are rows with only NAs

v1 <- names(df)[max.col(!is.na(df)) * NA^!rowSums(!is.na(df))]
i1 <- !is.na(v1)
v1[i1] <- paste0(v1[i1], "==1")

and for the second dataset as there are no NAs, we can directly compare with 1 to get a logical matrix, do the same step as before

paste0(names(df_noNA)[max.col(df_noNA == 1)], "==1")
#[1] "a==1" "a==1" "b==1" "b==1" "c==1" "c==1"


问:
"FullPath cannot be applied" error for nested node_modules in VS2015 CTP6
I'm playing around with MVC6 + Aurelia project in Visual Studio 2015 CTP6, and came across something interesting.

My node_modules is by default in the project root and everything works fine. However, I'd like to keep source tree a bit more organized and moved  node_modules, jspm_modules and related stuff to a subfolder - eg. MyApp\client\node_modules etc.

But now Visual Studio stops loading the project. Here's exception from "VsProjectFault.failure.txt":

```<code>(Inner Exception #1) System.InvalidOperationException: The item metadata "%(FullPath)" cannot be applied to the path "client\node_modules\conventional-changelog\node_modules\lodash.assign\node_modules\lodash._basecreatecallback\node_modules\lodash.bind\node_modules\lodash._createwrapper\node_modules\lodash._basecreatewrapper\node_modules\". C:\Work\xxxxxxxxxx\xxxxxxxxxx.xxx\src\client\node_modules\conventional-changelog\node_modules\lodash.assign\node_modules\lodash._basecreatecallback\node_modules\lodash.bind\node_modules\lodash._createwrapper\node_modules\lodash._basecreatewrapper\node_modules\
   at Microsoft.Build.Shared.ErrorUtilities.ThrowInvalidOperation(String resourceName, Object[] args)
   at Microsoft.Build.Shared.ErrorUtilities.VerifyThrowInvalidOperation(Boolean condition, String resourceName, Object arg0, Object arg1, Object arg2)
   at Microsoft.Build.Shared.FileUtilities.ItemSpecModifiers.GetItemSpecModifier(String currentDirectory, String itemSpec, String definingProjectEscaped, String modifier, String& fullPath)
   ...
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.Utilities.DataflowExtensions.<>c__DisplayClass37`2.<<CreateSelfFilteringTransformBlock>b__38>d__0.MoveNext()
</code>```

Apparently the problem is in node_modules recursive path being too long - and there's bug #6960 in Node tracker

Node needs an alternative approach to endless, recursively nested
  node_modules folders on Windows. Most Windows tools, utilities and
  shells cannot handle file and folder paths longer than 260 characters
  at most.

...which seems like closed as won't fix to me:

Node isn't going to change, so this isn't really a Node issue. The
  problem is not with the module loading semantics, but with the module
  installation semantics. (The two are related, but not identical.)

But then I don't understand how come the project was loading in the first place, because some paths are definitely over 260 symbols even if node_modules is under the project root!

Is there some setting in config or something which helps Visual Studio 2015 to load the project with node_modules, what's going on?

答:
VS2015 / project.json Build + VS2017 / CSProj build

http://dan.clarke.name/2017/02/including-excluding-files-from-build-with-vs2017-and-net-core/

Just change to (inside the "Project" tag):

```<code><ItemGroup>
    <Compile Remove="[ClientAppRoot]\node_modules\**" />
    <Content Remove="[ClientAppRoot]\node_modules\**" />
    <EmbeddedResource Remove="[ClientAppRoot]\node_modules\**" />
    <None Remove="[ClientAppRoot]\node_modules\**" />
</ItemGroup>
</code>```

Body:
I'm playing around with MVC6 + Aurelia project in Visual Studio 2015 CTP6, and came across something interesting.

My node_modules is by default in the project root and everything works fine. However, I'd like to keep source tree a bit more organized and moved  node_modules, jspm_modules and related stuff to a subfolder - eg. MyApp\client\node_modules etc.

But now Visual Studio stops loading the project. Here's exception from "VsProjectFault.failure.txt":

(Inner Exception #1) System.InvalidOperationException: The item metadata "%(FullPath)" cannot be applied to the path "client\node_modules\conventional-changelog\node_modules\lodash.assign\node_modules\lodash._basecreatecallback\node_modules\lodash.bind\node_modules\lodash._createwrapper\node_modules\lodash._basecreatewrapper\node_modules\". C:\Work\xxxxxxxxxx\xxxxxxxxxx.xxx\src\client\node_modules\conventional-changelog\node_modules\lodash.assign\node_modules\lodash._basecreatecallback\node_modules\lodash.bind\node_modules\lodash._createwrapper\node_modules\lodash._basecreatewrapper\node_modules\
   at Microsoft.Build.Shared.ErrorUtilities.ThrowInvalidOperation(String resourceName, Object[] args)
   at Microsoft.Build.Shared.ErrorUtilities.VerifyThrowInvalidOperation(Boolean condition, String resourceName, Object arg0, Object arg1, Object arg2)
   at Microsoft.Build.Shared.FileUtilities.ItemSpecModifiers.GetItemSpecModifier(String currentDirectory, String itemSpec, String definingProjectEscaped, String modifier, String& fullPath)
   ...
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ProjectSystem.Utilities.DataflowExtensions.<>c__DisplayClass37`2.<<CreateSelfFilteringTransformBlock>b__38>d__0.MoveNext()

Apparently the problem is in node_modules recursive path being too long - and there's bug #6960 in Node tracker

Node needs an alternative approach to endless, recursively nested
  node_modules folders on Windows. Most Windows tools, utilities and
  shells cannot handle file and folder paths longer than 260 characters
  at most.

...which seems like closed as won't fix to me:

Node isn't going to change, so this isn't really a Node issue. The
  problem is not with the module loading semantics, but with the module
  installation semantics. (The two are related, but not identical.)

But then I don't understand how come the project was loading in the first place, because some paths are definitely over 260 symbols even if node_modules is under the project root!

Is there some setting in config or something which helps Visual Studio 2015 to load the project with node_modules, what's going on?

Body:
VS2015 / project.json Build + VS2017 / CSProj build

http://dan.clarke.name/2017/02/including-excluding-files-from-build-with-vs2017-and-net-core/

Just change to (inside the "Project" tag):

<ItemGroup>
    <Compile Remove="[ClientAppRoot]\node_modules\**" />
    <Content Remove="[ClientAppRoot]\node_modules\**" />
    <EmbeddedResource Remove="[ClientAppRoot]\node_modules\**" />
    <None Remove="[ClientAppRoot]\node_modules\**" />
</ItemGroup>


问:
React MaterialUI Card: how to change Card's class on expand? -> Custom React component
There are 20 cards on the page.

MaterialUI Card has onExpandChange property where I can define an action like this:

```<code><Card expandable={true} onExpandChange={this.clickHandle}>
</code>```

In this action I can easily know if the clicked card is expanded or not, because the callback function is defined like this in the MaterialUI: function(newExpandedState: boolean) => void

```<code>clickHandle = (newExpandedState: boolean) => {
    //do something
}
</code>```

Now I would like to change card's class, for example, give it class expanded when newExpandedState is true.

The problem is that I don't know how to tell this function which card has been expanded. Things like onExpandChange={this.clickHandle(newState, 'card1')} don't work. I have 20 cards on the page and I don't know which one should get expanded class. Any ideas how to do this?

答:
One way to do it is to wrap the material-ui's card with your own custom card and add a state to it:
import React from 'react';
import { Card } from 'material-ui';

```<code>class MyCustomCard extends React.Component {
  state = {
    expanded: null
  }

  toggleExpanded = () => {
    this.setState((state) => ({
      expanded: !state.expanded
    }))
  }

  render() {
    return <Card expandable expanded={this.state.expanded} onExpandChange={this.toggleExpanded}>
  }
}
</code>```

Then you can use it like this:

```<code>import React from 'react';
import Card from '../MyCustomCard';

class App extends React.Component {
  ...

  render() {
    return (
      <div>
        <Card />
        <Card />
        <Card />
        <Card />
        <Card />
        ...
      </div>
    )
  }
}
</code>```

Body:
There are 20 cards on the page.

MaterialUI Card has onExpandChange property where I can define an action like this:

<Card expandable={true} onExpandChange={this.clickHandle}>

In this action I can easily know if the clicked card is expanded or not, because the callback function is defined like this in the MaterialUI: function(newExpandedState: boolean) => void

clickHandle = (newExpandedState: boolean) => {
    //do something
}

Now I would like to change card's class, for example, give it class expanded when newExpandedState is true.

The problem is that I don't know how to tell this function which card has been expanded. Things like onExpandChange={this.clickHandle(newState, 'card1')} don't work. I have 20 cards on the page and I don't know which one should get expanded class. Any ideas how to do this?

Body:
One way to do it is to wrap the material-ui's card with your own custom card and add a state to it:
import React from 'react';
import { Card } from 'material-ui';

class MyCustomCard extends React.Component {
  state = {
    expanded: null
  }

  toggleExpanded = () => {
    this.setState((state) => ({
      expanded: !state.expanded
    }))
  }

  render() {
    return <Card expandable expanded={this.state.expanded} onExpandChange={this.toggleExpanded}>
  }
}

Then you can use it like this:

import React from 'react';
import Card from '../MyCustomCard';

class App extends React.Component {
  ...

  render() {
    return (
      <div>
        <Card />
        <Card />
        <Card />
        <Card />
        <Card />
        ...
      </div>
    )
  }
}


问:
Handling special characters in json_encode
In my database, there are many special characters like (İstanbul, Yeşilköy, Atatürk and more).

when I directly fetch these data from the database all working fine. Means data remain original but problem occur when I convert these data to JSON using json_encode().

After encoding all these data converted to some strange characters like
 ?stanbul, Bak?rköy...

But after decodeing (using json_decode) I need the original string which was before encoding(json_encode).

I tried many solutions provided on the web to solve the problem but none of them is fully working in my case.

some solutions I tried-

$item =   utf8_encode($item);

$item = html_entity_decode($item, ENT_COMPAT, 'UTF-8');

http://www.php.net/manual/en/function.json-encode.php

I also tried a library available on github (https://github.com/neitanod/forceutf8)

If not possible to get the original string atleast there should not be any ? like thing(remove these things).

Suggest me something to solve the issue.

答:
Use mysqli_set_charset(connection,charset); before mysqli_query();

Example:

```<code>mysqli_set_charset( $CONNECTION, "utf8" );

$result_query = mysqli_query( $CONNECTION, $query );
</code>```

Body:
Use mysqli_set_charset(connection,charset); before mysqli_query();

Example:

mysqli_set_charset( $CONNECTION, "utf8" );

$result_query = mysqli_query( $CONNECTION, $query );


问:
Draw a curve line going through the blobs in OpenCV C++
I am trying to draw a line that goes through the given blobs. The following is a given example

I want a curve line that goes through multiple blobs in horizontal direction as shown below.

答:
Just as example:

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

img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
(_, contours, _) = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# biggest area
target = max(contours, key=lambda x: cv2.contourArea(x))
cv2.drawContours(img, [target], -1, [0, 0, 255], -1) # debug
# just example of fitting
x = target[:, :, 0].flatten()
y = target[:, :, 1].flatten()
poly = np.poly1d(np.polyfit(x, y, 5))
for _x in range(min(x), max(x), 5): # too lazy for line/curve :)
    cv2.circle(img, (_x, int(poly(_x))), 3, [0, 255, 0])

cv2.imshow('result', img)
cv2.waitKey(0)
</code>```

Body:
Just as example:

import cv2
import numpy as np

img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
(_, contours, _) = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# biggest area
target = max(contours, key=lambda x: cv2.contourArea(x))
cv2.drawContours(img, [target], -1, [0, 0, 255], -1) # debug
# just example of fitting
x = target[:, :, 0].flatten()
y = target[:, :, 1].flatten()
poly = np.poly1d(np.polyfit(x, y, 5))
for _x in range(min(x), max(x), 5): # too lazy for line/curve :)
    cv2.circle(img, (_x, int(poly(_x))), 3, [0, 255, 0])

cv2.imshow('result', img)
cv2.waitKey(0)


问:
Correct way of implementing Finalize and Dispose(When parent class implements IDisposable)
I was implementing Finalize and Dispose in my classes, I implemented IDisposable on my parent class and override the Dispose(bool) overload in my child classes. I was not sure

whether to use a duplicate isDisposed variable(as its already there in base class) or not?

Whether to implement a finalizer in child class too or not?

Both these things are done in example given here -

http://guides.brucejmack.biz/CodeRules/FxCop/Docs/Rules/Usage/DisposeMethodsShouldCallBaseClassDispose.html

Whereas example in this MSDN article doesn't have any of these two -
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

whereas this example in MSDN is not complete -
http://msdn.microsoft.com/en-us/library/ms182330.aspx

答:
Only implement a finalizer if an object holds information about stuff needing cleanup, and this information is in some form other than Object references to other objects needing cleanup (e.g. a file handle stored as an Int32).  If a class implements a finalizer, it should not hold strong Object references to any other objects which are not required for cleanup.  If it would hold other references, the portion responsible for cleanup should be split off into its own object with a finalizer, and the main object should hold a reference to that.  The main object should then not have a finalizer.

Derived classes should only have finalizers if the purpose of the base class was to support one.  If the purpose of a class doesn't center around a finalizer, there's not much point allowing a derived class to add one, since derived classes almost certainly shouldn't (even if they need to add unmanaged resources, they should put the resources in their own class and just hold a reference to it).


问:
Unable to start the deployed spark job server error org.slf4j.LoggerFactory not found
I am trying to use the spark job server on a cluster on CDH 5.11, spark version 1.6.0
When I try to start the spark jobserver on the deployed machine I get this error log

```<code>[ERROR] [06/02/2017 15:30:14.966] [JobServer-akka.actor.default-dispatcher-3] [ActorSystem(JobServer)] Uncaught error from thread [JobServer-akka.actor.default-dispatcher-3] shutting down JVM since 'akka.jvm-ex$
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at akka.event.slf4j.Logger$.apply(Slf4jLogger.scala:30)
at akka.event.slf4j.SLF4JLogging$class.log(Slf4jLogger.scala:19)
at akka.event.slf4j.Slf4jLogger.log$lzycompute(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger.log(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger$$anonfun$receive$1.applyOrElse(Slf4jLogger.scala:80)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
at akka.actor.ActorCell.invoke(ActorCell.scala:456)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
at akka.dispatch.Mailbox.run(Mailbox.scala:219)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 14 more

Uncaught error from thread [JobServer-akka.actor.default-dispatcher-3] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[JobServer]
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at akka.event.slf4j.Logger$.apply(Slf4jLogger.scala:30)
at akka.event.slf4j.SLF4JLogging$class.log(Slf4jLogger.scala:19)
at akka.event.slf4j.Slf4jLogger.log$lzycompute(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger.log(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger$$anonfun$receive$1.applyOrElse(Slf4jLogger.scala:80)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
at akka.actor.ActorCell.invoke(ActorCell.scala:456)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
at akka.dispatch.Mailbox.run(Mailbox.scala:219)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 14 more
</code>```

Did anybody faced the same issue or provide some help ?

答:
Few things here!!

How are you deploying?
The problem seems to be that some how the SLF4J jar is excluded from SJS class path. It is possible that there is a version conflict on it.

And check the spark dependencies in the UI. (and find SLF4J there!!)

You have to check scala version; spark version and the Spark-Job-Server versions if they're conflicting!!!

In your case, for spark version 1.6.0; the selected scala version should be 2.10.4. (not any other versions like 2.11 or 2.12)

Body:
I am trying to use the spark job server on a cluster on CDH 5.11, spark version 1.6.0
When I try to start the spark jobserver on the deployed machine I get this error log

[ERROR] [06/02/2017 15:30:14.966] [JobServer-akka.actor.default-dispatcher-3] [ActorSystem(JobServer)] Uncaught error from thread [JobServer-akka.actor.default-dispatcher-3] shutting down JVM since 'akka.jvm-ex$
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at akka.event.slf4j.Logger$.apply(Slf4jLogger.scala:30)
at akka.event.slf4j.SLF4JLogging$class.log(Slf4jLogger.scala:19)
at akka.event.slf4j.Slf4jLogger.log$lzycompute(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger.log(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger$$anonfun$receive$1.applyOrElse(Slf4jLogger.scala:80)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
at akka.actor.ActorCell.invoke(ActorCell.scala:456)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
at akka.dispatch.Mailbox.run(Mailbox.scala:219)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 14 more

Uncaught error from thread [JobServer-akka.actor.default-dispatcher-3] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[JobServer]
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at akka.event.slf4j.Logger$.apply(Slf4jLogger.scala:30)
at akka.event.slf4j.SLF4JLogging$class.log(Slf4jLogger.scala:19)
at akka.event.slf4j.Slf4jLogger.log$lzycompute(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger.log(Slf4jLogger.scala:54)
at akka.event.slf4j.Slf4jLogger$$anonfun$receive$1.applyOrElse(Slf4jLogger.scala:80)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
at akka.actor.ActorCell.invoke(ActorCell.scala:456)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
at akka.dispatch.Mailbox.run(Mailbox.scala:219)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 14 more

Did anybody faced the same issue or provide some help ?


问:
If-else statement giving error
normal if else statement is working but optimized if else not working

calVal == "0" ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString();

答:
Are you trying to assign calVal? If yes, try:

```<code>calVal = ((calVal == "0") ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString());
</code>```

The shorthand if statement if correct, but the compiler complains that you aren't doing anything.

Title: If-else statement giving error

Body:
Are you trying to assign calVal? If yes, try:

calVal = ((calVal == "0") ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString());

The shorthand if statement if correct, but the compiler complains that you aren't doing anything.