问:
Retrieving data does not import more than one value for each person using SOAP API
I have an issue where I want to retrieve data using SOAP API. In my main block, I create a DataTable called ResultsTable which I create columns for. I then loop through a list of LocalAPIKeys and for each key I execute this function:

```<code>private static DataTable GetPayrollV2(DataTable ResultsTable, string ServerUrl, string LocalAPIKey)
    {
           // Setting up to retrieve data from SOAP API. Removed code.
           // Get response and return it
           XmlDocument xmlResult = new XmlDocument();
           try
           {
               using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
               {
               StreamReader reader = new StreamReader(response.GetResponseStream());
               result = reader.ReadToEnd();
               reader.Close();
               }
               xmlResult.LoadXml(result);
           }
           catch (Exception e)
           {
               Console.WriteLine(e.Message);
           }

           XmlNodeList also_calledList = xmlResult.GetElementsByTagName("return");
           XmlNode also_calledElement = also_calledList[0];
           XmlNodeList titleList = also_calledElement.ChildNodes;

           foreach (XmlNode titleNode in titleList)
           {
               if (titleNode != null)
               {
                   DataRow row = ResultsTable.NewRow();
                   row["StoreKey"] = titleNode["costCentre"].InnerText;  // Error after edit, System.NullReferenceException
                   row["EmployeeName"] = titleNode["empName"].InnerText;
                   row["DateKey"] = titleNode["date"].InnerText;
                   row["Incheck"] = titleNode["in"].InnerText;
                   row["Outcheck"] = titleNode["out"].InnerText;
                   ResultsTable.Rows.Add(row);
                   return ResultsTable;
               }
           }
        return ResultsTable;
     }
</code>```

which I simply want to add a row to the existing DataTable (later on in the code, I copy the whole DataTable using SqlBulkCopy into a SQL Database).

My issue is that when I run my example Query in SOAP UI I get the following output:

```<code><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="https://serverURL">
   <SOAP-ENV:Body>
      <ns1:wsdlGetValuesResponse xmlns:ns1="uri:Values">
         <return xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="tns:PayrollV2[14]">
            <item xsi:type="tns:PayrollV2">
               <empName xsi:type="xsd:string">Doe, John</empName>
               <badgeNo xsi:type="xsd:string">3761</badgeNo>
               <date xsi:type="xsd:date">2017-03-30</date>
               <in xsi:type="xsd:string">18:15</in>
               <out xsi:type="xsd:string">20:00</out>
               <costCentre xsi:type="xsd:string">6002</costCentre>
            </item>
            <item xsi:type="tns:PayrollV2">
               <empName xsi:type="xsd:string">Doe, John</empName>
               <badgeNo xsi:type="xsd:string">3761</badgeNo>
               <date xsi:type="xsd:date">2017-03-30</date>
               <in xsi:type="xsd:string">20:00</in>
               <out xsi:type="xsd:string">21:00</out>
               <costCentre xsi:type="xsd:string">6002</costCentre>
            </item>
            <item xsi:type="tns:PayrollV2">
               <empName xsi:type="xsd:string">Doe, John</empName>
               <badgeNo xsi:type="xsd:string">3761</badgeNo>
               <date xsi:type="xsd:date">2017-03-30</date>
               <in xsi:type="xsd:string">21:15</in>
               <out xsi:type="xsd:string">22:00</out>
               <costCentre xsi:type="xsd:string">6002</costCentre>
            </item>
         </return>
      </ns1:wsdlGetValuesResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

but when I've ran my script, there are no errors however the resulting table in SQL has only one row of data of John Doe, the entry from which he checked in 18:15 and out 20:00 of the thirtiest of march, the rest are gone.

The Table ResultsTable also only contain 1 entry of each name. Thus, even if people have worked on both the 30:th and the 31:st, only one entry is returned in total.

Does anyone have any idea why I wont get the whole output from SOAP UI?

EDIT

I altered the code by modifying:

```<code>XmlNodeList also_calledList = xmlResult.GetElementsByTagName("return");
</code>```

into

```<code> XmlNodeList also_calledList = xmlResult.GetElementsByTagName("item");
</code>```

This change appeared to pan out OK. When I inspect also_calledList it seems to return the values I want, i.e. multiple incheck times for the same employee and date.

This however caused an error which caused the program to not be able to proceed about a NullReference at the row which I have commented in the code.

EDIT 2

I noticed that the titleList has the following appearence when I inspect it using Quick View:

From further testing I've noticed that only the XmlElement [0] is returned to the DataTable. How can I "Catch" the data of the remaining 14?

I tried to do:

```<code>foreach (XmlElement _ in titleList)
{
    foreach (XmlNode titleNode in titleList)
    {
        if (titleNode != null && titleNode.InnerText != null)
        {
           DataRow row = ResultsTable.NewRow();
           row["StoreKey"] = titleNode["costCentre"].InnerText;
           row["EmployeeName"] = titleNode["empName"].InnerText;
           row["DateKey"] = titleNode["date"].InnerText;
           row["Incheck"] = titleNode["in"].InnerText;
           row["Outcheck"] = titleNode["out"].InnerText;
           ResultsTable.Rows.Add(row);
           return ResultsTable;
          }
    }
}
</code>```

but that returned the same output.

I've also tried to use the original Query, but loop using

```<code>  foreach (XmlNode titleNode in titleList[1])
  {
         \\ same after this
  }
</code>```

but this returned an empty data table. My thought was to be able to iterate using some kind of recursion of ... in titleList[i] where i would be a loop from 0 to the amount of elements returned.

答:
I wrote a simple program to parse your Xml

```<code>public static PayrollItem[] GetPayrollItems(XmlDocument xmlDoc)
{
    var items = new List<PayrollItem>();

    var node = xmlDoc.FirstChild; //SOAP-ENV:Envelope
    if (node != null)
    {
        node = node.FirstChild; //SOAP-ENV:Body
        if (node != null)
        {
            node = node.FirstChild; //ns1:wsdlGetValuesResponse
            if (node != null)
            {
                node = node.FirstChild;  //return

                if (node != null)
                {
                    int count = node.ChildNodes.Count;

                    foreach (XmlNode nodeItem in node.ChildNodes)
                    {
                        PayrollItem item = new PayrollItem();

                        item.EmpName = nodeItem["empName"].InnerText;
                        item.BadgeNo = nodeItem["badgeNo"].InnerText;
                        item.CostCentre = nodeItem["costCentre"].InnerText;
                        item.Date = nodeItem["date"].InnerText;
                        item.In = nodeItem["in"].InnerText;
                        item.Out = nodeItem["out"].InnerText;

                        items.Add(item);
                    }
                }
            }
        }
    }

    return items.ToArray();
}
</code>```

Here PayrollItem is a simple data Class to hold the values

```<code>class PayrollItem
{
    public string EmpName { get; set; }
    public string BadgeNo { get; set; }
    public string Date { get; set; }
    public string In { get; set; }
    public string Out { get; set; }
    public string CostCentre { get; set; }
}
</code>```

Once you have your Xml converted to an object, you can use this object to populate your DataRow

The logic in the program is very simple. I just used the .FirstChild property to navigate the Xml to reach the relevant node.

Currently all the elements are treated as string. You can change it to appropriate data type and use it in subsequent processing.

Body:
I have an issue where I want to retrieve data using SOAP API. In my main block, I create a DataTable called ResultsTable which I create columns for. I then loop through a list of LocalAPIKeys and for each key I execute this function:

private static DataTable GetPayrollV2(DataTable ResultsTable, string ServerUrl, string LocalAPIKey)
    {
           // Setting up to retrieve data from SOAP API. Removed code.
           // Get response and return it
           XmlDocument xmlResult = new XmlDocument();
           try
           {
               using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
               {
               StreamReader reader = new StreamReader(response.GetResponseStream());
               result = reader.ReadToEnd();
               reader.Close();
               }
               xmlResult.LoadXml(result);
           }
           catch (Exception e)
           {
               Console.WriteLine(e.Message);
           }

           XmlNodeList also_calledList = xmlResult.GetElementsByTagName("return");
           XmlNode also_calledElement = also_calledList[0];
           XmlNodeList titleList = also_calledElement.ChildNodes;

           foreach (XmlNode titleNode in titleList)
           {
               if (titleNode != null)
               {
                   DataRow row = ResultsTable.NewRow();
                   row["StoreKey"] = titleNode["costCentre"].InnerText;  // Error after edit, System.NullReferenceException
                   row["EmployeeName"] = titleNode["empName"].InnerText;
                   row["DateKey"] = titleNode["date"].InnerText;
                   row["Incheck"] = titleNode["in"].InnerText;
                   row["Outcheck"] = titleNode["out"].InnerText;
                   ResultsTable.Rows.Add(row);
                   return ResultsTable;
               }
           }
        return ResultsTable;
     }

which I simply want to add a row to the existing DataTable (later on in the code, I copy the whole DataTable using SqlBulkCopy into a SQL Database).

My issue is that when I run my example Query in SOAP UI I get the following output:

<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="https://serverURL">
   <SOAP-ENV:Body>
      <ns1:wsdlGetValuesResponse xmlns:ns1="uri:Values">
         <return xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="tns:PayrollV2[14]">
            <item xsi:type="tns:PayrollV2">
               <empName xsi:type="xsd:string">Doe, John</empName>
               <badgeNo xsi:type="xsd:string">3761</badgeNo>
               <date xsi:type="xsd:date">2017-03-30</date>
               <in xsi:type="xsd:string">18:15</in>
               <out xsi:type="xsd:string">20:00</out>
               <costCentre xsi:type="xsd:string">6002</costCentre>
            </item>
            <item xsi:type="tns:PayrollV2">
               <empName xsi:type="xsd:string">Doe, John</empName>
               <badgeNo xsi:type="xsd:string">3761</badgeNo>
               <date xsi:type="xsd:date">2017-03-30</date>
               <in xsi:type="xsd:string">20:00</in>
               <out xsi:type="xsd:string">21:00</out>
               <costCentre xsi:type="xsd:string">6002</costCentre>
            </item>
            <item xsi:type="tns:PayrollV2">
               <empName xsi:type="xsd:string">Doe, John</empName>
               <badgeNo xsi:type="xsd:string">3761</badgeNo>
               <date xsi:type="xsd:date">2017-03-30</date>
               <in xsi:type="xsd:string">21:15</in>
               <out xsi:type="xsd:string">22:00</out>
               <costCentre xsi:type="xsd:string">6002</costCentre>
            </item>
         </return>
      </ns1:wsdlGetValuesResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

but when I've ran my script, there are no errors however the resulting table in SQL has only one row of data of John Doe, the entry from which he checked in 18:15 and out 20:00 of the thirtiest of march, the rest are gone.

The Table ResultsTable also only contain 1 entry of each name. Thus, even if people have worked on both the 30:th and the 31:st, only one entry is returned in total.

Does anyone have any idea why I wont get the whole output from SOAP UI?

EDIT

I altered the code by modifying:

XmlNodeList also_calledList = xmlResult.GetElementsByTagName("return");

into

 XmlNodeList also_calledList = xmlResult.GetElementsByTagName("item");

This change appeared to pan out OK. When I inspect also_calledList it seems to return the values I want, i.e. multiple incheck times for the same employee and date.

This however caused an error which caused the program to not be able to proceed about a NullReference at the row which I have commented in the code.

EDIT 2

I noticed that the titleList has the following appearence when I inspect it using Quick View:

From further testing I've noticed that only the XmlElement [0] is returned to the DataTable. How can I "Catch" the data of the remaining 14?

I tried to do:

foreach (XmlElement _ in titleList)
{
    foreach (XmlNode titleNode in titleList)
    {
        if (titleNode != null && titleNode.InnerText != null)
        {
           DataRow row = ResultsTable.NewRow();
           row["StoreKey"] = titleNode["costCentre"].InnerText;
           row["EmployeeName"] = titleNode["empName"].InnerText;
           row["DateKey"] = titleNode["date"].InnerText;
           row["Incheck"] = titleNode["in"].InnerText;
           row["Outcheck"] = titleNode["out"].InnerText;
           ResultsTable.Rows.Add(row);
           return ResultsTable;
          }
    }
}

but that returned the same output.

I've also tried to use the original Query, but loop using

  foreach (XmlNode titleNode in titleList[1])
  {
         \\ same after this
  }

but this returned an empty data table. My thought was to be able to iterate using some kind of recursion of ... in titleList[i] where i would be a loop from 0 to the amount of elements returned.

Body:
I wrote a simple program to parse your Xml

public static PayrollItem[] GetPayrollItems(XmlDocument xmlDoc)
{
    var items = new List<PayrollItem>();

    var node = xmlDoc.FirstChild; //SOAP-ENV:Envelope
    if (node != null)
    {
        node = node.FirstChild; //SOAP-ENV:Body
        if (node != null)
        {
            node = node.FirstChild; //ns1:wsdlGetValuesResponse
            if (node != null)
            {
                node = node.FirstChild;  //return

                if (node != null)
                {
                    int count = node.ChildNodes.Count;

                    foreach (XmlNode nodeItem in node.ChildNodes)
                    {
                        PayrollItem item = new PayrollItem();

                        item.EmpName = nodeItem["empName"].InnerText;
                        item.BadgeNo = nodeItem["badgeNo"].InnerText;
                        item.CostCentre = nodeItem["costCentre"].InnerText;
                        item.Date = nodeItem["date"].InnerText;
                        item.In = nodeItem["in"].InnerText;
                        item.Out = nodeItem["out"].InnerText;

                        items.Add(item);
                    }
                }
            }
        }
    }

    return items.ToArray();
}

Here PayrollItem is a simple data Class to hold the values

class PayrollItem
{
    public string EmpName { get; set; }
    public string BadgeNo { get; set; }
    public string Date { get; set; }
    public string In { get; set; }
    public string Out { get; set; }
    public string CostCentre { get; set; }
}

Once you have your Xml converted to an object, you can use this object to populate your DataRow

The logic in the program is very simple. I just used the .FirstChild property to navigate the Xml to reach the relevant node.

Currently all the elements are treated as string. You can change it to appropriate data type and use it in subsequent processing.


来源: stackexchange

问:
Powershell- compare files and take action
I'm attempting to create a powershell script to compare two IP addresses out of two different text files then take an action base on if they match or they don't match. See below

```<code>(Invoke-WebRequest ifconfig.me/ip).content | Out-File "C:\test\test2.txt"
$ErrorActionPreference = "Stop"
$File = "C:\test\test.txt"
$File2 = "C:\test\test2.txt"

Compare-Object -ReferenceObject (Get-Content $File2) -DifferenceObject (Get-
Content $File) -IncludeEqual
</code>```

If the two files match I obviously get a ==, or an => if they don't match. I'm not sure how to use == or => as a variable to continue the rest of the script. Any help or recommendations are greatly appreciated.

答:
You can assign a variable to the Compare-Object result. When I did a quick test it seems like nothing is returned if the two objects matched. So you would have to check for $null in the value of the variable.

```<code>$a = Compare-Object -ReferenceObject "abc" -DifferenceObject "abc"
if($a -ne $null){continue working here}else{do other action here}
</code>```

For more info check out:
https://ss64.com/ps/compare-object.html

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to create a powershell script to compare two IP addresses out of two different text files then take an action base on if they match or they don't match. See below

(Invoke-WebRequest ifconfig.me/ip).content | Out-File "C:\test\test2.txt"
$ErrorActionPreference = "Stop"
$File = "C:\test\test.txt"
$File2 = "C:\test\test2.txt"

Compare-Object -ReferenceObject (Get-Content $File2) -DifferenceObject (Get-
Content $File) -IncludeEqual

If the two files match I obviously get a ==, or an => if they don't match. I'm not sure how to use == or => as a variable to continue the rest of the script. Any help or recommendations are greatly appreciated.

Body:
You can assign a variable to the Compare-Object result. When I did a quick test it seems like nothing is returned if the two objects matched. So you would have to check for $null in the value of the variable.

$a = Compare-Object -ReferenceObject "abc" -DifferenceObject "abc"
if($a -ne $null){continue working here}else{do other action here}

For more info check out:
https://ss64.com/ps/compare-object.html


问:
SimpleModal content isn't loading in IE8 when CSS overflow is set to "scroll" or "auto"
I'm using simplemodal on a website I'm developing.  Everything was working fine across all browsers until I added "overflow: auto;" to my simplemodal CSS as such:

```<code>#simplemodal-container {height:90%; width:80%; color:#fff; overflow:
</code>```

auto;}

I get the scrollbars when needed in FF, Safari, and Chrome just fine, but when I look at it in IE8 (haven't tried IE6 or IE7), most if not all of the content of the modal is missing.  It appears to be spinning as though it's waiting for the server, but nothing happens.

I've looked everywhere online for an answer to this issue, but haven't been able to find anyone else who's having the same issue.

Please let me know if you need anything else from me.

Thank you in advance!

答:
Pekka, thanks for taking a look.  I was sure that it wasn't the javascript, because one of the buttons, (resume) links to a simple html doc with a table and that wasn't even showing up.

But I think I've figured it out!

In the CSS, there were also some opacity settings, which I pretty much copied over from the simplemodal website.  But one of the settings was an IE workaround that was throwing errors whenever I validated the page.  So about 5 minutes ago, I thought, "hm.  I wonder if I get rid of those opacity settings if that might do the trick."  I wasn't really using them anyway - I had set the opacity of my modal window to 100%.  So I just got rid of the settings, and now it works in IE.  Go figure.

On the "images" modal, my thumbnails are getting cut off in IE, so I do have one more thing to figure out, but at least it's showing up now!

HOO-RAY.

ContentLicense: CC BY-SA 2.5

Body:
I'm using simplemodal on a website I'm developing.  Everything was working fine across all browsers until I added "overflow: auto;" to my simplemodal CSS as such:

#simplemodal-container {height:90%; width:80%; color:#fff; overflow:

auto;}

I get the scrollbars when needed in FF, Safari, and Chrome just fine, but when I look at it in IE8 (haven't tried IE6 or IE7), most if not all of the content of the modal is missing.  It appears to be spinning as though it's waiting for the server, but nothing happens.

I've looked everywhere online for an answer to this issue, but haven't been able to find anyone else who's having the same issue.

Please let me know if you need anything else from me.

Thank you in advance!


问:
Dealing with polymorphic association: is there such a thing as "too many" LEFT JOIN?
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

```<code>SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.
</code>```

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you

答:
Yes, you can use the product_type (so called "discriminator") to help the DBMS produce a better query plan and avoid unnecessary joins. You can do something like this:

```<code>SELECT
    *
FROM
    Product
    LEFT JOIN Product_A
        ON product_type = 1 -- Or whatever is the actual value in your case.
        AND Product.product_id = Product_A.product_id
    LEFT JOIN Product_B
        ON product_type = 2
        AND Product.product_id = Product_B.product_id
    LEFT JOIN Product_C
        ON product_type = 3
        AND Product.product_id = Product_C.product_id
    LEFT JOIN Product_D
        ON product_type = 4
        AND Product.product_id = Product_D.product_id
WHERE
    Product.product_id = 1337
</code>```

The DBMS should be able to short-circuit all "branches" that don't have the right product_type and avoid the corresponding joins.1

Whether this is actually better than using a separate query to fetch product_type and then choosing the corresponding "special" query (and incurring another database round-trip) - that's something you should test. As always, test on the representative amounts of data!

1 At least Oracle or SQL Server would do that - please check for MySQL!

Body:
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you

Body:
Yes, you can use the product_type (so called "discriminator") to help the DBMS produce a better query plan and avoid unnecessary joins. You can do something like this:

SELECT
    *
FROM
    Product
    LEFT JOIN Product_A
        ON product_type = 1 -- Or whatever is the actual value in your case.
        AND Product.product_id = Product_A.product_id
    LEFT JOIN Product_B
        ON product_type = 2
        AND Product.product_id = Product_B.product_id
    LEFT JOIN Product_C
        ON product_type = 3
        AND Product.product_id = Product_C.product_id
    LEFT JOIN Product_D
        ON product_type = 4
        AND Product.product_id = Product_D.product_id
WHERE
    Product.product_id = 1337

The DBMS should be able to short-circuit all "branches" that don't have the right product_type and avoid the corresponding joins.1

Whether this is actually better than using a separate query to fetch product_type and then choosing the corresponding "special" query (and incurring another database round-trip) - that's something you should test. As always, test on the representative amounts of data!

1 At least Oracle or SQL Server would do that - please check for MySQL!


问:
after submit popup show again
I have this form which is linked to post php

```<code><form action="newsletter.php" method="post" >
    <input type="text" name="name" id="wd1_nlpopup_name" placeholder="Name" value="" class="textinput" tabindex="500">
    <input type="text" name="email" id="wd1_nlpopup_mail" placeholder="Your email" value="" class="textinput" tabindex="501">
    <input type="submit" name="submit" class="btn btn-orange btn-large" value="Submit" id="submit">
</form>
</code>```

and this javascript file which popup the form

```<code>jQuery(document).ready(function($){
    var wd1_nlpopup_expires = $("#wd1_nlpopup").data("expires");
    var wd1_nlpopup_delay = $("#wd1_nlpopup").data("delay") * 1000;

    $('#wd1_nlpopup_close').on('click', function(e){
        $.cookie('wd1_nlpopup', 'closed', { expires: wd1_nlpopup_expires, path: '/' });
        $('#wd1_nlpopup,#wd1_nlpopup_overlay').fadeOut(200);
        e.preventDefault();
    });

        $('#submit').on('submit', function(e){
        $.cookie('wd1_nlpopup', 'submited', { expires: wd1_nlpopup_expires, path: '/' });
        $('#wd1_nlpopup,#wd1_nlpopup_overlay').fadeOut(200);
        e.preventDefault();
    });

    if($.cookie('wd1_nlpopup') != 'closed' || 'submited'){
        setTimeout(wd1_open_nlpopup, wd1_nlpopup_delay);
    }
</code>```

When data is submited data is in mysql database but popup show again i trying to use onsubmit with function but same result or popup don`t show but data is not in the database.Thank you

答:
Remove the line e.preventDefault(); from your on submit function.

Change your if statement at the end to this:
if($.cookie('wd1_nlpopup') != 'closed' && $.cookie('wd1_nlpopup') != 'submited'){

The || 'submited' clause is evaluated as "truthy", therefore that statement, since it's an OR, is always truthy, thus that pop up will always show.

https://developer.mozilla.org/en-US/docs/Glossary/Truthy

In JavaScript, a truthy value is a value that is considered  true when
  evaluated in a Boolean context. All values are truthy unless they are
  defined as falsy (i.e., except for false, 0, "", null, undefined, and
  NaN).

JavaScript uses type coercion in Boolean contexts.

Examples of truthy values in JavaScript (which will translate to true
  and thus execute the if block):

if (true)

if ({})

if ([])

if (42)

if ("foo")

if (new Date())

if (-42)

...

Title: after submit popup show again

Body:
I have this form which is linked to post php

<form action="newsletter.php" method="post" >
    <input type="text" name="name" id="wd1_nlpopup_name" placeholder="Name" value="" class="textinput" tabindex="500">
    <input type="text" name="email" id="wd1_nlpopup_mail" placeholder="Your email" value="" class="textinput" tabindex="501">
    <input type="submit" name="submit" class="btn btn-orange btn-large" value="Submit" id="submit">
</form>

and this javascript file which popup the form

jQuery(document).ready(function($){
    var wd1_nlpopup_expires = $("#wd1_nlpopup").data("expires");
    var wd1_nlpopup_delay = $("#wd1_nlpopup").data("delay") * 1000;

    $('#wd1_nlpopup_close').on('click', function(e){
        $.cookie('wd1_nlpopup', 'closed', { expires: wd1_nlpopup_expires, path: '/' });
        $('#wd1_nlpopup,#wd1_nlpopup_overlay').fadeOut(200);
        e.preventDefault();
    });

        $('#submit').on('submit', function(e){
        $.cookie('wd1_nlpopup', 'submited', { expires: wd1_nlpopup_expires, path: '/' });
        $('#wd1_nlpopup,#wd1_nlpopup_overlay').fadeOut(200);
        e.preventDefault();
    });

    if($.cookie('wd1_nlpopup') != 'closed' || 'submited'){
        setTimeout(wd1_open_nlpopup, wd1_nlpopup_delay);
    }

When data is submited data is in mysql database but popup show again i trying to use onsubmit with function but same result or popup don`t show but data is not in the database.Thank you


问:
Assigning updated value to $_SESSION array
Can someone tell me why the $_SESSION array is not getting modified by the code below.  The object is to put the date in DoNotShipBefore of each record. It is obviously putting the value somewhere as the output of $Row['DoNotShipBefore'] shows the correct date.  But, when the loop is done, it doesn't appear to have taken.

```<code>session_start();
print_r($_SESSION[cart_array]);
foreach($_SESSION[cart_array] as $Row) {

      $Row['DoNotShipBefore'] = date("m/d/Y") ;
      echo "<br>New Value of DoNotShipBefore (From cart_array): ". $Row['DoNotShipBefore'] ;

}
print "<br><br>";
print_r($_SESSION[cart_array]);
die();
</code>```

Output follows:

```<code>Array ( [0] => Array ( [groupId] => 26141 [DoNotShipBefore] => 10/01/2017))

New Value of DoNotShipBefore (From cart_array): 07/06/2017

Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 10/01/2017))

// Should be (or what I want is):
Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 07/06/2017))
</code>```

I'm having a hard time wrapping my head around how to address Arrays within the SESSION, so would really appreciate any help.

答:
Except when the value is an object, when you assign a variable it makes a copy of the value (internally it uses copy-on-write for efficiency). So $Row is a copy of the row in $_SESSION. You're modifying that copy, not the original array.

You can use a reference variable to make it refer to the original array, by putting & before the variable.

```<code>foreach($_SESSION['cart_array'] as &$Row) {
</code>```

Body:
Can someone tell me why the $_SESSION array is not getting modified by the code below.  The object is to put the date in DoNotShipBefore of each record. It is obviously putting the value somewhere as the output of $Row['DoNotShipBefore'] shows the correct date.  But, when the loop is done, it doesn't appear to have taken.

session_start();
print_r($_SESSION[cart_array]);
foreach($_SESSION[cart_array] as $Row) {

      $Row['DoNotShipBefore'] = date("m/d/Y") ;
      echo "
New Value of DoNotShipBefore (From cart_array): ". $Row['DoNotShipBefore'] ;

}
print "

";
print_r($_SESSION[cart_array]);
die();

Output follows:

Array ( [0] => Array ( [groupId] => 26141 [DoNotShipBefore] => 10/01/2017))

New Value of DoNotShipBefore (From cart_array): 07/06/2017

Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 10/01/2017))

// Should be (or what I want is):
Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 07/06/2017))

I'm having a hard time wrapping my head around how to address Arrays within the SESSION, so would really appreciate any help.

Body:
Except when the value is an object, when you assign a variable it makes a copy of the value (internally it uses copy-on-write for efficiency). So $Row is a copy of the row in $_SESSION. You're modifying that copy, not the original array.

You can use a reference variable to make it refer to the original array, by putting & before the variable.

foreach($_SESSION['cart_array'] as &$Row) {


问:
Equivalent of apply() by row in the tidyverse?
I want to insert a new column into a data.frame, which value is TRUE when there is at least one missing value in the row and FALSE otherwise.

For that problem, apply is a a perfect use case:

 EDIT - added example

```<code>tab <- data.frame(a = 1:10, b = c(NA, letters[2:10]), c = c(LETTERS[1:9], NA))

tab$missing <- apply(tab, 1, function(x) any(is.na(x)))
</code>```

However, I loaded the strict package, and got this error: apply() coerces X to a matrix so is dangerous to use with data frames.Please use lapply() instead.

I know that I can safely ignore this error, however, I was wondering if there was a way to code it using one of the tidyverse packages, in a simple manner. I tried unsuccessfully with dplyr:

```<code>tab %>%
  rowwise() %>%
  mutate(missing = any(is.na(.), na.rm = TRUE))
</code>```

答:
If you want to avoid coercing to a matrix, you can use purrr::pmap, which iterates across the elements of a list in parallel and passes them to a function:

library(tidyverse)

tab <- data_frame(a = 1:10,
                  b = c(NA, letters[2:10]),
                  c = c(LETTERS[1:9], NA))

tab %>% mutate(missing = pmap_lgl(., ~any(is.na(c(...)))))
#> # A tibble: 10 x 4
#>        a     b     c missing
#>    <int> <chr> <chr>   <lgl>
#>  1     1  <NA>     A    TRUE
#>  2     2     b     B   FALSE
#>  3     3     c     C   FALSE
#>  4     4     d     D   FALSE
#>  5     5     e     E   FALSE
#>  6     6     f     F   FALSE
#>  7     7     g     G   FALSE
#>  8     8     h     H   FALSE
#>  9     9     i     I   FALSE
#> 10    10     j  <NA>    TRUE
```

<p>In the function, <code>c</code> is necessary to pull all the parameters passed to the function <code>...</code> into a vector, which can be passed to <code>is.na</code> and collapsed with <code>any</code>. The <code>*_lgl</code> suffixed <code>pmap</code> simplifies the result to a Boolean vector.</p>

<p>Note that while this avoids coercing to matrix, it will not necessarily be faster than approaches that do, as matrix operations are highly optimized in R. It may make more sense to <em>explicitly</em> coerce to a matrix, e.g.</p>

<pre class="lang-r prettyprint-override"><code>tab %>% mutate(missing = rowSums(is.na(as.matrix(.))) > 0)
</code>```

which returns the same thing.

Body:
I want to insert a new column into a data.frame, which value is TRUE when there is at least one missing value in the row and FALSE otherwise.

For that problem, apply is a a perfect use case:

 EDIT - added example

tab <- data.frame(a = 1:10, b = c(NA, letters[2:10]), c = c(LETTERS[1:9], NA))

tab$missing <- apply(tab, 1, function(x) any(is.na(x)))

However, I loaded the strict package, and got this error: apply() coerces X to a matrix so is dangerous to use with data frames.Please use lapply() instead.

I know that I can safely ignore this error, however, I was wondering if there was a way to code it using one of the tidyverse packages, in a simple manner. I tried unsuccessfully with dplyr:

tab %>%
  rowwise() %>%
  mutate(missing = any(is.na(.), na.rm = TRUE))

Body:
If you want to avoid coercing to a matrix, you can use purrr::pmap, which iterates across the elements of a list in parallel and passes them to a function:

library(tidyverse)

tab <- data_frame(a = 1:10,
                  b = c(NA, letters[2:10]),
                  c = c(LETTERS[1:9], NA))

tab %>% mutate(missing = pmap_lgl(., ~any(is.na(c(...)))))
#> # A tibble: 10 x 4
#>        a     b     c missing
#>    <int> <chr> <chr>   <lgl>
#>  1     1  <NA>     A    TRUE
#>  2     2     b     B   FALSE
#>  3     3     c     C   FALSE
#>  4     4     d     D   FALSE
#>  5     5     e     E   FALSE
#>  6     6     f     F   FALSE
#>  7     7     g     G   FALSE
#>  8     8     h     H   FALSE
#>  9     9     i     I   FALSE
#> 10    10     j  <NA>    TRUE

In the function, c is necessary to pull all the parameters passed to the function ... into a vector, which can be passed to is.na and collapsed with any. The *_lgl suffixed pmap simplifies the result to a Boolean vector.

Note that while this avoids coercing to matrix, it will not necessarily be faster than approaches that do, as matrix operations are highly optimized in R. It may make more sense to explicitly coerce to a matrix, e.g.

tab %>% mutate(missing = rowSums(is.na(as.matrix(.))) > 0)

which returns the same thing.


问:
Trouble Scraping site with BS4
usually I'm able to write a script that works for scraping, but I've been having some difficulty scraping this site for the table enlisted for this research project I'm working on. I'm planning to verify the script working on one State before entering the URL of my targeted states.

```<code>import requests
import bs4 as bs

url = ("http://programs.dsireusa.org/system/program/detail/284")
dsire_get = requests.get(url)
soup = bs.BeautifulSoup(dsire_get.text,'lxml')
table = soup.findAll('div', {'data-ng-controller': 'DetailsPageCtrl'})
print(table)
#I'm printing "Table" just to ensure that the table information I'm looking for is within this sections
</code>```

I'm not sure if the site is attempting to block people from scraping, but all the info that I'm looking to grab is within "&quot"if you look what Table outputs.

答:
The text is rendered with JavaScript.
First render the page with dryscrape

(If you don't want to use dryscrape see Web-scraping JavaScript page with Python )

Then the text can be extracted, after it has been rendered, from a different position on the page i.e the place it has been rendered to.

As an example this code will extract HTML from the summary.

```<code>import bs4 as bs
import dryscrape

url = ("http://programs.dsireusa.org/system/program/detail/284")
session = dryscrape.Session()
session.visit(url)
dsire_get = session.body()
soup = bs.BeautifulSoup(dsire_get,'html.parser')
table = soup.findAll('div', {'class': 'programSummary ng-binding'})
print(table[0])
</code>```

Outputs:

```<code><div class="programSummary ng-binding" data-ng-bind-html="program.summary"><p>
<strong>Eligibility and Availability</strong></p>
<p>
Net metering is available to all "qualifying facilities" (QFs), as defined by the federal <i>Public Utility Regulatory Policies Act of 1978</i> (PURPA), which pertains to renewable energy systems and combined heat and power systems up to 80 megawatts (MW) in capacity. There is no statewide cap on the aggregate capacity of net-metered systems.</p>
<p>
All utilities subject to Public ...
</code>```

Title: Trouble Scraping site with BS4

Body:
usually I'm able to write a script that works for scraping, but I've been having some difficulty scraping this site for the table enlisted for this research project I'm working on. I'm planning to verify the script working on one State before entering the URL of my targeted states.

import requests
import bs4 as bs

url = ("http://programs.dsireusa.org/system/program/detail/284")
dsire_get = requests.get(url)
soup = bs.BeautifulSoup(dsire_get.text,'lxml')
table = soup.findAll('div', {'data-ng-controller': 'DetailsPageCtrl'})
print(table)
#I'm printing "Table" just to ensure that the table information I'm looking for is within this sections

I'm not sure if the site is attempting to block people from scraping, but all the info that I'm looking to grab is within "&quot"if you look what Table outputs.

Body:
The text is rendered with JavaScript.
First render the page with dryscrape

(If you don't want to use dryscrape see Web-scraping JavaScript page with Python )

Then the text can be extracted, after it has been rendered, from a different position on the page i.e the place it has been rendered to.

As an example this code will extract HTML from the summary.

import bs4 as bs
import dryscrape

url = ("http://programs.dsireusa.org/system/program/detail/284")
session = dryscrape.Session()
session.visit(url)
dsire_get = session.body()
soup = bs.BeautifulSoup(dsire_get,'html.parser')
table = soup.findAll('div', {'class': 'programSummary ng-binding'})
print(table[0])

Outputs:

<div class="programSummary ng-binding" data-ng-bind-html="program.summary"><p>
<strong>Eligibility and Availability</strong></p>
<p>
Net metering is available to all "qualifying facilities" (QFs), as defined by the federal <i>Public Utility Regulatory Policies Act of 1978</i> (PURPA), which pertains to renewable energy systems and combined heat and power systems up to 80 megawatts (MW) in capacity. There is no statewide cap on the aggregate capacity of net-metered systems.</p>
<p>
All utilities subject to Public ...


问:
How to push Laravel 5.4 project to a server with PHP CLI version 5.4.16?
My client uses a server with Apache PHP version 5.6.30 but the CLI PHP version is 5.4.16. And they can't change the CLI PHP version.

I use Git && SSH to push the project to the server from my local machine. But since the CLI PHP version is 5.4.16, I can't run

```<code>composer install
</code>```

I will get these messages

```<code>Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.4.16) does not satisfy that requirement.
  Problem 2
    - symfony/var-dumper v3.3.2 requires php >=5.5.9 -> your PHP version (5.4.16) does not satisfy that requirement.
    - symfony/var-dumper v3.3.2 requires php >=5.5.9 -> your PHP version (5.4.16) does not satisfy that requirement.
    - Installation request for symfony/var-dumper v3.3.2 -> satisfiable by symfony/var-dumper[v3.3.2].
</code>```

The phpinfo() tells that the version of PHP is 5.6.30. So I guess that part should be fine. But I don't know that to solve this situation.

When I go to the website, I get these error messages:

```<code>Warning: require(/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php): failed to open stream: No such file or directory in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Warning: require(/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php): failed to open stream: No such file or directory in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Fatal error: require(): Failed opening required '/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php' (include_path='.:/opt/plesk/php/5.6/share/pear') in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12
</code>```

答:
Although not ideal, you can also push the entire vendor folder along to the server.  All composer install really does is create the vendor folder.  If you upload your entire project folder, vendors included, then you will be able to run it on the server without running composer.  As long as the web version meets your minimum requirements, then this means that you should be able to effectively ignore the client version.

That being said, you'll run into this problem again if you need to run any tasks from the command line.

Body:
My client uses a server with Apache PHP version 5.6.30 but the CLI PHP version is 5.4.16. And they can't change the CLI PHP version.

I use Git && SSH to push the project to the server from my local machine. But since the CLI PHP version is 5.4.16, I can't run

composer install

I will get these messages

Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.4.16) does not satisfy that requirement.
  Problem 2
    - symfony/var-dumper v3.3.2 requires php >=5.5.9 -> your PHP version (5.4.16) does not satisfy that requirement.
    - symfony/var-dumper v3.3.2 requires php >=5.5.9 -> your PHP version (5.4.16) does not satisfy that requirement.
    - Installation request for symfony/var-dumper v3.3.2 -> satisfiable by symfony/var-dumper[v3.3.2].

The phpinfo() tells that the version of PHP is 5.6.30. So I guess that part should be fine. But I don't know that to solve this situation.

When I go to the website, I get these error messages:

Warning: require(/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php): failed to open stream: No such file or directory in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Warning: require(/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php): failed to open stream: No such file or directory in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Fatal error: require(): Failed opening required '/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php' (include_path='.:/opt/plesk/php/5.6/share/pear') in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12


问:
How can I pass my user entered information to my database using php?
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

```<code><!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//<!-- post added information to database -->
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>
</code>```

From looking at my code I believe the issue is with this line.

```<code>   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
</code>```

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

```<code>$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
</code>```

These hard coded entries are put into the database but i can't get the user entered data to go in.

答:
Your insert code be like this

```<code>$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
</code>```

Then your value will be in database
If field id is primary key and auto increment then  your insert statement should be like

Try this:

```<code>$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";
</code>```

Body:
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>

From looking at my code I believe the issue is with this line.

   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";

These hard coded entries are put into the database but i can't get the user entered data to go in.

Body:
Your insert code be like this

$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";

Then your value will be in database
If field id is primary key and auto increment then  your insert statement should be like

Try this:

$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";


问:
C++ virtual method, that doesn't require "this" pointer - optimization
I'd like to implement access to a certain class:

```<code>class A { some properties and methods };
</code>```

The problem is there are multiple states A can be in and the methods need to behave accordingly. One way is this:

```<code>class A
{
    void Method1() {
        if (A is in state 1) { do something }
        else if (A is in state 2) { do something else }
        ...
    }
};
</code>```

That obviously isn't very optimal, if the methods are called many times. So a solution, which is simple to implement, would be to create several classes for different states:

```<code>class A
{
    class State1 {
        virtual void Method1(A& a) { do something; }
        ...
    } State1Instance;

    class State2 { ... }
    ...
};
</code>```

And then manage a pointer to the object depending on current state (e.g. State1Instance) and call methods of this object. That avoids the CPU consuming condition.

BUT the State# methods also receive the completely useless "this" pointer to the State object. Is there a way to avoid this? I know the difference is minimal, but I'm trying to make this as optimal as possible and using a CPU register for a completely pointless value is not ideal. This would actually be a good use for "virtual static", which is forbidden however.

答:
One of the most versatile solutions available out of the box in c++17, and courtesy of boost prior is the variant type and the concept of a static_visitor.

Using c++14 and boost::variant I have created a very simple state machine that uses type-based switching of code paths plus automatic catching of un-accounted-for state/event combinations.

For a fuller solution I would refer you to the boost fsm header-only library.

```<code>#include <boost/variant.hpp>
#include <iostream>
#include <typeinfo>

struct event1 {
};

struct event2 {
};

struct state_machine {

    struct state1 {
    };

    struct state2 {
    };

    struct state3 {
    };

    using state_type = boost::variant<state1, state2, state3>;

    struct handle_event {
        // default case for event/state combinations we have not coded for
        template<class SM, class State, class Event>
        void operator()(SM &sm, State &state, Event const&event) const {
            std::cout << "unhandled event "
                      "state=" << typeid(state).name() << " "
                      "event=" << typeid(event).name() << std::endl;
        }

        template<class SM>
        void operator()(SM &sm, state1 &state, event1 const&event) const {
            std::cout << "received event1 while in state1 - switching to state 2" << std::endl;
            sm.change_state(state2());
        }

        template<class SM>
        void operator()(SM &sm, state2 &state, event2 const&event) const {
            std::cout << "received event2 while in state2 - switching to state 1" << std::endl;
            sm.change_state(state1());
        }

        template<class SM>
        void operator()(SM &sm, state1 &state, event2 const&event) const {
            std::cout << "received event2 while in state1 - switching to state 3" << std::endl;
            sm.change_state(state3());
        }

    };

    template<class Event>
    auto notify_event(Event const&evt) {
        return boost::apply_visitor([this, &evt](auto& state)
                                    {
                                        handle_event()(*this, state, evt);
                                    }, state_);
    }

    template<class NewState>
    void change_state(NewState&& ns) {
        state_ = std::forward<NewState>(ns);
    }

private:

    state_type state_ = state1{};
};

int main()
{
    state_machine sm {};

    sm.notify_event(event1());
    sm.notify_event(event2());
    sm.notify_event(event2());

    // we have not coded for this one
    sm.notify_event(event2());
}
</code>```

example output (exact output will depend on compiler ABI):

```<code>received event1 while in state1 - switching to state 2
received event2 while in state2 - switching to state 1
received event2 while in state1 - switching to state 3
unhandled event state=N13state_machine6state3E event=6event2
</code>```

Body:
I'd like to implement access to a certain class:

class A { some properties and methods };

The problem is there are multiple states A can be in and the methods need to behave accordingly. One way is this:

class A
{
    void Method1() {
        if (A is in state 1) { do something }
        else if (A is in state 2) { do something else }
        ...
    }
};

That obviously isn't very optimal, if the methods are called many times. So a solution, which is simple to implement, would be to create several classes for different states:

class A
{
    class State1 {
        virtual void Method1(A& a) { do something; }
        ...
    } State1Instance;

    class State2 { ... }
    ...
};

And then manage a pointer to the object depending on current state (e.g. State1Instance) and call methods of this object. That avoids the CPU consuming condition.

BUT the State# methods also receive the completely useless "this" pointer to the State object. Is there a way to avoid this? I know the difference is minimal, but I'm trying to make this as optimal as possible and using a CPU register for a completely pointless value is not ideal. This would actually be a good use for "virtual static", which is forbidden however.

Body:
One of the most versatile solutions available out of the box in c++17, and courtesy of boost prior is the variant type and the concept of a static_visitor.

Using c++14 and boost::variant I have created a very simple state machine that uses type-based switching of code paths plus automatic catching of un-accounted-for state/event combinations.

For a fuller solution I would refer you to the boost fsm header-only library.

#include <boost/variant.hpp>
#include <iostream>
#include <typeinfo>

struct event1 {
};

struct event2 {
};

struct state_machine {

    struct state1 {
    };

    struct state2 {
    };

    struct state3 {
    };

    using state_type = boost::variant<state1, state2, state3>;

    struct handle_event {
        // default case for event/state combinations we have not coded for
        template<class SM, class State, class Event>
        void operator()(SM &sm, State &state, Event const&event) const {
            std::cout << "unhandled event "
                      "state=" << typeid(state).name() << " "
                      "event=" << typeid(event).name() << std::endl;
        }

        template<class SM>
        void operator()(SM &sm, state1 &state, event1 const&event) const {
            std::cout << "received event1 while in state1 - switching to state 2" << std::endl;
            sm.change_state(state2());
        }

        template<class SM>
        void operator()(SM &sm, state2 &state, event2 const&event) const {
            std::cout << "received event2 while in state2 - switching to state 1" << std::endl;
            sm.change_state(state1());
        }

        template<class SM>
        void operator()(SM &sm, state1 &state, event2 const&event) const {
            std::cout << "received event2 while in state1 - switching to state 3" << std::endl;
            sm.change_state(state3());
        }

    };

    template<class Event>
    auto notify_event(Event const&evt) {
        return boost::apply_visitor([this, &evt](auto& state)
                                    {
                                        handle_event()(*this, state, evt);
                                    }, state_);
    }

    template<class NewState>
    void change_state(NewState&& ns) {
        state_ = std::forward<NewState>(ns);
    }

private:

    state_type state_ = state1{};
};

int main()
{
    state_machine sm {};

    sm.notify_event(event1());
    sm.notify_event(event2());
    sm.notify_event(event2());

    // we have not coded for this one
    sm.notify_event(event2());
}

example output (exact output will depend on compiler ABI):

received event1 while in state1 - switching to state 2
received event2 while in state2 - switching to state 1
received event2 while in state1 - switching to state 3
unhandled event state=N13state_machine6state3E event=6event2


问:
How to write a generalized method in Factory Pattern to provide object?
```<code>public class GsonStudentFactory{
....
 public static MasterStudent createMasterStudent(Student student) {
    return gson.fromJson(student.getBody(), MasterStudent.class);
 }

 public static  BTechStudent createBtechStudent(Student student) {
    return gson.fromJson(student.getBody(), BTechStudent.class);
 }
...
}
</code>```

In order to generalize I can use 'if' condition and I can check 'if instance of student is BTechStudent or MasterStudent' and return appropriate BTechStudent or MasterStudent object.

Is there any better way, to generalize these two methods?

note:- BTechStudent and MasterStudent classes extends Student class.

Thanks in Advance.

答:
I'm not sure if I understood it correctly, but see if this helps you:

```<code>public static <T extends Student> T createStudent(Student student) {
    return gson.fromJson(student.getBody(), (Class<T>) student.getClass());
}
</code>```

And use it like this:

```<code>MasterStudent masterStudent = createStudent(student);
</code>```

or

```<code>BTechStudent btech = createStudent(student);
</code>```

Body:
public class GsonStudentFactory{
....
 public static MasterStudent createMasterStudent(Student student) {
    return gson.fromJson(student.getBody(), MasterStudent.class);
 }

 public static  BTechStudent createBtechStudent(Student student) {
    return gson.fromJson(student.getBody(), BTechStudent.class);
 }
...
}

In order to generalize I can use 'if' condition and I can check 'if instance of student is BTechStudent or MasterStudent' and return appropriate BTechStudent or MasterStudent object.

Is there any better way, to generalize these two methods?

note:- BTechStudent and MasterStudent classes extends Student class.

Thanks in Advance.

Body:
I'm not sure if I understood it correctly, but see if this helps you:

public static <T extends Student> T createStudent(Student student) {
    return gson.fromJson(student.getBody(), (Class<T>) student.getClass());
}

And use it like this:

MasterStudent masterStudent = createStudent(student);

or

BTechStudent btech = createStudent(student);


问:
How To Increase Sklearn GMM predict() Performance Speed?
I am using Sklearn to estimate the Gaussian Mixture Model (GMM) on some data.

After the estimation, I have many query points. I would like to obtain their probabilities of belonging to each of the estimated Gaussian.

The code below works. However, the gmm_sk.predict_proba(query_points) part is very slow as I need to run it multiple times on 100000 sets of samples, where each sample contains 1000 points.

I guess that it happens because it is sequential. Is there a way to make it parallel? Or any other way to make it faster? Maybe on GPU using TensorFlow?

I saw TensorFlow has its own GMM algorithm but it was very hard to implement.

Here is the code that I have written:

```<code>import numpy as np
from sklearn.mixture import GaussianMixture
import time

n_gaussians = 1000
covariance_type = 'diag'
points = np.array(np.random.rand(10000, 3), dtype=np.float32)
query_points = np.array(np.random.rand(1000, 3), dtype=np.float32)
start = time.time()

#GMM with sklearn
gmm_sk = GaussianMixture(n_components = n_gaussians, covariance_type=covariance_type)
gmm_sk.fit(points)
mid_t = time.time()
elapsed = time.time() - start
print("learning took "+ str(elapsed))

temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))

end_t = time.time() - mid_t
print("predictions took " + str(end_t))
</code>```

I solved it ! using multiprocessing.
just replaced

```<code>temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))
</code>```

with

```<code>import multiprocessing as mp
    query_points = query_points.tolist()
    parallel = mp.Pool()
    fv = parallel.map(par_gmm, query_points)
    parallel.close()
    parallel.join()
</code>```

答: I see that your number of Gaussian components in the GMM is 1000, which, I think is a very large number, given your data dimensionality is relatively low (3). This is probably the reason that it runs slow, since it needs to evaluate 1000 separate Gaussians. If your sample count is low, then this is also very prone to overfitting. You can try a lower number of components, which will naturally be faster and will most likely generalize better.</p>

Body:
I am using Sklearn to estimate the Gaussian Mixture Model (GMM) on some data.

After the estimation, I have many query points. I would like to obtain their probabilities of belonging to each of the estimated Gaussian.

The code below works. However, the gmm_sk.predict_proba(query_points) part is very slow as I need to run it multiple times on 100000 sets of samples, where each sample contains 1000 points.

I guess that it happens because it is sequential. Is there a way to make it parallel? Or any other way to make it faster? Maybe on GPU using TensorFlow?

I saw TensorFlow has its own GMM algorithm but it was very hard to implement.

Here is the code that I have written:

import numpy as np
from sklearn.mixture import GaussianMixture
import time

n_gaussians = 1000
covariance_type = 'diag'
points = np.array(np.random.rand(10000, 3), dtype=np.float32)
query_points = np.array(np.random.rand(1000, 3), dtype=np.float32)
start = time.time()

#GMM with sklearn
gmm_sk = GaussianMixture(n_components = n_gaussians, covariance_type=covariance_type)
gmm_sk.fit(points)
mid_t = time.time()
elapsed = time.time() - start
print("learning took "+ str(elapsed))

temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))

end_t = time.time() - mid_t
print("predictions took " + str(end_t))

I solved it ! using multiprocessing.
just replaced

temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))

with

import multiprocessing as mp
    query_points = query_points.tolist()
    parallel = mp.Pool()
    fv = parallel.map(par_gmm, query_points)
    parallel.close()
    parallel.join()


问:
/bin/sh: 1: composer: not found
I am trying to build a Dockerfile.

```<code>FROM php:7

RUN mkdir -p /home/winpc/test/laravelApp/app
WORKDIR /home/winpc/test/laravelApp/app

COPY composer.json /home/winpc/test/laravelApp/app
RUN composer install

COPY . /home/winpc/test/laravelApp/app

CMD php artisan serve --host=0.0.0.0 --port=8181
EXPOSE 8181
</code>```

But when i run the build command it says:

```<code>docker build -t lar-app .
/bin/sh: 1: composer: not found
The command '/bin/sh -c composer install' returned a non-zero code: 127
</code>```

But when I type just composer it is properly displaying the information
I guess the problem is with the command:

```<code>RUN composer install
</code>```

Here I am using Ubuntu 14.04

答:
As the Stacktrace says, install composer before running composer command.

I've added these lines:

```<code>RUN wget https://raw.githubusercontent.com/composer/getcomposer.org/1b137f8bf6db3e79a38a5bc45324414a6b1f9df2/web/installer -O - -q | php -- --quiet
RUN mv composer.phar /usr/local/bin/composer
</code>```

So your Dockerfile will be:

```<code>FROM php:7

# Install composer:
RUN wget https://raw.githubusercontent.com/composer/getcomposer.org/1b137f8bf6db3e79a38a5bc45324414a6b1f9df2/web/installer -O - -q | php -- --quiet
RUN mv composer.phar /usr/local/bin/composer

RUN mkdir -p /home/winpc/test/laravelApp/app
WORKDIR /home/winpc/test/laravelApp/app

COPY composer.json /home/winpc/test/laravelApp/app
RUN composer install

COPY . /home/winpc/test/laravelApp/app

CMD php artisan serve --host=0.0.0.0 --port=8181
EXPOSE 8181
</code>```

Title: /bin/sh: 1: composer: not found

Body:
I am trying to build a Dockerfile.

FROM php:7

RUN mkdir -p /home/winpc/test/laravelApp/app
WORKDIR /home/winpc/test/laravelApp/app

COPY composer.json /home/winpc/test/laravelApp/app
RUN composer install

COPY . /home/winpc/test/laravelApp/app

CMD php artisan serve --host=0.0.0.0 --port=8181
EXPOSE 8181

But when i run the build command it says:

docker build -t lar-app .
/bin/sh: 1: composer: not found
The command '/bin/sh -c composer install' returned a non-zero code: 127

But when I type just composer it is properly displaying the information
I guess the problem is with the command:

RUN composer install

Here I am using Ubuntu 14.04

Body:
As the Stacktrace says, install composer before running composer command.

I've added these lines:

RUN wget https://raw.githubusercontent.com/composer/getcomposer.org/1b137f8bf6db3e79a38a5bc45324414a6b1f9df2/web/installer -O - -q | php -- --quiet
RUN mv composer.phar /usr/local/bin/composer

So your Dockerfile will be:

FROM php:7

# Install composer:
RUN wget https://raw.githubusercontent.com/composer/getcomposer.org/1b137f8bf6db3e79a38a5bc45324414a6b1f9df2/web/installer -O - -q | php -- --quiet
RUN mv composer.phar /usr/local/bin/composer

RUN mkdir -p /home/winpc/test/laravelApp/app
WORKDIR /home/winpc/test/laravelApp/app

COPY composer.json /home/winpc/test/laravelApp/app
RUN composer install

COPY . /home/winpc/test/laravelApp/app

CMD php artisan serve --host=0.0.0.0 --port=8181
EXPOSE 8181


问:
Import doc and docx files in .Net and C#
I'm writing a text editor and I want to add the possibility to import .doc and .docx files. I know that I could use OLE Automation, but if I use a recent OLE library, it won't work with those people with an older version of Word, and if instead I use an older version, it won't be able to read .docx files.
Any ideas?
Thanks

EDIT: Another solution would be that, like my application works with HTML and RTF, convert .doc and .docx files with command line to one of these formats, something like this: http://www.snee.com/bobdc.blog/ 2007/09/using-word-for-command-line-co.html

答:
It's works with the Office 2003 PIA, tested in my computer running Office 2010:</p>

```<code>using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;

public string GetHtmlFromDoc(string path)
    var wordApp = new Application {Visible = false};

//Cargar documento
            object srcPath = path;
            var wordDoc = wordApp.Documents.Open(ref srcPath);

            //Guardarlo en HTML
            string destPath = Path.Combine(Path.GetTempPath(), "word" + (new Random().Next()) + ".html");
            if (wordDoc != null)
            {
                object oDestPath = destPath;
                object exportFormat = WdSaveFormat.wdFormatHTML;
                wordDoc.SaveAs(ref oDestPath, ref exportFormat);
            }

            //Cerrar
            wordDoc.Close();
            wordApp.Quit();

            //Comprobar que el archivo existe);
            if (File.Exists(destPath))
            {
               return File.ReadAllText(destPath, Encoding.Default);
}
return null;
}
</code>```

Body:
It's works with the Office 2003 PIA, tested in my computer running Office 2010:

using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;

public string GetHtmlFromDoc(string path)
    var wordApp = new Application {Visible = false};

//Cargar documento
            object srcPath = path;
            var wordDoc = wordApp.Documents.Open(ref srcPath);

            //Guardarlo en HTML
            string destPath = Path.Combine(Path.GetTempPath(), "word" + (new Random().Next()) + ".html");
            if (wordDoc != null)
            {
                object oDestPath = destPath;
                object exportFormat = WdSaveFormat.wdFormatHTML;
                wordDoc.SaveAs(ref oDestPath, ref exportFormat);
            }

            //Cerrar
            wordDoc.Close();
            wordApp.Quit();

            //Comprobar que el archivo existe);
            if (File.Exists(destPath))
            {
               return File.ReadAllText(destPath, Encoding.Default);
}
return null;
}


问:
Paperclip attachment_name returns nil
I have two models with attached files with using of Paperclip. Those two models are almost identical, however when I call a method '.attachment_name' on each class, for the second model, it returns nil.

I'm posting here code for both models unexpurgated because I don't know what information is important.

Here is the first model:

```<code>class DocumentationFile < ActiveRecord::Base
  belongs_to :documentation

  has_attached_file :file, styles: { large: '720x720>', medium: '300x300>', thumb: '100x100>' },
                           default_url: '/images/:style/missing.png'

  validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/,  'application/pdf'] },
                       size: { in: 0.megabytes..5.megabytes }

  validates :file, presence: true
end
</code>```

Here is a second one:

```<code>class JobExtra < ActiveRecord::Base
  belongs_to :job

  has_attached_file :file
  validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/, 'application/pdf'] },
                       size: { in: 0.megabytes..5.megabytes }
end
</code>```

So when in rails console I'm trying to get attachment name for both models with the second model I'm getting nil:

```<code>2.3.3 :003 > DocumentationFile.attachment_name
 => :file
2.3.3 :004 > JobExtra.attachment_name
 => nil
</code>```

I can't understand why it's happening and what I'm doing wrong. I've tried to add same validations and options to has_attached_file but it didn't help.

So I've run out of ideas and this issue is driving my crazy. I will be grateful for any help!

答:
Can we see your controller? I had the same problem and I solved it by writing in the create method:

```<code>def create
  @job.file = params[:job][:file]
  @job.save
end
</code>```

The reason behind this is that Rails actually processes the file/image, but everything is inside the model. Something like this:

Parameters:

```<code>{"job"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x007f
f342035948 @tempfile=#<Tempfile:/var/folders/_2/....jpg>, @original_filename="....jpg", filename=\"....jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"send"}
</code>```

Title: Paperclip attachment_name returns nil

Body:
I have two models with attached files with using of Paperclip. Those two models are almost identical, however when I call a method '.attachment_name' on each class, for the second model, it returns nil.

I'm posting here code for both models unexpurgated because I don't know what information is important.

Here is the first model:

class DocumentationFile < ActiveRecord::Base
  belongs_to :documentation

  has_attached_file :file, styles: { large: '720x720>', medium: '300x300>', thumb: '100x100>' },
                           default_url: '/images/:style/missing.png'

  validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/,  'application/pdf'] },
                       size: { in: 0.megabytes..5.megabytes }

  validates :file, presence: true
end

Here is a second one:

class JobExtra < ActiveRecord::Base
  belongs_to :job

  has_attached_file :file
  validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/, 'application/pdf'] },
                       size: { in: 0.megabytes..5.megabytes }
end

So when in rails console I'm trying to get attachment name for both models with the second model I'm getting nil:

2.3.3 :003 > DocumentationFile.attachment_name
 => :file
2.3.3 :004 > JobExtra.attachment_name
 => nil

I can't understand why it's happening and what I'm doing wrong. I've tried to add same validations and options to has_attached_file but it didn't help.

So I've run out of ideas and this issue is driving my crazy. I will be grateful for any help!

Body:
Can we see your controller? I had the same problem and I solved it by writing in the create method:

def create
  @job.file = params[:job][:file]
  @job.save
end

The reason behind this is that Rails actually processes the file/image, but everything is inside the model. Something like this:

Parameters:

{"job"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x007f
f342035948 @tempfile=#<Tempfile:/var/folders/_2/....jpg>, @original_filename="....jpg", filename=\"....jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"send"}


问:
What is more efficient? Using .replace() or passing string to list
Solving the following problem from CodeFights:

Given two strings, find the number of common characters between them.
  For s1 = "aabcc" and s2 = "adcaa", the output should be
  commonCharacterCount(s1, s2) = 3.

Strings have 3 common characters - 2 "a"s and 1 "c".

The way I approached it, whenever I took a letter into account I wanted to cancel it out so as not to count it again. I know strings are immutable, even when using methods such as .replace() (replace() method returns a copy of the string, no the actual string changed).

In order to mutate said string what I tend to do at the start is simply pass it on to a list with list(mystring) and then mutate that.

Question is... what is more efficient of the following? Take into account that option B gets done over and over, worst case scenario the strings are equal and have a match for match. Meanwhile option A happens once.

Option A)

```<code>list(mystring)
</code>```

Option B)

```<code>mystring = mystring.replace(letterThatMatches, "")
</code>```

答:
The idea of calling replace on the string for each element you find, is simply not a good idea: it takes O(n) to do that. If you do that for every character in the other string, it will result in an O(m×n) algorithm with m the number of characters of the first string, and n the number of characters from the second string.

You can simply use two Counters, then calculate the minimum of the two, and then calculate the sum of the counts. Like:

```<code>from collections import Counter

def common_chars(s1,s2):
    c1 = Counter(s1) # count for every character in s1, the amount
    c2 = Counter(s2) # count for every character in s2, the amount
    c3 = c1 & c2 # produce the minimum of each character
    return sum(c3.values()) # sum up the resulting counts
</code>```

Or as a one-liner:

```<code>def common_chars(s1,s2):
    return sum((Counter(s1) & Counter(s2)).values())
</code>```

If dictionary lookup can be done in O(1) (which usually holds for an average case), this is an O(m+n) algorithm: the counting then happens in O(m) and O(n) respectively, and calculating the minimum runs in the number of different characters (which is at most O(max(m,n)). Finally taking the sum is again an O(max(m,n)) operation.

For the sample input, this results in:

```<code>>>> common_chars("aabcc","adcaa")
3
</code>```

Body:
Solving the following problem from CodeFights:

Given two strings, find the number of common characters between them.
  For s1 = "aabcc" and s2 = "adcaa", the output should be
  commonCharacterCount(s1, s2) = 3.

Strings have 3 common characters - 2 "a"s and 1 "c".

The way I approached it, whenever I took a letter into account I wanted to cancel it out so as not to count it again. I know strings are immutable, even when using methods such as .replace() (replace() method returns a copy of the string, no the actual string changed).

In order to mutate said string what I tend to do at the start is simply pass it on to a list with list(mystring) and then mutate that.

Question is... what is more efficient of the following? Take into account that option B gets done over and over, worst case scenario the strings are equal and have a match for match. Meanwhile option A happens once.

Option A)

list(mystring)

Option B)

mystring = mystring.replace(letterThatMatches, "")

Body:
The idea of calling replace on the string for each element you find, is simply not a good idea: it takes O(n) to do that. If you do that for every character in the other string, it will result in an O(m×n) algorithm with m the number of characters of the first string, and n the number of characters from the second string.

You can simply use two Counters, then calculate the minimum of the two, and then calculate the sum of the counts. Like:

from collections import Counter

def common_chars(s1,s2):
    c1 = Counter(s1) # count for every character in s1, the amount
    c2 = Counter(s2) # count for every character in s2, the amount
    c3 = c1 & c2 # produce the minimum of each character
    return sum(c3.values()) # sum up the resulting counts

Or as a one-liner:

def common_chars(s1,s2):
    return sum((Counter(s1) & Counter(s2)).values())

If dictionary lookup can be done in O(1) (which usually holds for an average case), this is an O(m+n) algorithm: the counting then happens in O(m) and O(n) respectively, and calculating the minimum runs in the number of different characters (which is at most O(max(m,n)). Finally taking the sum is again an O(max(m,n)) operation.

For the sample input, this results in:

>>> common_chars("aabcc","adcaa")
3


答:
One way is to check the value of the SideIndicator property; e.g.:

```<code>if ( (Compare-Object (Get-Content test1.txt) (Get-Content test2.txt) -IncludeEqual).SideIndicator -eq '==' ) {
  "The files are equal"
}
</code>```

Compare-Object outputs nothing if there are no differences and you omit -IncludeEqual, so the above can also be written as:

```<code>if ( -not (Compare-Object (Get-Content test1.txt) (Get-Content test2.txt)) ) {
  "The files are equal"
}
</code>```

Title: Powershell- compare files and take action

Body:
I'm attempting to create a powershell script to compare two IP addresses out of two different text files then take an action base on if they match or they don't match. See below

(Invoke-WebRequest ifconfig.me/ip).content | Out-File "C:\test\test2.txt"
$ErrorActionPreference = "Stop"
$File = "C:\test\test.txt"
$File2 = "C:\test\test2.txt"

Compare-Object -ReferenceObject (Get-Content $File2) -DifferenceObject (Get-
Content $File) -IncludeEqual

If the two files match I obviously get a ==, or an => if they don't match. I'm not sure how to use == or => as a variable to continue the rest of the script. Any help or recommendations are greatly appreciated.

Body:
One way is to check the value of the SideIndicator property; e.g.:

if ( (Compare-Object (Get-Content test1.txt) (Get-Content test2.txt) -IncludeEqual).SideIndicator -eq '==' ) {
  "The files are equal"
}

Compare-Object outputs nothing if there are no differences and you omit -IncludeEqual, so the above can also be written as:

if ( -not (Compare-Object (Get-Content test1.txt) (Get-Content test2.txt)) ) {
  "The files are equal"
}


问:
How to automatically save files in Matlab?
I have a neural network and am generating figures and I wish to save those figures automatically with the filename as the training function and the hidden layer size, as well as the percentage correct

I have the following

```<code>... trainFcn=trainscg
</code>```

This changes between a couple of options: scg, rp, lm, etc

I also have the

```<code>hiddenLayerSize=[10 10 10]
</code>```

These values also change often.

I run my neural network and output a confusion matrix:

```<code>figure, plotconfusion(nnOutput, target)
</code>```

I then do

```<code>saveas(gcf, trainFcn+hiddenLayerSize)
</code>```

This does not work when I add the variables like that and also fails when I put a comma instead of a plus. How can I make this saveas work and make the filename my variables? I don't need to have the accuracy in the filename but if I can then it'd be great.

答:
Your method does not work because the function expects a string as a filename but trainFcn+hiddenLayerSize is not one. Try the following:

```<code>% convert size vector to a string
sizeString = sprintf('%dx', hiddenLayerSize);
sizeString = sizeString(1:end-1); % removes the trailing x
% auto-generate your filename
filename = sprintf('%s_%s', func2str(trainFcn), sizeString);
saveas(gcf, filename);
</code>```

This assumes that you have defined trainFcn like trainFcn = @trainscg; or something similar.

Body:
I have a neural network and am generating figures and I wish to save those figures automatically with the filename as the training function and the hidden layer size, as well as the percentage correct

I have the following

... trainFcn=trainscg

This changes between a couple of options: scg, rp, lm, etc

I also have the

hiddenLayerSize=[10 10 10]

These values also change often.

I run my neural network and output a confusion matrix:

figure, plotconfusion(nnOutput, target)

I then do

saveas(gcf, trainFcn+hiddenLayerSize)

This does not work when I add the variables like that and also fails when I put a comma instead of a plus. How can I make this saveas work and make the filename my variables? I don't need to have the accuracy in the filename but if I can then it'd be great.

Body:
Your method does not work because the function expects a string as a filename but trainFcn+hiddenLayerSize is not one. Try the following:

% convert size vector to a string
sizeString = sprintf('%dx', hiddenLayerSize);
sizeString = sizeString(1:end-1); % removes the trailing x
% auto-generate your filename
filename = sprintf('%s_%s', func2str(trainFcn), sizeString);
saveas(gcf, filename);

This assumes that you have defined trainFcn like trainFcn = @trainscg; or something similar.


问:
Oracle bug related to TO_DATE function?
I have some month/year data stored in a VARCHAR2 field, formatted as MM/YYYY.
When I try to convert it to a date for comparison with other dates in WHERE clause, I get "ORA-01841: (full) year must be between -4713 and +9999, and not be 0" error.

I checked for null values, there are none. I checked the two character month with min and max functions, they return min = '01' and max = '12'.  I checked the separator - there are no rows where position 3 is not '/'.   The length of the field is always 7.  Finally, using 4 characters from the year position, I determined that min = '2010' and max = '3020'.   I also checked each character of the year for < '0' and > '9' with no rows returned.   When I run the SQL without the to_date in the WHERE clause, but leave it in as a select column, then it does not throw an error.

How do I locate the bad data in this case?   I am stumped.

Field null check (in where clause):

```<code>and field is null ; result is 0 rows
</code>```

Length of field checking (in where clause):

```<code>and length(field) != 7 ; result is 0 rows
</code>```

Month checking (as select column)

```<code>min(substr(field, 1, 2)) ; result is '01' (string)
max(substr(field, 1, 2)) ; result is '12' (string)
</code>```

Separator checking (in where clause)

```<code>and substr(field, 3, 1) != '/'    ; result is 0 rows
</code>```

Year checking (as select column)

```<code>min(substr(field, 4, 4)) ; result is '2010' (string)
max(substr(field, 4, 4)) ; result is '3020' (string)
</code>```

答: Found my issue - other portions of my WHERE clause were narrowing my focus to the rows with GOOD data.  However, there is no guarantee about the order of which items in the WHERE clause are evaluated first, second, etc.  So I had to look at ALL the data for 'field' in the table.  You cannot just comment out the WHERE clause giving you trouble.  I found some rows with field = '0/0' which was the root cause of my data issue.</p>

Title: Oracle bug related to TO_DATE function?

Body:
I have some month/year data stored in a VARCHAR2 field, formatted as MM/YYYY.
When I try to convert it to a date for comparison with other dates in WHERE clause, I get "ORA-01841: (full) year must be between -4713 and +9999, and not be 0" error.

I checked for null values, there are none. I checked the two character month with min and max functions, they return min = '01' and max = '12'.  I checked the separator - there are no rows where position 3 is not '/'.   The length of the field is always 7.  Finally, using 4 characters from the year position, I determined that min = '2010' and max = '3020'.   I also checked each character of the year for < '0' and > '9' with no rows returned.   When I run the SQL without the to_date in the WHERE clause, but leave it in as a select column, then it does not throw an error.

How do I locate the bad data in this case?   I am stumped.

Field null check (in where clause):

and field is null ; result is 0 rows

Length of field checking (in where clause):

and length(field) != 7 ; result is 0 rows

Month checking (as select column)

min(substr(field, 1, 2)) ; result is '01' (string)
max(substr(field, 1, 2)) ; result is '12' (string)

Separator checking (in where clause)

and substr(field, 3, 1) != '/'    ; result is 0 rows

Year checking (as select column)

min(substr(field, 4, 4)) ; result is '2010' (string)
max(substr(field, 4, 4)) ; result is '3020' (string)


问:
How many byte read the std::istream::peek() function
I have try to read the next character in a file with only characters and with a file with only integers. This function return the next value (int or char). Now the question is how many byte read peek()? For first file it seems read one byte while for the second file it seems read four byte. How it's possible?</p>

答:
[H]ow many byte[s are] read [by] peek()?

std::ifstream::peek() reads one character (i.e. one byte) from the file, and returns it inside an int (the use of int is so that there is sufficient range to conditionally return EOF).

(Other std::basic_istream specialisations may have different char_type and int_type aliases, so the exact types and numbers given may differ if you use them. But the key is still that you extract one character, even if you think your ASCII file contains "numbers".)

It doesn't matter what the bytes of your file are: human-readable ASCII text, human-readable ASCII numbers, an encoded ZIP, random values… std::ifstream::peek() is an "unformatted input function", which is a type of IOStream function that works on the characters in a file.

For first file it seems read one byte while for the second file it seems read four byte.

  How it's possible?

It's not. You did something wrong.


问:
Create columns based on count of each unique value of one column in Pig
I have a dataset such as:

```<code>UserID Item EventType
  001   A     Buy
  001   B     Sell
  031   A     Sell
  008   C     Buy
  001   C     Buy
  001   A     Buy
  008   C     Sell
</code>```

How can I split the EventType column into a different column for each event. That is, I want two new columns EventType_Buy and EventType_Sell containing the counts of the occurrences of those events for each UserID and Item pair.

So the output should be something like this:

```<code>UserID Item EventType_Buy EventType_Sell
  001   A         2              0
  001   B         0              1
  001   C         1              0
  008   C         1              1
  031   A         0              1
</code>```

I'm not so much interested in the sorting, but I plan to use this data in R later, so I would like some help trying to perform this split into column counts.

I've tried creating separate objects for each event type and grouping by UserID, and Item, and generating the counts and trying to join these objects, but I'm not having much success.

答:
Ref : https://pig.apache.org/docs/r0.14.0/basic.html#foreach

Pig Script :

```<code>input_data = LOAD 'input.csv' USING PigStorage(',') AS (user_id:chararray,item:chararray,event_type:chararray);

req_stats = FOREACH(GROUP input_data BY (user_id,item)) {
                buy_bag = FILTER input_data BY event_type == 'Buy';
                sell_bag = FILTER input_data BY event_type == 'Sell';
                GENERATE FLATTEN(group) AS (user_id,item), COUNT(buy_bag) AS event_type_buy, COUNT(sell_bag) AS event_type_sell;
};

DUMP req_stats;
</code>```

Input :

```<code>001,A,Buy
001,B,Sell
031,A,Sell
008,C,Buy
001,C,Buy
001,A,Buy
008,C,Sell
</code>```

Output : DUMP req_stats

```<code>(001,A,2,0)
(001,B,0,1)
(001,C,1,0)
(008,C,1,1)
(031,A,0,1)
</code>```

Body:
I have a dataset such as:

UserID Item EventType
  001   A     Buy
  001   B     Sell
  031   A     Sell
  008   C     Buy
  001   C     Buy
  001   A     Buy
  008   C     Sell

How can I split the EventType column into a different column for each event. That is, I want two new columns EventType_Buy and EventType_Sell containing the counts of the occurrences of those events for each UserID and Item pair.

So the output should be something like this:

UserID Item EventType_Buy EventType_Sell
  001   A         2              0
  001   B         0              1
  001   C         1              0
  008   C         1              1
  031   A         0              1

I'm not so much interested in the sorting, but I plan to use this data in R later, so I would like some help trying to perform this split into column counts.

I've tried creating separate objects for each event type and grouping by UserID, and Item, and generating the counts and trying to join these objects, but I'm not having much success.

Body:
Ref : https://pig.apache.org/docs/r0.14.0/basic.html#foreach

Pig Script :

input_data = LOAD 'input.csv' USING PigStorage(',') AS (user_id:chararray,item:chararray,event_type:chararray);

req_stats = FOREACH(GROUP input_data BY (user_id,item)) {
                buy_bag = FILTER input_data BY event_type == 'Buy';
                sell_bag = FILTER input_data BY event_type == 'Sell';
                GENERATE FLATTEN(group) AS (user_id,item), COUNT(buy_bag) AS event_type_buy, COUNT(sell_bag) AS event_type_sell;
};

DUMP req_stats;

Input :

001,A,Buy
001,B,Sell
031,A,Sell
008,C,Buy
001,C,Buy
001,A,Buy
008,C,Sell

Output : DUMP req_stats

(001,A,2,0)
(001,B,0,1)
(001,C,1,0)
(008,C,1,1)
(031,A,0,1)


问:
how do I test methods using boto3 with moto
I am writing test cases for a quick class to find / fetch keys from s3, using boto3.  I have used moto in the past to test boto (not 3) code but am trying to move to boto3 with this project, and running into an issue:

```<code>class TestS3Actor(unittest.TestCase):
    @mock_s3
    def setUp(self):
        self.bucket_name = 'test_bucket_01'
        self.key_name = 'stats_com/fake_fake/test.json'
        self.key_contents = 'This is test data.'
        s3 = boto3.session.Session().resource('s3')
        s3.create_bucket(Bucket=self.bucket_name)
        s3.Object(self.bucket_name, self.key_name).put(Body=self.key_contents)
</code>```

error:

```<code>...
File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 344, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 314, in _raise_timeout
if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
TypeError: __str__ returned non-string (type WantWriteError)
botocore.hooks: DEBUG: Event needs-retry.s3.CreateBucket: calling handler <botocore.retryhandler.RetryHandler object at 0x10ce75310>
</code>```

It looks like moto is not mocking out the boto3 call correctly - how do I make that work?

答:
According to this information, it looks like streaming upload to s3 using Boto3 S3 Put is not yet supported.

In my case, I used following to successfully upload an object to a bucket:

```<code>s3.Object(self.s3_bucket_name, self.s3_key).put(Body=open("file_to_upload", 'rb'))
</code>```

where "file_to_upload" is your local file to be uploaded to s3 bucket. For your test case, you can just create a temporary file to check this functionality:

```<code>test_file = open("test_file.json", "w")
test_file.write("some test contents")
test_file.close()
s3.Object(self.s3_bucket_name, self.s3_key).put(Body=open("test_file", 'rb'))
</code>```

Body:
I am writing test cases for a quick class to find / fetch keys from s3, using boto3.  I have used moto in the past to test boto (not 3) code but am trying to move to boto3 with this project, and running into an issue:

class TestS3Actor(unittest.TestCase):
    @mock_s3
    def setUp(self):
        self.bucket_name = 'test_bucket_01'
        self.key_name = 'stats_com/fake_fake/test.json'
        self.key_contents = 'This is test data.'
        s3 = boto3.session.Session().resource('s3')
        s3.create_bucket(Bucket=self.bucket_name)
        s3.Object(self.bucket_name, self.key_name).put(Body=self.key_contents)

error:

...
File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 344, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 314, in _raise_timeout
if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
TypeError: __str__ returned non-string (type WantWriteError)
botocore.hooks: DEBUG: Event needs-retry.s3.CreateBucket: calling handler <botocore.retryhandler.RetryHandler object at 0x10ce75310>

It looks like moto is not mocking out the boto3 call correctly - how do I make that work?

Body:
According to this information, it looks like streaming upload to s3 using Boto3 S3 Put is not yet supported.

In my case, I used following to successfully upload an object to a bucket:

s3.Object(self.s3_bucket_name, self.s3_key).put(Body=open("file_to_upload", 'rb'))

where "file_to_upload" is your local file to be uploaded to s3 bucket. For your test case, you can just create a temporary file to check this functionality:

test_file = open("test_file.json", "w")
test_file.write("some test contents")
test_file.close()
s3.Object(self.s3_bucket_name, self.s3_key).put(Body=open("test_file", 'rb'))


答:
Since you're using plesk, you should find the binary of other PHP versions at /opt/plesk/php.</p>

```<code>/opt/plesk/php/5.6/bin/php /usr/bin/composer install
</code>```

Title: How to push Laravel 5.4 project to a server with PHP CLI version 5.4.16?

Body:
My client uses a server with Apache PHP version 5.6.30 but the CLI PHP version is 5.4.16. And they can't change the CLI PHP version.

I use Git && SSH to push the project to the server from my local machine. But since the CLI PHP version is 5.4.16, I can't run

composer install

I will get these messages

Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.4.16) does not satisfy that requirement.
  Problem 2
    - symfony/var-dumper v3.3.2 requires php >=5.5.9 -> your PHP version (5.4.16) does not satisfy that requirement.
    - symfony/var-dumper v3.3.2 requires php >=5.5.9 -> your PHP version (5.4.16) does not satisfy that requirement.
    - Installation request for symfony/var-dumper v3.3.2 -> satisfiable by symfony/var-dumper[v3.3.2].

The phpinfo() tells that the version of PHP is 5.6.30. So I guess that part should be fine. But I don't know that to solve this situation.

When I go to the website, I get these error messages:

Warning: require(/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php): failed to open stream: No such file or directory in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Warning: require(/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php): failed to open stream: No such file or directory in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Fatal error: require(): Failed opening required '/var/www/vhosts/example.com/httpdocs/vendor/composer/ClassLoader.php' (include_path='.:/opt/plesk/php/5.6/share/pear') in /var/www/vhosts/example.com/httpdocs/vendor/composer/autoload_real.php on line 12

Body:
Since you're using plesk, you should find the binary of other PHP versions at /opt/plesk/php.

/opt/plesk/php/5.6/bin/php /usr/bin/composer install