问:
Navigation bar odd behavior after giving it a fixed position in the css file
I made a navigation bar with a dropdown and was working fine until i added the "position: fixed;" statement in the css file. Once I did that the dropdown either isn't coming up when the mouse hovers over the designated button or is coming up off screen. Note the parent button reacts to the mouse hover fine in terms of color changes, that's why i think the dropdown is coming up off screen.

EDIT: i realized that the dropdown appears in the ul element and i can scroll within it to view the list. It's not appearing as an actual dropdown over the content on the page but within the navbar itself.

Here's my code:

ul.navbar {
  overflow-x: hidden;
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: 48px;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
  overflow: hidden;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <ul class="navbar">
    <li id="navbar" style=" margin-left: 3%; width:22%">Home</li>
    <li id="navbar" style=" width: 50%; text-align: center"><img src="logo.png" width="45px" height="45px" style="margin: 0"></li>
    <li id="navbar" class="dropdown" style="float: right; margin-right: 3%; width: 21%; text-align: right">
      Jump to...
      <div class="dropdown-content">
        Item1
        Item2
      </div>
    </li>

  </ul>

</body></code>```

答:
Remove overflow from .navbar

ul.navbar {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: 48px;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
  overflow: hidden;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <ul class="navbar">
    <li id="navbar" style=" margin-left: 3%; width:22%">Home</li>
    <li id="navbar" style=" width: 50%; text-align: center"><img src="logo.png" width="45px" height="45px" style="margin: 0"></li>
    <li id="navbar" class="dropdown" style="float: right; margin-right: 3%; width: 21%; text-align: right">
      Jump to...
      <div class="dropdown-content">
        Item1
        Item2
      </div>
    </li>

  </ul>

</body></code>```

Body:
I made a navigation bar with a dropdown and was working fine until i added the "position: fixed;" statement in the css file. Once I did that the dropdown either isn't coming up when the mouse hovers over the designated button or is coming up off screen. Note the parent button reacts to the mouse hover fine in terms of color changes, that's why i think the dropdown is coming up off screen.

EDIT: i realized that the dropdown appears in the ul element and i can scroll within it to view the list. It's not appearing as an actual dropdown over the content on the page but within the navbar itself.

Here's my code:

ul.navbar {
  overflow-x: hidden;
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: 48px;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
  overflow: hidden;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Home

      Jump to...

        Item1
        Item2

Body:
Remove overflow from .navbar

ul.navbar {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: #ffb90f;
  width: 100%;
  display: block;
  vertical-align: middle;
  height: 48px;
  position: fixed;
  top: 0;
}

.navbar li {
  display: inline-block;
  overflow: hidden;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
dropdown:hover .dropbtn {
  background-color: #FFC63D;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #FFF3D5;
  min-width: 160px;
  box-shadow: 0px 8px 100px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  margin-left: 8.7%;
}

.dropdown-content a {
  color: #FFBE1E;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ffb90f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

<body>

  <ul class="navbar">
    <li id="navbar" style=" margin-left: 3%; width:22%"><a href="homepage.php" class="dropbtn">Home</a></li>
    <li id="navbar" style=" width: 50%; text-align: center"><img src="logo.png" width="45px" height="45px" style="margin: 0"></li>
    <li id="navbar" class="dropdown" style="float: right; margin-right: 3%; width: 21%; text-align: right">
      <a href="javascript:void(0)" class="dropbtn">Jump to...</a>
      <div class="dropdown-content">
        <a href="#">Item1</a>
        <a href="#">Item2</a>
      </div>
    </li>

  </ul>

</body>


来源: stackexchange

问:
iOS Launch screen in React Native
I'm working with a React Native app and I'm trying to set a customize launch screen but I'm not able to.

React Native creates a LaunchScreen.xib by default, so I've created a LaunchImage inside Images.xcassets:

I've also read that I've to modify the "Launch Screen File" under "App Icons and Launch Images" in my options:

Once I've done that, my launch screen became totally black and when the app is loaded, there are both top and bottom black frames:

What do I have to do to set my launch screen in my React Native project?

答: Make sure the 'Launch Screen File' select is empty:

ContentLicense: CC BY-SA 4.0

Title: iOS Launch screen in React Native

ContentLicense: CC BY-SA 3.0


问:
How can I change the VB.NET application connection string after deployment?
I have written a VB.NET application and created a setup file to install the same on the target machine. An ODBC connection is used to connect to SQL Server instance through a DSN.

My development computer used Integrated Security whereas the target computer uses SQL Authentication which requires me to hard code the credentials in the connection string while building the setup file.

I have previously looked up for solutions, but they require one to define the credentials every time the application is run. I have seen an application that requests the credentials the first time it is run or if the connection is unsuccessful, but unfortunately could not retrieve the source code for the same.

Any guidance on similar lines would be helpful.

答:
Add application settings of string type with user scope for the user name and password, lets say username & userpass. Let the User save these values the first time they run your app.  Then just incorporate the My.Settings.username and My.Settings.userpass into your connection string.

To save the settings:

```<code>My.Settings.username = txt_user.text
My.Settings.Save()
</code>```

This way the user can change the username & password if required without you having to update your code.

Body:
Add application settings of string type with user scope for the user name and password, lets say username & userpass. Let the User save these values the first time they run your app.  Then just incorporate the My.Settings.username and My.Settings.userpass into your connection string.

To save the settings:

My.Settings.username = txt_user.text
My.Settings.Save()

This way the user can change the username & password if required without you having to update your code.


问:
Know when a FireBase Notification has been clicked
Is there a way to know that a user has clicked on a notification when the application is in the foreground?

I need to send analytics for when users click on the notification and I need to know when they have clicked it.

I can't put the analytics in the destination activity as I have other analytics that are sent when the user gets to that screen. I need to know that a user has specifically clicked on the notification to open the destination activity.

For example is there a callback for when a user clicks on the notification?

Thank you

答:
you should .setContentIntent(pendingIntent) in NotificationCompat.Builder
and put into this intent variable, then, on app start, you should check if this variable exists in intent of destination activity and if it is true, send analytics
if it is what you want, i can give code sample


问:
destroying object doesn't remove delegate from invocation list
I have a little problem with my objects...
I have an object with one delegate inside to which it subscribe in constructor.
When I destroy this object the invocation list still tell me that it has one subscriber in. and when and create this object again I find two subscriber in (the old that I have destroyed and the new one).
How can I solve this problem and remove the subscriber in the list cleanly?

Here is the code for test:(two button to destroy and create object inside)

```<code>public partial class Form1 : Form
{
    testdelegate thisdelegatetest;
    public Form1()
    {
        InitializeComponent();
        thisdelegatetest = new testdelegate();//create object
        Timer mytimer = new Timer();//timer to see something BEGIN
        mytimer.Interval = 1000;
        mytimer.Tick += new EventHandler(mytimer_Tick);
        mytimer.Start();//timer to see something END
    }
    protected void mytimer_Tick(object sender, EventArgs e)
    {//each 1second look at the list invocation
        lb_IndelList.Text = "actual subscribers : " + testdelegate.dl_myfunctionthatcopy.GetInvocationList().Count().ToString();
    }
    private void DestroyObject_Click(object sender, EventArgs e)
    {//destroy object
    /*edit*/
        thisdelegatetest.Delete();
        thisdelegatetest = null;//dereferencing for GC
    /*edit*/
    }

    private void CreateObject_Click(object sender, EventArgs e)
    {//create object
        thisdelegatetest = new testdelegate();
    }

}
public class testdelegate
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    /*edit*/
    public void Delete()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
    }
    /*edit*/
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
    }
}
</code>```

Thanks for your help.

答:
Since you cannot call the destructor manually, why not implementing the IDisposable interface and execute the unregistering in the Dispose method?=!

```<code>public class testdelegate : IDisposable
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
        Console.WriteLine("Copied");
    }

    public void Dispose()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
        GC.SuppressFinalize(this);
    }
}
</code>```

In the DestroyObject_Click method you would just call the Dispose method:

```<code>private void DestroyObject_Click(object sender, EventArgs e)
{   //call Dispose destroy object
    thisdelegatetest.Dispose();
}
</code>```

Body:
I have a little problem with my objects...
I have an object with one delegate inside to which it subscribe in constructor.
When I destroy this object the invocation list still tell me that it has one subscriber in. and when and create this object again I find two subscriber in (the old that I have destroyed and the new one).
How can I solve this problem and remove the subscriber in the list cleanly?

Here is the code for test:(two button to destroy and create object inside)

public partial class Form1 : Form
{
    testdelegate thisdelegatetest;
    public Form1()
    {
        InitializeComponent();
        thisdelegatetest = new testdelegate();//create object
        Timer mytimer = new Timer();//timer to see something BEGIN
        mytimer.Interval = 1000;
        mytimer.Tick += new EventHandler(mytimer_Tick);
        mytimer.Start();//timer to see something END
    }
    protected void mytimer_Tick(object sender, EventArgs e)
    {//each 1second look at the list invocation
        lb_IndelList.Text = "actual subscribers : " + testdelegate.dl_myfunctionthatcopy.GetInvocationList().Count().ToString();
    }
    private void DestroyObject_Click(object sender, EventArgs e)
    {//destroy object
    /*edit*/
        thisdelegatetest.Delete();
        thisdelegatetest = null;//dereferencing for GC
    /*edit*/
    }

    private void CreateObject_Click(object sender, EventArgs e)
    {//create object
        thisdelegatetest = new testdelegate();
    }

}
public class testdelegate
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    /*edit*/
    public void Delete()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
    }
    /*edit*/
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
    }
}

Thanks for your help.

Body:
Since you cannot call the destructor manually, why not implementing the IDisposable interface and execute the unregistering in the Dispose method?=!

public class testdelegate : IDisposable
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
        Console.WriteLine("Copied");
    }

    public void Dispose()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
        GC.SuppressFinalize(this);
    }
}

In the DestroyObject_Click method you would just call the Dispose method:

private void DestroyObject_Click(object sender, EventArgs e)
{   //call Dispose destroy object
    thisdelegatetest.Dispose();
}


问:
RegEx: Handling subgroups of Big - OR - Group as individuals and not as group count together
Let's say I have this pattern:

```<code>(?:StackOverflow is (.*)|(.*) is StackOverflow)
</code>```

I am using Java or Python. But I think they work quite similar.

My Input Strings would be:

```<code>StackOverflow is great
</code>```

or

```<code>great is StackOverflow
</code>```

In the real use case, I don't know the pattern and I don't know the input String. Both are set by the user.

I've tested it with regex101.com .

The result looks like this:

StackOverflow is great : Group 0 is great

great is StackOverflow : Group 1 is great

However I need both times to have Group 0 be great .
So what I'm trying to achieve is: Only count those groups, that actually exist in the input strings. Any other part of the big surrounding OR - group should be ignored.

I searched already on the internet but I don't really know what to search for in this case.

Is there a way to do this in RegEx?

答:
Generally speaking, regex doesn't work that way. Groups are numbered from left to right and there's nothing you can do about it.

That said, the regex module for python does it differently. It would consider both of these groups as #1. Unfortunately I don't know if such a thing exists for Java.

However, I think the real solution here is for the user to input a different regex. For example, your regex could be written as (StackOverflow is )?(.+)(?(1)| is StackOverflow), which is functionally equivalent except the word you're matching will always be in group #2. (Of course, this solution doesn't work if the word absolutely must be captured in group #1.)

Body:
Let's say I have this pattern:

(?:StackOverflow is (.*)|(.*) is StackOverflow)

I am using Java or Python. But I think they work quite similar.

My Input Strings would be:

StackOverflow is great

or

great is StackOverflow

In the real use case, I don't know the pattern and I don't know the input String. Both are set by the user.

I've tested it with regex101.com .

The result looks like this:

StackOverflow is great : Group 0 is great

great is StackOverflow : Group 1 is great

However I need both times to have Group 0 be great .
So what I'm trying to achieve is: Only count those groups, that actually exist in the input strings. Any other part of the big surrounding OR - group should be ignored.

I searched already on the internet but I don't really know what to search for in this case.

Is there a way to do this in RegEx?


问:
Substring a String depending on int
I wanted to substring a String depending on int that I will passed on the method. I used nested loop for this. But everytime it loops I wanted to substring only from last substring to int the I passed in the method and get also the last string. How can I achieve this?

```<code>private static void input(String s, int I)
{
    List list = new ArrayList();

    for(int a = 0; a < s.length(); a++)
    {
        for(int position = 0; position < s.length(); position++)
        {
            if(position + a + I <= s.length())
            {
                list.add(s.substring(position, position + a + I));
            }
        }
    }

}

input("abaca", 2);
</code>```

Expected output: "ab", "ac", "a"

答:
It's really better to completely rewrite your code, but if you want to save your structure(even though it's not correct), just remove 1 loop and do something like this:</p>

```<code>private static void input(String s, int I) {
    List list = new ArrayList();

    for (int position = 0; position < s.length();position += I) {
        if (position + I <= s.length()) {
            list.add(s.substring(position, position + I));
        } else {
            list.add(s.substring(position, s.length()));
            return;
        }
    }
}
</code>```

Title: Substring a String depending on int

Body:
I wanted to substring a String depending on int that I will passed on the method. I used nested loop for this. But everytime it loops I wanted to substring only from last substring to int the I passed in the method and get also the last string. How can I achieve this?

private static void input(String s, int I)
{
    List list = new ArrayList();

    for(int a = 0; a < s.length(); a++)
    {
        for(int position = 0; position < s.length(); position++)
        {
            if(position + a + I <= s.length())
            {
                list.add(s.substring(position, position + a + I));
            }
        }
    }

}

input("abaca", 2);

Expected output: "ab", "ac", "a"

Body:
It's really better to completely rewrite your code, but if you want to save your structure(even though it's not correct), just remove 1 loop and do something like this:

private static void input(String s, int I) {
    List list = new ArrayList();

    for (int position = 0; position < s.length();position += I) {
        if (position + I <= s.length()) {
            list.add(s.substring(position, position + I));
        } else {
            list.add(s.substring(position, s.length()));
            return;
        }
    }
}


问:
What's "s" mean in result of `ls -l`?
I'm running ls -l, result is

```<code>[root@yf-mos-test-net09 b2cebb02-d171-4929-95d6-61e54cd647f7]# ls /usr/local/var/run/openvswitch/n-ddc979cd -l
srwxr-x--- 1 root root 0 Jun  8 15:53 /usr/local/var/run/openvswitch/n-ddc979cd
</code>```

what's "s" mean in "srwxr-x---" ?

Thank you!

答: The first letter is for file type. The 's' means it's a socket.</p>

Title: What's "s" mean in result of `ls -l`?

Body:
I'm running ls -l, result is

[root@yf-mos-test-net09 b2cebb02-d171-4929-95d6-61e54cd647f7]# ls /usr/local/var/run/openvswitch/n-ddc979cd -l
srwxr-x--- 1 root root 0 Jun  8 15:53 /usr/local/var/run/openvswitch/n-ddc979cd

what's "s" mean in "srwxr-x---" ?

Thank you!


问:
Erlang workflow
How do you organize your erlang workflow? I'm learning some Erlang now and I'm using Rebar, recompiling, rebuilding and restarting an entire release (I'm trying to keep things OTP'ish) after each edit. I'm pretty sure that there is a smarter way to do this.</p>

答:
For automatic reloading of src files with each edit, You can try auto plugin in rebar3.

I have recently moved to rebar3 and found it to have much easier to work with compared to rebar.

ContentLicense: CC BY-SA 2.5

Title: Erlang workflow


问:
Save data in sd card using appcelerator for android 6 and above
I try to save data(.csv) in sd card using my mobile application develop using appcelerator.

For android 5 and below it success the csv can store in sd card but in android 6 and 7 I cant find the file.

I'm using this code : Ti.Filesystem.externalStorageDirectory from http://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage

the code is

```<code>exports.exportCsvData = function(input)
{
var rowTxt = "";
for(var i=0;i < input.length; i++){
    for(var j = 0; j < input[i].length; j++){
        rowTxt += '"' + input[i][j] + '"';

        if(j < (input[i].length-1))
        {
            rowTxt += ',';
        }
    }
    rowTxt += '\n';// adding new line at end of row
}

// creating output file in application data directory
// option 1
   var outputFile = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory,'output.csv');

outputFile.write(rowTxt);

if(outputFile.exists){
    alert("CSV generated!!!");
}

return outputFile.nativePath;
};
</code>```

I also give permission to save file in sd card :

```<code><manifest>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
</code>```

can help me to solve this problem.

答:
In Android 6.0 and above you should ask for certain permissions during runtime.
You can check the "Permissions" section here:

http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Android

There is an example how you can do that.
More detailed explanation on Android side you can find here:

https://developer.android.com/training/permissions/requesting.html

Body:
I try to save data(.csv) in sd card using my mobile application develop using appcelerator.

For android 5 and below it success the csv can store in sd card but in android 6 and 7 I cant find the file.

I'm using this code : Ti.Filesystem.externalStorageDirectory from http://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage

the code is

exports.exportCsvData = function(input)
{
var rowTxt = "";
for(var i=0;i < input.length; i++){
    for(var j = 0; j < input[i].length; j++){
        rowTxt += '"' + input[i][j] + '"';

        if(j < (input[i].length-1))
        {
            rowTxt += ',';
        }
    }
    rowTxt += '\n';// adding new line at end of row
}

// creating output file in application data directory
// option 1
   var outputFile = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory,'output.csv');

outputFile.write(rowTxt);

if(outputFile.exists){
    alert("CSV generated!!!");
}

return outputFile.nativePath;
};

I also give permission to save file in sd card :

<manifest>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

can help me to solve this problem.


问:
predicting from flexmix object (R)
I fit some data to a mixture distribution of two gaussian in flexmix:

```<code>data("NPreg", package = "flexmix")
mod <- flexmix(yn ~ x, data = NPreg, k = 2,
           model = list(FLXMRglm(yn ~ x, family= "gaussian"),
                        FLXMRglm(yn ~ x, family = "gaussian")))
</code>```

the model fit is as follows:

```<code>> mod

Call:
flexmix(formula = yn ~ x, data = NPreg, k = 2, model =    list(FLXMRglm(yn ~ x, family = "gaussian"),
    FLXMRglm(yn ~ x, family = "gaussian")))

Cluster sizes:
  1   2
 74 126

convergence after 31 iterations
</code>```

But how do I actually predict from this model?

when I do

```<code>pred <- predict(mod, NPreg)
</code>```

I get a list with the predictions from each of the two components

To get a single prediction, do I have to add in the cluster sizes like this?

```<code>single <- (74/200)* pred$Comp.1[,1] + (126/200)*pred$Comp.2[,2]
</code>```

答:
You can pass an additional argument to your prediction call.</p>

```<code>pred <- predict(mod, NPreg, aggregate = TRUE)[[1]][,1]
</code>```

Title: predicting from flexmix object (R)

Body:
I fit some data to a mixture distribution of two gaussian in flexmix:

data("NPreg", package = "flexmix")
mod <- flexmix(yn ~ x, data = NPreg, k = 2,
           model = list(FLXMRglm(yn ~ x, family= "gaussian"),
                        FLXMRglm(yn ~ x, family = "gaussian")))

the model fit is as follows:

> mod

Call:
flexmix(formula = yn ~ x, data = NPreg, k = 2, model =    list(FLXMRglm(yn ~ x, family = "gaussian"),
    FLXMRglm(yn ~ x, family = "gaussian")))

Cluster sizes:
  1   2
 74 126

convergence after 31 iterations

But how do I actually predict from this model?

when I do

pred <- predict(mod, NPreg)

I get a list with the predictions from each of the two components

To get a single prediction, do I have to add in the cluster sizes like this?

single <- (74/200)* pred$Comp.1[,1] + (126/200)*pred$Comp.2[,2]

Body:
You can pass an additional argument to your prediction call.

pred <- predict(mod, NPreg, aggregate = TRUE)[[1]][,1]


问:
IBM Worklight - Why sql query used in worklight.js and what is use of that in application
We have observed that in worklight.js file below sql query is being used.

```<code>selectStmt.text = "SELECT * FROM cookies WHERE name=\"" + cookieName + "\"";
</code>```

Please let us know why this is being used and where application is using the same. Is there any security concern on the same.

答:
This is valid only in case of Adobe AIR environments. By design , in case of Adobe AIR , cookies are stored in a SQLLite DB. The query you noted is to retrieve the cookie from this SQLLite DB.

This is not applicable to any other MFP environments ( hybrid or native).
If you are using Adobe AIR environment, this is expected behaviour.

Body:
We have observed that in worklight.js file below sql query is being used.

selectStmt.text = "SELECT * FROM cookies WHERE name=\"" + cookieName + "\"";

Please let us know why this is being used and where application is using the same. Is there any security concern on the same.


问:
How to make list-menu display when it have class active?

jQuery(document).ready(function() {
  $(".list-menu").hide();
  $(".head-list a").click(function() {
    $(".list-menu:visible").slideUp('slow');
    $(".head-list").removeClass('active-menu');
    $(this).parent().addClass('active-menu').next().slideDown('slow');
    return false;
  });
  if ($(".list-menu ul li").hasClass('active')) {
    $(".list-menu").show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="head-list">Puchase</div>
<div class="list-menu">
  <ul>
    <li class="<?php if($page == 'home'){ echo 'active';} ?>">Purchase</li>
    <li>Purchase List</li>
    <li>Purchase3</li>
    <li>Purchase4</li>
    <li>Purchase5</li>
  </ul>
</div></code>```

I Wanna it to display the .list-menu that have ul li class active only.

Thank You for your answers.

答:
Here You can use it

```<code>$page=basename($_SERVER['PHP_SELF']);
<li  class="menu-dropdown <?php
if(basename($_SERVER['PHP_SELF'])=="home.php"){ echo 'active'; } ?> ">
</code>```

Hope it will work properlly

Body:
jQuery(document).ready(function() {
  $(".list-menu").hide();
  $(".head-list a").click(function() {
    $(".list-menu:visible").slideUp('slow');
    $(".head-list").removeClass('active-menu');
    $(this).parent().addClass('active-menu').next().slideDown('slow');
    return false;
  });
  if ($(".list-menu ul li").hasClass('active')) {
    $(".list-menu").show();
  }
});

Puchase

    <li class="<?php if($page == 'home'){ echo 'active';} ?>">Purchase

Purchase List

Purchase3

Purchase4

Purchase5

I Wanna it to display the .list-menu that have ul li class active only.

Thank You for your answers.

Body:
Here You can use it

$page=basename($_SERVER['PHP_SELF']);
<li  class="menu-dropdown <?php
if(basename($_SERVER['PHP_SELF'])=="home.php"){ echo 'active'; } ?> ">

Hope it will work properlly


问:
how to create a dropdown list in iphone?
i did a view based application and it tat thr 3 buttons and when i click each different subviews are displayed for performing different actions.when i click 1st button it should show a textfield to enter the items---for this i should have a drop down list to list the items available so that user can select the items from there.if i use pickerview then how i should display it as it may occupy more screen space.and if there is any other method pls give me the code.

could anyone help me with clear codes to complete this task pls.

thanku

答: I would suggest learning the Alarm.app when you set the recurrences of an alarm. A check in front of a table view cell is usually the best way to implement a similar dropdownlist in web terms.</p>


问:
running rsync with quoted arguments using python's subprocess
I've got some automation backup script that executing rsync using subprocess module.
It was all fine until the new requirement to specify ssh identity file.

According to rsync manuals, ssh identity should be passed as quoted string:

```<code>-e "ssh -i /home/username/.ssh/identity"
</code>```

But this will fail to run in subprocess:

```<code>subprocess.Popen(['rsync', '-avz', '-e "ssh -i /home/username/.ssh/identity"', '~/Downloads', 'root@remote_server:/lvm/archive/backup'])
<subprocess.Popen object at 0x7fd111939710>
rsync: Failed to exec ssh -i /home/username/.ssh/identity: No such file or directory (2)
rsync error: error in IPC code (code 14) at pipe.c(85) [sender=3.1.0]
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in IPC code (code 14) at io.c(226) [sender=3.1.0]
</code>```

Any idea?

Thanks

答: subprocess.Popen(['rsync', '-avz', '-e', 'ssh -i /home/username/.ssh/identity', '~/Downloads', 'root@remove_server:/lvm/archive/backup'])

Body:
I've got some automation backup script that executing rsync using subprocess module.
It was all fine until the new requirement to specify ssh identity file.

According to rsync manuals, ssh identity should be passed as quoted string:

-e "ssh -i /home/username/.ssh/identity"

But this will fail to run in subprocess:

subprocess.Popen(['rsync', '-avz', '-e "ssh -i /home/username/.ssh/identity"', '~/Downloads', 'root@remote_server:/lvm/archive/backup'])
<subprocess.Popen object at 0x7fd111939710>
rsync: Failed to exec ssh -i /home/username/.ssh/identity: No such file or directory (2)
rsync error: error in IPC code (code 14) at pipe.c(85) [sender=3.1.0]
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in IPC code (code 14) at io.c(226) [sender=3.1.0]

Any idea?

Thanks


问:
PL/SQL Trigger Mutating Table on compound trigger
writing a trigger on table that updates another table on oracle
trigger throws mutating table error.
I know the error is coming because i am updating the table that is reference in my row level block but i cannot figure out a work around

EDIT: This code throws a PL/SQL: numeric or value error: NULL index table key value but i seem to have gotten around the mutating table.

```<code>create or replace TRIGGER DSPLATE_WELL_VOLUME_V3
FOR UPDATE ON DSPLATE
COMPOUND TRIGGER

TYPE t_PLATE_ID IS TABLE OF DSPLATE.PLATE_ID%TYPE;
v_PLATE_ID  t_PLATE_ID;
TYPE t_NEW_AMOUNT IS TABLE OF DSPLATE.AMOUNT%TYPE;
v_NEW_AMOUNT  t_NEW_AMOUNT;

BEFORE STATEMENT IS
BEGIN
    v_PLATE_ID := t_PLATE_ID();
    v_NEW_AMOUNT := t_NEW_AMOUNT();
END BEFORE STATEMENT;

BEFORE EACH ROW IS
BEGIN
  IF :NEW.PLATE_TYPE != :OLD.PLATE_TYPE AND :NEW.PLATE_TYPE = 'Assay Plate'
      AND :NEW.AMOUNT_INITIAL IS NOT NULL AND :OLD.AMOUNT_INITIAL IS NULL THEN
           v_PLATE_ID(v_PLATE_ID.LAST) := :OLD.PLATE_ID;
           v_NEW_AMOUNT(v_NEW_AMOUNT.LAST) := :NEW.AMOUNT_INITIAL;
  END IF;
END BEFORE EACH ROW;

AFTER STATEMENT IS
BEGIN
    FOR p IN 1..v_PLATE_ID.LAST LOOP
                  UPDATE DSPLATE_WELL
            SET AMOUNT = AMOUNT - v_NEW_AMOUNT(p)
              WHERE WELL_ID IN (SELECT DSPLATE_WELL.WELL_ID
              FROM DSPLATE INNER JOIN DSPLATE_WELL ON DSPLATE_WELL.PLATE_ID = DSPLATE.PLATE_ID
              WHERE DSPLATE_WELL.WELL_VALUE IN (SELECT DSPLATE_WELL.WELL_VALUE
              FROM DSPLATE_WELL INNER JOIN DSPLATE ON DSPLATE.PLATE_ID = DSPLATE_WELL.PLATE_ID WHERE DSPLATE.PLATE_ID = v_PLATE_ID(p))
              AND DSPLATE.PLATE_TYPE = 'Cherry Pick Plate' AND DSPLATE.LOCATION_ID = 1420);
        END LOOP;
END AFTER STATEMENT;

END;
</code>```

The original trigger i wrote that worked is this but I want it to be written as a compound trigger instead, when a plate_type is set to 'assay plate' the query looks up all well_values of that plate_id on table DSPLATE_WELL, the well_values correspond back to many different plate_ids on table DSPLATE with plate_type 'cherry pick' and specific WELL_IDs where the WELL_VALUES originally came from must have their volume amount updated.

```<code>create or replace TRIGGER INSERT_DSPLATE_WELL_VOLUME
AFTER UPDATE ON DSPLATE
FOR EACH ROW
DECLARE
pragma autonomous_transaction;

BEGIN
  IF :NEW.PLATE_TYPE != :OLD.PLATE_TYPE AND :NEW.PLATE_TYPE = 'Assay Plate'
AND :NEW.AMOUNT_INITIAL IS NOT NULL AND :OLD.AMOUNT_INITIAL IS NULL
  THEN
      UPDATE DSPLATE_WELL
        SET AMOUNT = AMOUNT - :NEW.AMOUNT_INITIAL
          WHERE WELL_ID IN (SELECT DSPLATE_WELL.WELL_ID
          FROM DSPLATE INNER JOIN DSPLATE_WELL ON DSPLATE_WELL.PLATE_ID = DSPLATE.PLATE_ID
          WHERE DSPLATE_WELL.WELL_VALUE IN (SELECT DSPLATE_WELL.WELL_VALUE
          FROM DSPLATE_WELL INNER JOIN DSPLATE ON DSPLATE.PLATE_ID = DSPLATE_WELL.PLATE_ID WHERE DSPLATE.PLATE_ID = :OLD.PLATE_ID)
          AND DSPLATE.PLATE_TYPE = 'Cherry Pick Plate' AND DSPLATE.LOCATION_ID = 1420);
          COMMIT;
  END IF;
END;
</code>```

答: I had written similar compound triggers and I used "before statement" to catch the values (I had used a SELECT to fill a structure with bulk collect) and "after each row" to update.</p>

Body:
writing a trigger on table that updates another table on oracle
trigger throws mutating table error.
I know the error is coming because i am updating the table that is reference in my row level block but i cannot figure out a work around

EDIT: This code throws a PL/SQL: numeric or value error: NULL index table key value but i seem to have gotten around the mutating table.

create or replace TRIGGER DSPLATE_WELL_VOLUME_V3
FOR UPDATE ON DSPLATE
COMPOUND TRIGGER

TYPE t_PLATE_ID IS TABLE OF DSPLATE.PLATE_ID%TYPE;
v_PLATE_ID  t_PLATE_ID;
TYPE t_NEW_AMOUNT IS TABLE OF DSPLATE.AMOUNT%TYPE;
v_NEW_AMOUNT  t_NEW_AMOUNT;

BEFORE STATEMENT IS
BEGIN
    v_PLATE_ID := t_PLATE_ID();
    v_NEW_AMOUNT := t_NEW_AMOUNT();
END BEFORE STATEMENT;

BEFORE EACH ROW IS
BEGIN
  IF :NEW.PLATE_TYPE != :OLD.PLATE_TYPE AND :NEW.PLATE_TYPE = 'Assay Plate'
      AND :NEW.AMOUNT_INITIAL IS NOT NULL AND :OLD.AMOUNT_INITIAL IS NULL THEN
           v_PLATE_ID(v_PLATE_ID.LAST) := :OLD.PLATE_ID;
           v_NEW_AMOUNT(v_NEW_AMOUNT.LAST) := :NEW.AMOUNT_INITIAL;
  END IF;
END BEFORE EACH ROW;

AFTER STATEMENT IS
BEGIN
    FOR p IN 1..v_PLATE_ID.LAST LOOP
                  UPDATE DSPLATE_WELL
            SET AMOUNT = AMOUNT - v_NEW_AMOUNT(p)
              WHERE WELL_ID IN (SELECT DSPLATE_WELL.WELL_ID
              FROM DSPLATE INNER JOIN DSPLATE_WELL ON DSPLATE_WELL.PLATE_ID = DSPLATE.PLATE_ID
              WHERE DSPLATE_WELL.WELL_VALUE IN (SELECT DSPLATE_WELL.WELL_VALUE
              FROM DSPLATE_WELL INNER JOIN DSPLATE ON DSPLATE.PLATE_ID = DSPLATE_WELL.PLATE_ID WHERE DSPLATE.PLATE_ID = v_PLATE_ID(p))
              AND DSPLATE.PLATE_TYPE = 'Cherry Pick Plate' AND DSPLATE.LOCATION_ID = 1420);
        END LOOP;
END AFTER STATEMENT;

END;

The original trigger i wrote that worked is this but I want it to be written as a compound trigger instead, when a plate_type is set to 'assay plate' the query looks up all well_values of that plate_id on table DSPLATE_WELL, the well_values correspond back to many different plate_ids on table DSPLATE with plate_type 'cherry pick' and specific WELL_IDs where the WELL_VALUES originally came from must have their volume amount updated.

create or replace TRIGGER INSERT_DSPLATE_WELL_VOLUME
AFTER UPDATE ON DSPLATE
FOR EACH ROW
DECLARE
pragma autonomous_transaction;

BEGIN
  IF :NEW.PLATE_TYPE != :OLD.PLATE_TYPE AND :NEW.PLATE_TYPE = 'Assay Plate'
AND :NEW.AMOUNT_INITIAL IS NOT NULL AND :OLD.AMOUNT_INITIAL IS NULL
  THEN
      UPDATE DSPLATE_WELL
        SET AMOUNT = AMOUNT - :NEW.AMOUNT_INITIAL
          WHERE WELL_ID IN (SELECT DSPLATE_WELL.WELL_ID
          FROM DSPLATE INNER JOIN DSPLATE_WELL ON DSPLATE_WELL.PLATE_ID = DSPLATE.PLATE_ID
          WHERE DSPLATE_WELL.WELL_VALUE IN (SELECT DSPLATE_WELL.WELL_VALUE
          FROM DSPLATE_WELL INNER JOIN DSPLATE ON DSPLATE.PLATE_ID = DSPLATE_WELL.PLATE_ID WHERE DSPLATE.PLATE_ID = :OLD.PLATE_ID)
          AND DSPLATE.PLATE_TYPE = 'Cherry Pick Plate' AND DSPLATE.LOCATION_ID = 1420);
          COMMIT;
  END IF;
END;


问:
Differentiate Numbers and Date in MSExcel
I am processing a large set of data. The data contain both numbers, String and Date. I want to differentiate between Date, String and Numbers. I am facing problem in differentiating between Numbers and Date.

I am currently using the below formula.

```<code>=(IF(TYPE(A1)=2,A1,TEXT(A1,"mmmm d, yyyy"))&"& "&IF(TYPE(B1)=2,B1,TEXT(B1,"mmmm d, yyyy"))&"& "&IF(TYPE(C1)=2,C1,TEXT(C1,"mmmm d, yyyy")))
</code>```

If I give 1, It is formatting it as Date January 01, 1900

Even I tried ISNUMBER function, It's returning true for a date as well, e.g: ISNUMBER(10/01/1900).

答:
ISNUMBER doesn't work because dates are numbers in actual sense. It's just the formatting that makes them appears as dates. For example 00/01/1900 is 0 formatted as a date. The same applies for TYPE function as it will return a 1 for a number (whether the number is formatted as a number or date)

Use this:

```<code>=LEFT(CELL("format",A1),1)
</code>```

It returns a d if A1 is formatted as date.

Body:
I am processing a large set of data. The data contain both numbers, String and Date. I want to differentiate between Date, String and Numbers. I am facing problem in differentiating between Numbers and Date.

I am currently using the below formula.

=(IF(TYPE(A1)=2,A1,TEXT(A1,"mmmm d, yyyy"))&"& "&IF(TYPE(B1)=2,B1,TEXT(B1,"mmmm d, yyyy"))&"& "&IF(TYPE(C1)=2,C1,TEXT(C1,"mmmm d, yyyy")))

If I give 1, It is formatting it as Date January 01, 1900

Even I tried ISNUMBER function, It's returning true for a date as well, e.g: ISNUMBER(10/01/1900).

Body:
ISNUMBER doesn't work because dates are numbers in actual sense. It's just the formatting that makes them appears as dates. For example 00/01/1900 is 0 formatted as a date. The same applies for TYPE function as it will return a 1 for a number (whether the number is formatted as a number or date)

Use this:

=LEFT(CELL("format",A1),1)

It returns a d if A1 is formatted as date.


问:
Display the saved images in dropzone after the page is loaded
Now, I use dropzone to implement the image upload and same the images into collectionFS, after upload I can see the images in dropzone, but after refresh the page, there is no images display.I can get the saved images from collectionFS, but how to set the value we can display the images when the page is loaded.
according to the checking for dropzone.js file, in the following file, it will define "this.files = []; whether we can pass one savefiles as one options items to this.files? after that, it can load saved files when page is load.
function Dropzone(element, options) </p>

答:
according to the following description from https://github.com/enyo/dropzone/wiki/FAQ, it can dispaly the image.

```<code>var mockFile = { name: image.name, size: image.size};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, image.url());
myDropzone.emit("complete", mockFile);
</code>```

but the size of image is not correct, it does not resize. so use the following:

```<code>myDropzone.createThumbnailFromUrl(mockFile, image.url());
</code>```

but the image can not display.
the image is added firstly, and save it into gridfs, after that, reload the page to get image.
is there any wrong to use dropzone?****

Body:
according to the following description from https://github.com/enyo/dropzone/wiki/FAQ, it can dispaly the image.

var mockFile = { name: image.name, size: image.size};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, image.url());
myDropzone.emit("complete", mockFile);

but the size of image is not correct, it does not resize. so use the following:

myDropzone.createThumbnailFromUrl(mockFile, image.url());

but the image can not display.
the image is added firstly, and save it into gridfs, after that, reload the page to get image.
is there any wrong to use dropzone?****


问:
How to verify signature with pss padding?
We created debug public and private keys for RSA sign.
And we generate sha256 hash and save in cp1.bin.
Then we try to verify signature but always failed.
If we don't use pss padding, the verify command will pass.
Anyone can please help to comment?

Thanks

C:\Project\pkc>openssl pkeyutl -sign -in cp1.bin -inkey pvt_dbg.pem  -out sig1.bin -pkeyopt digest:sha256 -pkeyopt rsa_padding_mode:pss -pkeyopt rsa_pss_saltlen:32

C:\Project\pkc>openssl pkeyutl -verify -in cp1.bin -sigfile sig1.bin -pkeyopt rsa_padding_mode:pss -pkeyopt rsa_pss_saltlen:32 -pubin -inkey pub_dbg.pem
Signature Verification Failure

答:
Can run verify command successfully now.

```<code>$ openssl pkeyutl -sign \
  -in hashOut.bin -inkey pvt_dbg.pem \
  -out sig1.bin \
  -pkeyopt digest:sha256 \
  -pkeyopt rsa_padding_mode:pss \
  -pkeyopt rsa_pss_saltlen:-1
</code>```

Then

```<code>$ openssl pkeyutl -verify \
  -in cp1.bin -sigfile sig1.bin \
  -pkeyopt rsa_padding_mode:pss \
  -pubin -inkey pub_dbg.pem \
  -pkeyopt rsa_pss_saltlen:-1 \
  -pkeyopt digest:sha256
</code>```

Body:
Can run verify command successfully now.

$ openssl pkeyutl -sign \
  -in hashOut.bin -inkey pvt_dbg.pem \
  -out sig1.bin \
  -pkeyopt digest:sha256 \
  -pkeyopt rsa_padding_mode:pss \
  -pkeyopt rsa_pss_saltlen:-1

Then

$ openssl pkeyutl -verify \
  -in cp1.bin -sigfile sig1.bin \
  -pkeyopt rsa_padding_mode:pss \
  -pubin -inkey pub_dbg.pem \
  -pkeyopt rsa_pss_saltlen:-1 \
  -pkeyopt digest:sha256


问:
How to run sudo -u username command in Ansible?
I want to run a specific command as sudo -u username <command name> using Ansible.

I tried below task, but facing permissions issue.

```<code>---
-
  hosts: all
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: "Create solr cores"
      shell: /opt/apps/solr/bin/solr create -c test10
      become_flags: '-u solr'
      register: core_one
#      changed_when: '"\"status\":0" in core_one.stdout'
</code>```

Could anyone suggest on this?

答:
The correct way to run a task is the following.

Having proper permissions is a prerequisite. Refer to man sudoers to learn more

```<code>- name: "Create solr cores"
  shell: /opt/apps/solr/bin/solr create -c test10
  become: yes
  become_user: solr
  register: core_one
</code>```

You already have become: yes on the play level, so just for clarity.

Body:
I want to run a specific command as sudo -u username <command name> using Ansible.

I tried below task, but facing permissions issue.

---
-
  hosts: all
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: "Create solr cores"
      shell: /opt/apps/solr/bin/solr create -c test10
      become_flags: '-u solr'
      register: core_one
#      changed_when: '"\"status\":0" in core_one.stdout'

Could anyone suggest on this?

Body:
The correct way to run a task is the following.

Having proper permissions is a prerequisite. Refer to man sudoers to learn more

- name: "Create solr cores"
  shell: /opt/apps/solr/bin/solr create -c test10
  become: yes
  become_user: solr
  register: core_one

You already have become: yes on the play level, so just for clarity.


问:
PyCharm: How to document :rtype: for function that returns generator
I try to document a :rtype: docstring parameter returning a generator of Node:

```<code>def __iter__(self):
    """iterate over node children

    :rtype: ???
    """
    for node in self.children.itervalues():
        yield node
</code>```

What :rtype: is supposed to be? generator of Node doesn't seems to work.

答:
You can hint the type of self.children using :type below it, as described in the official documentation. This would let you work with this variable everywhere using defined types. Here is an example:

```<code>class Node(object):
    def foo(self):
        pass

class Iterator(object):
    def __init__(self):
        self.children = ''
        """:type: dict[str, Node]"""   # <<< define type of self.children after assigning the value

    def __iter__(self):
        for node in self.children.itervalues():
            yield node

if __name__ == '__main__':
    for node in Iterator():
        node. # <<< type hinting will work here
</code>```

But if you prefer to set the return type of __iter__ method, you can do it using next syntax:

```<code>def __iter__(self):
    """
    :rtype: collections.Iterable[Node]
    """
    for node in self.children.itervalues():
        yield node
</code>```

I would prefer first solution though.

Body:
I try to document a :rtype: docstring parameter returning a generator of Node:

def __iter__(self):
    """iterate over node children

    :rtype: ???
    """
    for node in self.children.itervalues():
        yield node

What :rtype: is supposed to be? generator of Node doesn't seems to work.

Body:
You can hint the type of self.children using :type below it, as described in the official documentation. This would let you work with this variable everywhere using defined types. Here is an example:

class Node(object):
    def foo(self):
        pass

class Iterator(object):
    def __init__(self):
        self.children = ''
        """:type: dict[str, Node]"""   # <<< define type of self.children after assigning the value

    def __iter__(self):
        for node in self.children.itervalues():
            yield node

if __name__ == '__main__':
    for node in Iterator():
        node. # <<< type hinting will work here

But if you prefer to set the return type of __iter__ method, you can do it using next syntax:

def __iter__(self):
    """
    :rtype: collections.Iterable[Node]
    """
    for node in self.children.itervalues():
        yield node

I would prefer first solution though.


问:
need to loop through a PHP array in JavaScript
For example I have a PHP array, such as this one

```<code><?php $s= array('a','b','c','d','e','f') ; ?>
</code>```

And I need to loop through it in JavaScript, any ideas how do I do that?

```<code>for ( i=0 ; i < <?php echo sizeof($s) ?> ; i++) {
document.write('<?php echo $s [somehow need to get the 'i' value into here] ?>');
}
</code>```

Any suggestions? Thanks!

答:
```<code><?php $product = array('1'=>'acids','2'=>'chemical','3'=>'microbilogy'); ?>

<script>

  <select name="product_id" class="form-control">
  <?php foreach ($product as $key => $value)
  { echo" <option value=$value[product_id]> $value['product_name']
   </option>";  } ?>
  </select>

</script>
</code>```

if this is helpfull please give a thumbs up

Body:
For example I have a PHP array, such as this one

<?php $s= array('a','b','c','d','e','f') ; ?>

And I need to loop through it in JavaScript, any ideas how do I do that?

for ( i=0 ; i < <?php echo sizeof($s) ?> ; i++) {
document.write('<?php echo $s [somehow need to get the 'i' value into here] ?>');
}

Any suggestions? Thanks!

Body:
<?php $product = array('1'=>'acids','2'=>'chemical','3'=>'microbilogy'); ?>

<script>

  <select name="product_id" class="form-control">
  <?php foreach ($product as $key => $value)
  { echo" <option value=$value[product_id]> $value['product_name']
   </option>";  } ?>
  </select>

</script>

if this is helpfull please give a thumbs up


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
If they don't have to perform really advanced queries you could provide a ui that only allows certain choices, like a drop down list with "update,delete,select" then the next ddl would automatically populate with a list of available tables etc.. similar to query builder in sql management studio.

Then in your server side code you would convert these groups of ui elements into sql statements and use a parametrized query to stop malicious content

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis


问:
combine tables related to each other by a linking table and not to worry if the linking table is missing some data
I have a simple relational database set up similar to the example below

```<code>[Customer] --< [CGLink] >-- [Order]

Person:
Alias Name(PK)
A     Bill
B     Ben
C     Bob
D     Jim
E     John

CGLink:
ID(PK) Alias Type
1      A     W
2      A     X
3      B     W
4      B     X
5      B     Y
6      B     Z
7      C     Y
8      E     Z

Group:
Type(PK) Group
W        Double-U
X        Eks
Y        Whai
Z        Zed
</code>```

And I want to return a set of results like

```<code>Alias   Name   Group
A       Bill   Double-U
A       Bill   Eks
B       Ben    Double-U
B       Ben    Eks
B       Ben    Whai
B       Ben    Zed
C       Bob    Whai
D       Jim
E       John   Zed
</code>```

As you can see Jim had no associated data in the linking table and I want to avoid having to place a row of dummy data that I can link all people to who don't have a group in order to let me return this data.

The query I am using is

```<code>SELECT p.Alias, p.Name, g.Group
FROM Person AS p, Group AS s, CGLink AS l
WHERE (p.Alias=l.Alias
AND l.Type=s.Type)
ORDER BY p.Alias, p.Name;
</code>```

This returns

```<code>Alias   Name   Group
A       Bill   Double-U
A       Bill   Eks
B       Ben    Double-U
B       Ben    Eks
B       Ben    Whai
B       Ben    Zed
C       Bob    Whai
E       John   Zed
</code>```

Which as you can see, is missing Jim because he had no associated group.
How can I obtain the results I really want?

Cheers

答:
Try using an OUTER join</p>

```<code>SELECT p.Alias, p.Name, g.Group
FROM Person AS p
LEFT OUTER JOIN Group AS s ON p.Alias=l.Alias
LEFT OUTER JOIN CGLink AS l ON l.Type=s.Type
ORDER BY p.Alias, p.Name;
</code>```

Body:
I have a simple relational database set up similar to the example below

[Customer] --< [CGLink] >-- [Order]

Person:
Alias Name(PK)
A     Bill
B     Ben
C     Bob
D     Jim
E     John

CGLink:
ID(PK) Alias Type
1      A     W
2      A     X
3      B     W
4      B     X
5      B     Y
6      B     Z
7      C     Y
8      E     Z

Group:
Type(PK) Group
W        Double-U
X        Eks
Y        Whai
Z        Zed

And I want to return a set of results like

Alias   Name   Group
A       Bill   Double-U
A       Bill   Eks
B       Ben    Double-U
B       Ben    Eks
B       Ben    Whai
B       Ben    Zed
C       Bob    Whai
D       Jim
E       John   Zed

As you can see Jim had no associated data in the linking table and I want to avoid having to place a row of dummy data that I can link all people to who don't have a group in order to let me return this data.

The query I am using is

SELECT p.Alias, p.Name, g.Group
FROM Person AS p, Group AS s, CGLink AS l
WHERE (p.Alias=l.Alias
AND l.Type=s.Type)
ORDER BY p.Alias, p.Name;

This returns

Alias   Name   Group
A       Bill   Double-U
A       Bill   Eks
B       Ben    Double-U
B       Ben    Eks
B       Ben    Whai
B       Ben    Zed
C       Bob    Whai
E       John   Zed

Which as you can see, is missing Jim because he had no associated group.
How can I obtain the results I really want?

Cheers

Body:
Try using an OUTER join

SELECT p.Alias, p.Name, g.Group
FROM Person AS p
LEFT OUTER JOIN Group AS s ON p.Alias=l.Alias
LEFT OUTER JOIN CGLink AS l ON l.Type=s.Type
ORDER BY p.Alias, p.Name;


问:
Azure REST API - HTTP PUT request throws error "InvalidResourceGroup","message:"The resource group definition is invalid."
I am accessing Azure REST API using our HPOO's HTTP Client GET/POST/DELETE operations.

However, the http PUT requests containing Request BODY are throwing below error -- It works just fine with Postman app.

"InvalidResourceGroup","message":"The resource group definition is
  invalid."

We tried with API for creating a resource group

URL : https://management.azure.com/subscriptions/62a15758-4127-4b04-ac11-eda0baa41ee5/resourcegroups/RG334

here RG334 is the resource group I'm trying to Create.

2 Headers :

Content-Type : application/json

  Authorization : Bearer token value

Query Parameter and value : api-version, 2015-01-01

Body :

```<code>{
  "location": "West US",
  "tags": {
    "tagname1": "value"
  }
}
</code>```

答: when the request body is empty or invalid, Azure REST API throws this error, Please verify the payload which you are sending.</p>

Body:
I am accessing Azure REST API using our HPOO's HTTP Client GET/POST/DELETE operations.

However, the http PUT requests containing Request BODY are throwing below error -- It works just fine with Postman app.

"InvalidResourceGroup","message":"The resource group definition is
  invalid."

We tried with API for creating a resource group

URL : https://management.azure.com/subscriptions/62a15758-4127-4b04-ac11-eda0baa41ee5/resourcegroups/RG334

here RG334 is the resource group I'm trying to Create.

2 Headers :

Content-Type : application/json

  Authorization : Bearer token value

Query Parameter and value : api-version, 2015-01-01

Body :

{
  "location": "West US",
  "tags": {
    "tagname1": "value"
  }
}


问:
Appium Error: Couldn't start Appium REST http interface listener. Requested address is not available
I have a mac and I'm trying to run Appium to run iOS tests.

I'm using the Appium app for this, I looked on the troubleshoot section and I think everything is setup as it should, but the app give me this error:
"Couldn't start Appium REST http interface listener. Requested address is not available"

Someone know how can I fix this issue?

答:
Start the Windows Task Manager by pressing ctrl+alt+del (or open up Activity Monitor on your Mac). Under Processes tab kill the node.exe process. Try to start the Appium server again.

Solution from SO post : Appium: Couldn't start the appium server in Windows


问:
How to force Javapoet to create UTF-8 Java source code?
Is there a way to write a com.squareup.javapoet.JavaFile to the file system and make sure the file always is encoded using UTF-8?

Currently I am using com.squareup.javapoet.JavaFile#writeTo(java.io.File dir) but this uses the default encoding of the current virtual machine.

答:
Looking at the Github-Page of Javapoet, you can use the Method:

```<code>JavaFile.writeTo(PrintStream)
</code>```

So you should be able to create a PrintStream using UTF-8 und write the file like this:

```<code>PrintStream stream = new PrintStream("YourTargetFile.java", "UTF-8");
yourJavaFileObject.writeTo(stream);
</code>```

Body:
Looking at the Github-Page of Javapoet, you can use the Method:

JavaFile.writeTo(PrintStream)

So you should be able to create a PrintStream using UTF-8 und write the file like this:

PrintStream stream = new PrintStream("YourTargetFile.java", "UTF-8");
yourJavaFileObject.writeTo(stream);


问:
JS observer pattern
I try the observer pattern (by these two Urls: https://davidwalsh.name/pubsub-javascript, http://www.dofactory.com/javascript/observer-design-pattern) but listeners array is empty when I call the publish function.

```<code>main.pagination.event= (function () {
    var listeners = [];
    return {
        subscribe: function (fn) {
            listeners.push(fn);
            return {
                unsubscribe: function (fn) {
                    listeners= listeners.filter(
                        function (item) {
                            if (item !== fn) {
                                return item;
                            }
                        }
                    );
                }
            };
        },
        publish: function () {
            //it's empty
            listeners.forEach(function (item) {
                item("...");
            });
        }
    };
})();
main.pagination.init = function () {
   $('ul li').click(function () {
      main.pagination.event.publish();
   };
};

main.update.init = function() {
    var event = main.pagination.event.subscribe(main.update.listener);
};

main.update.listener = function (tbl) {
   alert(tbl);
};
</code>```

Thanks for help.

答:
It is empty because you call subscribe after publish which does not contain anything inside the listeners array. Just change the order of the calls like so

```<code>main.update.listener = function (tbl) {
    alert(tbl);
};
main.pagination.init = function () {
    $('ul li').click(function () {
        main.pagination.event.publish();
    };
};

main.update.init = function() {
    var event = main.pagination.event.subscribe(main.update.listener);
};

main.update.init(); // invoke subscribe first to add the listener to the array
main.pagination.init();
</code>```

Title: JS observer pattern

Body:
I try the observer pattern (by these two Urls: https://davidwalsh.name/pubsub-javascript, http://www.dofactory.com/javascript/observer-design-pattern) but listeners array is empty when I call the publish function.

main.pagination.event= (function () {
    var listeners = [];
    return {
        subscribe: function (fn) {
            listeners.push(fn);
            return {
                unsubscribe: function (fn) {
                    listeners= listeners.filter(
                        function (item) {
                            if (item !== fn) {
                                return item;
                            }
                        }
                    );
                }
            };
        },
        publish: function () {
            //it's empty
            listeners.forEach(function (item) {
                item("...");
            });
        }
    };
})();
main.pagination.init = function () {
   $('ul li').click(function () {
      main.pagination.event.publish();
   };
};

main.update.init = function() {
    var event = main.pagination.event.subscribe(main.update.listener);
};

main.update.listener = function (tbl) {
   alert(tbl);
};

Thanks for help.

Body:
It is empty because you call subscribe after publish which does not contain anything inside the listeners array. Just change the order of the calls like so

main.update.listener = function (tbl) {
    alert(tbl);
};
main.pagination.init = function () {
    $('ul li').click(function () {
        main.pagination.event.publish();
    };
};

main.update.init = function() {
    var event = main.pagination.event.subscribe(main.update.listener);
};

main.update.init(); // invoke subscribe first to add the listener to the array
main.pagination.init();


问:
Alternative of state in stateless component
enter code hereI was trying to include the Wheel Picker component to my project. It works well when cover it in the stateful component.So I tried convert it to stateless component, when I scroll the wheel, the selected Index always index to default value( Ex: when I scroll to item number 10, and the wheel auto scroll back to default 0) although I receive the correct values. Is there something wrong with my component?

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

import {
    Component,
    StyleSheet,
    Text,
    View
} from 'react-native';

import Picker from 'react-native-wheel-picker'
var PickerItem = Picker.Item;
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'transparent',
    },

});

const WheelTimePicker = ({selectedItems, receiveTime}) => {
    const _renderPikcer = () => {
       firstData = {
            secondList: [],
            minuteList: [],
        };
    for (var i = 0; i < 60; i++) {
            firstData.secondList.push(i + 'sec');
            firstData.minuteList.push(i + 'min');
        }

        return (
            <View>
             <Picker style={{ left: -70, width: 60, height: 60 }}
                selectedValue={selectedItems.selectedMin}
                itemStyle={{ color: "white", fontSize: 20 }}
                onValueChange={(index) => { selectedItems.selectedMin = index;receiveTime(selectedItems); }}>
                {firstData.minuteList.map((value, i) => (
                    <PickerItem label={value} value={i} key={"money" + value} />
                ))}
            </Picker>
            <Picker style={{ left: 60, width: 60, height: 70 }}
                selectedValue={selectedItems.selectedSec}
                itemStyle={{ color: "white", fontSize: 20 }}
                onValueChange={(index) => { selectedItems.selectedSec = index; receiveTime(selectedItems) }}>
                {firstData.secondList.map((value, i) => (
                    <PickerItem label={value} value={i} key={"money" + value} />
                ))}
            </Picker>
            </View>
        );
   }

    return (

        <View style={styles.container}>
  {_renderPikcer()}

        </View>
    );

};

WheelTimePicker.propTypes = {
     selectedItems: PropTypes.object.isRequired,
  receiveTime: PropTypes.func.isRequired,
};
export default WheelTimePicker;
</code>```

I put the component like this:

```<code> <WheelTimePicker selectedItems={{selectedMin: 2, selectedSec: 0}} receiveTime={(rc)=> _displayTime(rc)}/>
</code>```

答:
This is because you are trying to modify props that is getting passed down from the parent element. I.e. in a stateless component, the parameter passed in is the props. Props are read only (https://facebook.github.io/react/docs/components-and-props.html#props-are-read-only)

Also you are trying to update values inside render function that can potentially live in the state of the component. In this particular scenario, you are trying to modify the content of selectedItems which is a props that is getting passed down to your component.

In order to update the content of selectedItems, it would be better to keep selectedItems as the state in the parent component and use setState to update the values (this is probably your original approach, since you mentioned "It works well when cover it in the stateful component")

For example

```<code>class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: {
        selectedMin: 2,
        selectedSec: 0
      }
    }
  }

  _updateSelectedItems(rc) {
    this.setState({
      selectedItems: {
        selectedMin: rc.selectedMin || this.state.selectedMin,
        selectedSec: rc.selectedSec || this.state.selectedSec
      }
    })
  }

  render() {
    return (
      <WheelTimePicker selectedItems={this.state.selectedItems} receiveTime={(rc) => this._updateSelectedItems(rc)}/>
    )
  }
}
</code>```

This way, your WheelTimePicker component can be stateless. And in your Picker, probably would need to adjust it a little to something like:

```<code><Picker
  ...
  onValueChange={(index) => { receiveTime({selectedMin:index});}}
/>
</code>```

Body:
enter code hereI was trying to include the Wheel Picker component to my project. It works well when cover it in the stateful component.So I tried convert it to stateless component, when I scroll the wheel, the selected Index always index to default value( Ex: when I scroll to item number 10, and the wheel auto scroll back to default 0) although I receive the correct values. Is there something wrong with my component?

import React, {PropTypes} from 'react'

import {
    Component,
    StyleSheet,
    Text,
    View
} from 'react-native';

import Picker from 'react-native-wheel-picker'
var PickerItem = Picker.Item;
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'transparent',
    },

});

const WheelTimePicker = ({selectedItems, receiveTime}) => {
    const _renderPikcer = () => {
       firstData = {
            secondList: [],
            minuteList: [],
        };
    for (var i = 0; i < 60; i++) {
            firstData.secondList.push(i + 'sec');
            firstData.minuteList.push(i + 'min');
        }

        return (
            <View>
             <Picker style={{ left: -70, width: 60, height: 60 }}
                selectedValue={selectedItems.selectedMin}
                itemStyle={{ color: "white", fontSize: 20 }}
                onValueChange={(index) => { selectedItems.selectedMin = index;receiveTime(selectedItems); }}>
                {firstData.minuteList.map((value, i) => (
                    <PickerItem label={value} value={i} key={"money" + value} />
                ))}
            </Picker>
            <Picker style={{ left: 60, width: 60, height: 70 }}
                selectedValue={selectedItems.selectedSec}
                itemStyle={{ color: "white", fontSize: 20 }}
                onValueChange={(index) => { selectedItems.selectedSec = index; receiveTime(selectedItems) }}>
                {firstData.secondList.map((value, i) => (
                    <PickerItem label={value} value={i} key={"money" + value} />
                ))}
            </Picker>
            </View>
        );
   }

    return (

        <View style={styles.container}>
  {_renderPikcer()}

        </View>
    );

};

WheelTimePicker.propTypes = {
     selectedItems: PropTypes.object.isRequired,
  receiveTime: PropTypes.func.isRequired,
};
export default WheelTimePicker;

I put the component like this:

 <WheelTimePicker selectedItems={{selectedMin: 2, selectedSec: 0}} receiveTime={(rc)=> _displayTime(rc)}/>

Body:
This is because you are trying to modify props that is getting passed down from the parent element. I.e. in a stateless component, the parameter passed in is the props. Props are read only (https://facebook.github.io/react/docs/components-and-props.html#props-are-read-only)

Also you are trying to update values inside render function that can potentially live in the state of the component. In this particular scenario, you are trying to modify the content of selectedItems which is a props that is getting passed down to your component.

In order to update the content of selectedItems, it would be better to keep selectedItems as the state in the parent component and use setState to update the values (this is probably your original approach, since you mentioned "It works well when cover it in the stateful component")

For example

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: {
        selectedMin: 2,
        selectedSec: 0
      }
    }
  }

  _updateSelectedItems(rc) {
    this.setState({
      selectedItems: {
        selectedMin: rc.selectedMin || this.state.selectedMin,
        selectedSec: rc.selectedSec || this.state.selectedSec
      }
    })
  }

  render() {
    return (
      <WheelTimePicker selectedItems={this.state.selectedItems} receiveTime={(rc) => this._updateSelectedItems(rc)}/>
    )
  }
}

This way, your WheelTimePicker component can be stateless. And in your Picker, probably would need to adjust it a little to something like:

<Picker
  ...
  onValueChange={(index) => { receiveTime({selectedMin:index});}}
/>


问:
Dynamic formation of variable name in PHP?
The code below dynamically concatenates keys to an existing array $options_pool. So the final form should be: $options_pool[ $base_key ][ $first_key ][ $second_key ]... This is so I can dynamically assign a value to the elements of the array $options_pool which is multidimensional.

```<code>foreach( $this->post_vars as $name => $value ) {
    //Look for $name key in array $options_pool if it exists.
    //Use multi_array_key_exists() to handle the task
    //It should return something like "fruit:mango:apple_mango"
    //Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
    $match_key = multi_array_key_exists( $name, $options_pool );
    $option_keys = explode( ':', $match_key );
    $option_keys_length = count( $option_keys );
    $option_name_array = array();
    if( 0 < $option_keys_length ) {
     for( $c = $option_keys_length; $c > 0; $c-- ) {
         $sub_keys = '$options_pool';
         for( $c_sub = 0; $c_sub < $c ; $c_sub++ ) {
             $sub_keys .= '[ $option_keys[ '.  $c_sub . ' ] ]';
         }
         $option_name_array[] = $sub_keys;
     }
     foreach( $option_name_array as $f_var_name ) {
          //the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
          $f_var_name = $value;
       }
    }
}

//The $options_pool array
$options_pool = array( 'car' => '', 'animals' => '', 'fruit' => array( 'mango' => array( 'apple_mango' => '' ));
</code>```

I think the logic is correct except that this portion of the code:

```<code>foreach( $option_name_array as $f_var_name ) {
    $f_var_name = $value; //particularly this line
}
</code>```

doesn't work? I've tested printing the value of $f_var_name and the result is correct but it doesn't really call the array?

答:
In your foreach, you need to pass the value by reference, so you can edit it.

```<code>foreach( $option_name_array as &$f_var_name ){
  $f_var_name = $value;
}
</code>```

Body:
The code below dynamically concatenates keys to an existing array $options_pool. So the final form should be: $options_pool[ $base_key ][ $first_key ][ $second_key ]... This is so I can dynamically assign a value to the elements of the array $options_pool which is multidimensional.

foreach( $this->post_vars as $name => $value ) {
    //Look for $name key in array $options_pool if it exists.
    //Use multi_array_key_exists() to handle the task
    //It should return something like "fruit:mango:apple_mango"
    //Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
    $match_key = multi_array_key_exists( $name, $options_pool );
    $option_keys = explode( ':', $match_key );
    $option_keys_length = count( $option_keys );
    $option_name_array = array();
    if( 0 < $option_keys_length ) {
     for( $c = $option_keys_length; $c > 0; $c-- ) {
         $sub_keys = '$options_pool';
         for( $c_sub = 0; $c_sub < $c ; $c_sub++ ) {
             $sub_keys .= '[ $option_keys[ '.  $c_sub . ' ] ]';
         }
         $option_name_array[] = $sub_keys;
     }
     foreach( $option_name_array as $f_var_name ) {
          //the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
          $f_var_name = $value;
       }
    }
}

//The $options_pool array
$options_pool = array( 'car' => '', 'animals' => '', 'fruit' => array( 'mango' => array( 'apple_mango' => '' ));

I think the logic is correct except that this portion of the code:

foreach( $option_name_array as $f_var_name ) {
    $f_var_name = $value; //particularly this line
}

doesn't work? I've tested printing the value of $f_var_name and the result is correct but it doesn't really call the array?

Body:
In your foreach, you need to pass the value by reference, so you can edit it.

foreach( $option_name_array as &$f_var_name ){
  $f_var_name = $value;
}


问:
Countif alternative
Im trying to create a file that contains the count of each employee's day off for the whole year. Right now, i'm thinking of using countif:

```<code>=COUNTIF(C21:AG21,"L")+COUNTIF(C35:AG35,"L").... up to last month
</code>```

For me, It's a little bit long and messy. Is there any way to shorten it or any alternative? Thanks!

答:
SUMPRODUCT works in my test.

emp2 can be changed for a cell reference and $A$21:$A$35 to cover all employee names across the year, while $C$21:$CG$35 covers all the days in the year.

=SUMPRODUCT(($A$21:$A$35="emp2")*($C$21:$CG$35="L"))

Title: Countif alternative

Body:
Im trying to create a file that contains the count of each employee's day off for the whole year. Right now, i'm thinking of using countif:

=COUNTIF(C21:AG21,"L")+COUNTIF(C35:AG35,"L").... up to last month

For me, It's a little bit long and messy. Is there any way to shorten it or any alternative? Thanks!


问:
Can't echo value in file python
For example, I have a file python

work1.py

```<code>from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)
</code>```

And i have a file php to run file python via shell_exec function

```<code> <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>
</code>```

But when i run, nothing display. So what's problem? Please help me. Thanks.

答:
I think that the 'sudo' command is probably attempting to prompt you for a password, but there is no way for you to enter one when calling via PHP. Try removing the 'sudo', and perhaps then it will work.

If you need to be root to do some task in your Python script, then consider using setuid flag,
http://linuxg.net/how-to-set-the-setuid-and-setgid-bit-for-files-in-linux-and-unix/

Title: Can't echo value in file python

Body:
For example, I have a file python

work1.py

from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)

And i have a file php to run file python via shell_exec function

 <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>

But when i run, nothing display. So what's problem? Please help me. Thanks.