问:
C# Elegant way to handle checking for an item in a collection
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

```<code>TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }
</code>```

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

答:
Microsoft.SharePoint.Taxonomy.GroupCollection implements IEnumerable<Group>, so a bit of LINQ is probably just what the doctor ordered:-

```<code>if(termStore.Groups.Any(x => x.Name == "MyGroup"))
{
   // group contains at least one item matching the predicate.
}
else
{
   // group contains no items matching the predicate.
}
</code>```

You'll need to be using .NET 3.5 or better and add "using System.Linq;" to the top of your file.

Edit

If you don't have LINQ available, or if it offends you, or if you've genuinely profiled and found that iterating over Groups is killing performance compared to the string indexer, you could use GroupCollection.Count to avoid the error state:-

```<code>if (termStore.Groups.Count == 0 || termStore.Groups[groupName] == null)
{
  // Group doesn't exist.
}
</code>```

Body:
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

Body:
Microsoft.SharePoint.Taxonomy.GroupCollection implements IEnumerable<Group>, so a bit of LINQ is probably just what the doctor ordered:-

if(termStore.Groups.Any(x => x.Name == "MyGroup"))
{
   // group contains at least one item matching the predicate.
}
else
{
   // group contains no items matching the predicate.
}

You'll need to be using .NET 3.5 or better and add "using System.Linq;" to the top of your file.

Edit

If you don't have LINQ available, or if it offends you, or if you've genuinely profiled and found that iterating over Groups is killing performance compared to the string indexer, you could use GroupCollection.Count to avoid the error state:-

if (termStore.Groups.Count == 0 || termStore.Groups[groupName] == null)
{
  // Group doesn't exist.
}


来源: stackexchange

问:
javafx - Alert and stage focus
For my application I need to know whenever the app's window is being focused or not. For this, I can use primaryStage.focusedProperty().addListener(..), which will warn me of changes in focus of the stage.

But I have realized that opening an Alert with this primaryStage as owner and with modality set to WINDOW_MODAL makes the primaryStage loose focus (even though the window is in reality focused, or at least in Windows).

Now the problem that I have is that I want to know when the Window is focused and not just the primaryStage; or at least know if the Alert is being focused, but I could not find how.

I have tried to use similare properties on the alert(like onShowing and onHiding) without success.

Here is a piece of code to illustrate my problem :

```<code>package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));

        primaryStage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("primaryStage focused : "+newValue);
        });
        primaryStage.show();

        //create a basic alert
        Alert alert = new Alert(Alert.AlertType.INFORMATION,"This is a test");
        alert.initModality(Modality.WINDOW_MODAL); //will block input to its owner window
        alert.initOwner(primaryStage);
        alert.onShowingProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onShowing : "+newValue);
        });
        alert.onShownProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onShown : "+newValue);
        });
        alert.onHidingProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onHiding : "+newValue);
        });
        alert.onHiddenProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onHidden : "+newValue);
        });
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Basically it will print this :

```<code>primaryStage focused : true //stage is created and displayed
primaryStage focused : false //alert is displayed, stage loses focus. alt+tab changes nothing
primaryStage focused : true //alert closed by pressing 'ok'
</code>```

Which is strange because of all other prints that it should produce.
Also ideally I would need a :

```<code>primaryStage focused : true //stage is created and displayed
primaryStage focused : false //alert is displayed, stage loses focus
alert focused : true //alert gains focus
alert focused : false //alt+tab to an other window
alert focused : true //alt+tab back to this window
alert focused : false //alert closed by pressing 'ok'
primaryStage focused : true //stage regains focus
</code>```

Or something similar. Does anyone has an idea to achieve this, or is this primaryStage losing focus to a WINDOW_MODAL Alert an issue that I should report ?

答:
So finally I could find a workaround. It is possible for each buttonType used in an alert to determine whether it is focused or not. This property changes also when alt+tabbing, thus we can monitor every buttonType used and see if only one is focused or not.

Here my solution, a little bit hacky but achieving what I wanted :

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));

        primaryStage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("PrimaryStage focused : "+newValue);
        });
        primaryStage.show();

        //create a basic alert
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"This is a test");
        alert.initModality(Modality.WINDOW_MODAL); //will block input to its owner window
        alert.initOwner(primaryStage);

        alert.getButtonTypes().forEach(buttonType -> {
            //add a focus listnener for each buttonType of this alert
            alert.getDialogPane().lookupButton(buttonType).focusedProperty().addListener((observable, oldValue, newValue) -> {
                System.out.println(buttonType.getText()+" focused : "+newValue);
                System.out.println("Alert focused : "+isAlertFocused(alert));

            });
        });
        alert.showAndWait();
    }

    /** Looks all {@link ButtonType} used in the given {@link Alert} and checks if any of them is
     * focused, hence if the {@link Alert} is being focused
     *
     * @param alert the {@link Alert} we want to check the focused status from
     * @return true if the alert is focused, false otherwise
     */
    private boolean isAlertFocused(Alert alert){
        if(alert == null){
            return false;
        }

        final boolean[] focused = {false};
        alert.getButtonTypes().forEach(buttonType -> {
            focused[0] = focused[0] || alert.getDialogPane().lookupButton(buttonType).isFocused();
        });
        return focused[0];
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

I think I can also extend this method to dialog by adding a check of alert.getDialogPane().isFocused() inside the isAlertFocused(Alert alert) method, but this is out of the scope of my question.

ContentLicense: CC BY-SA 3.0

Title: javafx - Alert and stage focus

Body:
For my application I need to know whenever the app's window is being focused or not. For this, I can use primaryStage.focusedProperty().addListener(..), which will warn me of changes in focus of the stage.

But I have realized that opening an Alert with this primaryStage as owner and with modality set to WINDOW_MODAL makes the primaryStage loose focus (even though the window is in reality focused, or at least in Windows).

Now the problem that I have is that I want to know when the Window is focused and not just the primaryStage; or at least know if the Alert is being focused, but I could not find how.

I have tried to use similare properties on the alert(like onShowing and onHiding) without success.

Here is a piece of code to illustrate my problem :

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));

        primaryStage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("primaryStage focused : "+newValue);
        });
        primaryStage.show();

        //create a basic alert
        Alert alert = new Alert(Alert.AlertType.INFORMATION,"This is a test");
        alert.initModality(Modality.WINDOW_MODAL); //will block input to its owner window
        alert.initOwner(primaryStage);
        alert.onShowingProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onShowing : "+newValue);
        });
        alert.onShownProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onShown : "+newValue);
        });
        alert.onHidingProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onHiding : "+newValue);
        });
        alert.onHiddenProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("alert onHidden : "+newValue);
        });
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Basically it will print this :

primaryStage focused : true //stage is created and displayed
primaryStage focused : false //alert is displayed, stage loses focus. alt+tab changes nothing
primaryStage focused : true //alert closed by pressing 'ok'

Which is strange because of all other prints that it should produce.
Also ideally I would need a :

primaryStage focused : true //stage is created and displayed
primaryStage focused : false //alert is displayed, stage loses focus
alert focused : true //alert gains focus
alert focused : false //alt+tab to an other window
alert focused : true //alt+tab back to this window
alert focused : false //alert closed by pressing 'ok'
primaryStage focused : true //stage regains focus

Or something similar. Does anyone has an idea to achieve this, or is this primaryStage losing focus to a WINDOW_MODAL Alert an issue that I should report ?

Body:
So finally I could find a workaround. It is possible for each buttonType used in an alert to determine whether it is focused or not. This property changes also when alt+tabbing, thus we can monitor every buttonType used and see if only one is focused or not.

Here my solution, a little bit hacky but achieving what I wanted :

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));

        primaryStage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("PrimaryStage focused : "+newValue);
        });
        primaryStage.show();

        //create a basic alert
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"This is a test");
        alert.initModality(Modality.WINDOW_MODAL); //will block input to its owner window
        alert.initOwner(primaryStage);

        alert.getButtonTypes().forEach(buttonType -> {
            //add a focus listnener for each buttonType of this alert
            alert.getDialogPane().lookupButton(buttonType).focusedProperty().addListener((observable, oldValue, newValue) -> {
                System.out.println(buttonType.getText()+" focused : "+newValue);
                System.out.println("Alert focused : "+isAlertFocused(alert));

            });
        });
        alert.showAndWait();
    }

    /** Looks all {@link ButtonType} used in the given {@link Alert} and checks if any of them is
     * focused, hence if the {@link Alert} is being focused
     *
     * @param alert the {@link Alert} we want to check the focused status from
     * @return true if the alert is focused, false otherwise
     */
    private boolean isAlertFocused(Alert alert){
        if(alert == null){
            return false;
        }

        final boolean[] focused = {false};
        alert.getButtonTypes().forEach(buttonType -> {
            focused[0] = focused[0] || alert.getDialogPane().lookupButton(buttonType).isFocused();
        });
        return focused[0];
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I think I can also extend this method to dialog by adding a check of alert.getDialogPane().isFocused() inside the isAlertFocused(Alert alert) method, but this is out of the scope of my question.


问:
PHP can't read my html inside a file
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.</p>

```<code><?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;
</code>```

答:
I dont have enough contributions that is why am posting as answer.
Have you tried

```<code>include('templates/register.php');
</code>```

You want your HTML to be inserted in every page. I think this might work

Title: PHP can't read my html inside a file

Body:
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.

<?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;

Body:
I dont have enough contributions that is why am posting as answer.
Have you tried

include('templates/register.php');

You want your HTML to be inserted in every page. I think this might work


问:
how can edit content on a div with php
"hi, I am trying to make one user with username and password to edit the text on a page; I have a database with a table "users" with only one user and a table "save_text" where I save the text; now I am trying to save the text in the page with the next php code; please let me know if it is posible in this way and how ? I cannot save the text on the page  untill next modify for example, thanks"</p>

```<code><?php
require_once 'connect.php';
if (isset($_POST['submit'])){

                      $dbhost="localhost";
                      $dbuser="root";
                      $dbpass="";
                      $dbname="edit text";
                      $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' and     password='$password'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if ($count == 1){

$username = $_POST['username'];
$password = $_POST['password'];
$text = $_POST['text'];

$query = "Insert into save_text (username,password,text) VALUES     ('".$username."','".$password."','".$text."')";
$result = mysqli_query($conn, $query);

echo '<div id="section"><section>'.$text.'</section></div>';
}

else {
echo '<div id="section"><section>fail modify text</section></div>';
}

}
?>
</code>```

答:
one month ago I find myself the answer,
using the function : ob_start();
                      content of the php page;
                     ob_get_contents());   this will tranform the php page content into a html page content;
this is not exactly my work, I just find this function and use it, I still need to learn php from stackoverflow; anyway this could help me when I will do the same for a photo to start a local social network;</p>

Title: how can edit content on a div with php

Body:
"hi, I am trying to make one user with username and password to edit the text on a page; I have a database with a table "users" with only one user and a table "save_text" where I save the text; now I am trying to save the text in the page with the next php code; please let me know if it is posible in this way and how ? I cannot save the text on the page  untill next modify for example, thanks"

<?php
require_once 'connect.php';
if (isset($_POST['submit'])){

                      $dbhost="localhost";
                      $dbuser="root";
                      $dbpass="";
                      $dbname="edit text";
                      $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' and     password='$password'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if ($count == 1){

$username = $_POST['username'];
$password = $_POST['password'];
$text = $_POST['text'];

$query = "Insert into save_text (username,password,text) VALUES     ('".$username."','".$password."','".$text."')";
$result = mysqli_query($conn, $query);

echo '

'.$text.'

';
}

else {
echo '

fail modify text

';
}

}
?>


问:
setColorFilter is not working sometimes on android drawable
I am trying to apply color filter on drawable depending on selected primary color in preferences by user. This is the piece of code I am using.

```<code>getResources().getDrawable(R.drawable.ic_batman_1)
            .setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode.OVERLAY);
</code>```

Problem is that, sometimes, this piece of code does not change the color filter of drawable. I have placed this code in my activity (main activity) onCreate and onResume method.

So as soon as app launches, I want this color filter to be applied on that drawable but sometimes it is not happening. I also noticed that this problem is not happening on high end mobiles (high speed processor, more RAM) but only on low end mobiles.

But if I browse any other activity and come back to main activity, color filter gets applied. Debugged the code and setColorFilter is being called while launching with proper color parameter but for some reason it is not getting applied. Any kind of help is appreciated.

Please do not downvote this question, if you think this is stupid question, just comment and I will take the question down. I am on the verge of getting banned on SO for asking question.

答:
You try Drawable.mutate(); property like this,

```<code>Drawable drawable = ContextCompat.getDrawable(context, resource).mutate();

drawable.setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode. OVERLAY);
</code>```

```<code>/**
 * Make this drawable mutable. This operation cannot be reversed. A mutable
 * drawable is guaranteed to not share its state with any other drawable.
 * This is especially useful when you need to modify properties of drawables
 * loaded from resources. By default, all drawables instances loaded from
 * the same resource share a common state; if you modify the state of one
 * instance, all the other instances will receive the same modification.
 *
 * Calling this method on a mutable Drawable will have no effect.
 *
 * @return This drawable.
 * @see ConstantState
 * @see #getConstantState()
 */
public @NonNull Drawable mutate() {
    return this;
}
</code>```

Body:
I am trying to apply color filter on drawable depending on selected primary color in preferences by user. This is the piece of code I am using.

getResources().getDrawable(R.drawable.ic_batman_1)
            .setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode.OVERLAY);

Problem is that, sometimes, this piece of code does not change the color filter of drawable. I have placed this code in my activity (main activity) onCreate and onResume method.

So as soon as app launches, I want this color filter to be applied on that drawable but sometimes it is not happening. I also noticed that this problem is not happening on high end mobiles (high speed processor, more RAM) but only on low end mobiles.

But if I browse any other activity and come back to main activity, color filter gets applied. Debugged the code and setColorFilter is being called while launching with proper color parameter but for some reason it is not getting applied. Any kind of help is appreciated.

Please do not downvote this question, if you think this is stupid question, just comment and I will take the question down. I am on the verge of getting banned on SO for asking question.

Body:
You try Drawable.mutate(); property like this,

Drawable drawable = ContextCompat.getDrawable(context, resource).mutate();

drawable.setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode. OVERLAY);

/**
 * Make this drawable mutable. This operation cannot be reversed. A mutable
 * drawable is guaranteed to not share its state with any other drawable.
 * This is especially useful when you need to modify properties of drawables
 * loaded from resources. By default, all drawables instances loaded from
 * the same resource share a common state; if you modify the state of one
 * instance, all the other instances will receive the same modification.
 *
 * Calling this method on a mutable Drawable will have no effect.
 *
 * @return This drawable.
 * @see ConstantState
 * @see #getConstantState()
 */
public @NonNull Drawable mutate() {
    return this;
}


问:
header elements not aligning on small screens
I was practicing some webdesign skills and there is a problem here which is,the header on the full screen will not let it's elements get out but on mall screens it's the opposite:
here is the picture of it on the big screen:

And here is a picture from a small screen:

Here is the code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Responsive html practice site</title>
    <link href="css/styles.css" rel="stylesheet">
</head>
<body>

    <div class="container">

        <div class="header">
                 <div class="lgcontainer">
                        <h1 class="ib">Sonora</h1><img class="ib" src="img/images/logo.jpg" />
                 </div>
            <div>

            </div>

        </div>

    </div>

</body>
</html>
</code>```

here is the css:

```<code>body
{
    margin:0;
    padding:0;
}

.lgcontainer
{
    margin:0 0 0 3.5%;
    width:20%;
    float:left;
    text-align:center;
    height:inherit;
}

.lgcontainer h1
{
    margin:0 0 10% 0;
}

.lgcontainer img
{
    margin:5% 0 0 5%;
}

.header
{
 width:100%;
 background:linear-gradient(#393a3b, #000000);
 color:white;
 height:65px;

    }

.ib
{
    display:inline-block;
}
</code>```

I need to have it same as it is on full screen

答:
You need to set the .lgcontainer width to 100% and the text-align to left. Here is the css code:

```<code>body
{
    margin:0;
    padding:0;
}

.lgcontainer
{
    margin:0 0 0 3.5%;
    width:100%;
    float:left;
    text-align:left;
    height:inherit;
}

.lgcontainer h1
{
    margin:0 0 10% 0;
}

.lgcontainer img
{
    margin:1% 0 0 5%;
}

.header
{
 width:100%;
 background:linear-gradient(#393a3b, #000000);
 color:white;
 height:65px;

    }

.ib
{
    display:inline-block;
}
</code>```

Codepen example: https://codepen.io/anon/pen/KqGKLx

Body:
I was practicing some webdesign skills and there is a problem here which is,the header on the full screen will not let it's elements get out but on mall screens it's the opposite:
here is the picture of it on the big screen:

And here is a picture from a small screen:

Here is the code:

<!DOCTYPE html>

    <title>Responsive html practice site</title>
    <link href="css/styles.css" rel="stylesheet">

Sonora

here is the css:

body
{
    margin:0;
    padding:0;
}

.lgcontainer
{
    margin:0 0 0 3.5%;
    width:20%;
    float:left;
    text-align:center;
    height:inherit;
}

.lgcontainer h1
{
    margin:0 0 10% 0;
}

.lgcontainer img
{
    margin:5% 0 0 5%;
}

.header
{
 width:100%;
 background:linear-gradient(#393a3b, #000000);
 color:white;
 height:65px;

    }

.ib
{
    display:inline-block;
}

I need to have it same as it is on full screen

Body:
You need to set the .lgcontainer width to 100% and the text-align to left. Here is the css code:

body
{
    margin:0;
    padding:0;
}

.lgcontainer
{
    margin:0 0 0 3.5%;
    width:100%;
    float:left;
    text-align:left;
    height:inherit;
}

.lgcontainer h1
{
    margin:0 0 10% 0;
}

.lgcontainer img
{
    margin:1% 0 0 5%;
}

.header
{
 width:100%;
 background:linear-gradient(#393a3b, #000000);
 color:white;
 height:65px;

    }

.ib
{
    display:inline-block;
}

Codepen example: https://codepen.io/anon/pen/KqGKLx


问:
Azure function (VS2017) SQL table binding
I'm trying to bind data from AF to Azure SQL. It's easy to do in Azure Portal adding the binding params in function.json file

```<code> {
  "type": "apiHubTable",
  "name": "outputTable",
  "dataSetName": "default",
  "tableName": "SpeechToText",
  "connection": "sql_SQL",
  "direction": "out"
}
</code>```

But I cant do this in VS2017 preview(
Binding to Azure SQL is unavailable)

答:
You need to reference Microsoft.Azure.WebJobs.Extensions.ApiHub NuGet package

```<code>Install-Package Microsoft.Azure.WebJobs.Extensions.ApiHub -Version 1.0.0-beta3 -Pre
</code>```

and then use ApiHubTable attribute for your binding

```<code>[ApiHubTable("sql_SQL", DataSetName = "default", TableName = "SpeechToText")]
</code>```

Body:
I'm trying to bind data from AF to Azure SQL. It's easy to do in Azure Portal adding the binding params in function.json file

 {
  "type": "apiHubTable",
  "name": "outputTable",
  "dataSetName": "default",
  "tableName": "SpeechToText",
  "connection": "sql_SQL",
  "direction": "out"
}

But I cant do this in VS2017 preview(
Binding to Azure SQL is unavailable)

Body:
You need to reference Microsoft.Azure.WebJobs.Extensions.ApiHub NuGet package

Install-Package Microsoft.Azure.WebJobs.Extensions.ApiHub -Version 1.0.0-beta3 -Pre

and then use ApiHubTable attribute for your binding

[ApiHubTable("sql_SQL", DataSetName = "default", TableName = "SpeechToText")]


问:
TypeScript - Array sort extension method
I'm looking to create an array extension "sort" method in TypeScript where the array could be made of various object types. I could call this extension method from any component.

This sort needs to take in an object property to sort by (the property could be number or string of course) and the direction that's an enumerated type (ascending 1 or descending -1).  I have the arrays, I have the enum for sortDirection.  But where/how do I build the sort method to call it like this?

```<code>myArrayOfObjects.sort('name', sortDirection.Descending);
</code>```

Here's my existing component-level sort that I'm trying to turn into an extension method that I could call from anywhere.  It's easy enough to turn the direction into an enum and pass that it, but I'm really trying to make this an extension method:

```<code> sort(property: string): void {
    this.isDescending = !this.isDescending;
    this.column = property;
    const direction = this.isDescending ? 1 : -1;

    this.searchResults.sort(function (a, b) {
        if (a[property] < b[property]) {
            return -1 * direction;
        } else if (a[property] > b[property]) {
            return 1 * direction;
        } else {
            return 0;
        }
    });
    this.currentPage = 0;
}
</code>```

this.searchResults is below, but it could be any array or any object with properties. Again, this is currently a component-level function that I want to turn into an extension method for arrays:

```<code>@Input() searchResults: IPersonSummary[];
</code>```

答:
Because TypeScript have loaded base typings where method with name sort is defined you can't redefine it with the same name. If you consider to use some little different name (in example I choose mySort) you can do that. You need to define it in Array interface and assign your function to Array prototype.
Define extend with new name is best practise because you cant call base method anytimesince you override some base method. If you consider to call base method sometime in the future you will get into big trouble.

Recommended way to do it:

```<code>interface Array<T> {
    mySort(property: string): void;
}

Array.prototype.mySort = function (property: string): void {
    this.isDescending = !this.isDescending;
    this.column = property;
    const direction = this.isDescending ? 1 : -1;

    this.searchResults.sort(function (a, b) {
        if (a[property] < b[property]) {
            return -1 * direction;
        } else if (a[property] > b[property]) {
            return 1 * direction;
        } else {
            return 0;
        }
    });
    this.currentPage = 0;
}
</code>```

Body:
I'm looking to create an array extension "sort" method in TypeScript where the array could be made of various object types. I could call this extension method from any component.

This sort needs to take in an object property to sort by (the property could be number or string of course) and the direction that's an enumerated type (ascending 1 or descending -1).  I have the arrays, I have the enum for sortDirection.  But where/how do I build the sort method to call it like this?

myArrayOfObjects.sort('name', sortDirection.Descending);

Here's my existing component-level sort that I'm trying to turn into an extension method that I could call from anywhere.  It's easy enough to turn the direction into an enum and pass that it, but I'm really trying to make this an extension method:

 sort(property: string): void {
    this.isDescending = !this.isDescending;
    this.column = property;
    const direction = this.isDescending ? 1 : -1;

    this.searchResults.sort(function (a, b) {
        if (a[property]  b[property]) {
            return 1 * direction;
        } else {
            return 0;
        }
    });
    this.currentPage = 0;
}

this.searchResults is below, but it could be any array or any object with properties. Again, this is currently a component-level function that I want to turn into an extension method for arrays:

@Input() searchResults: IPersonSummary[];

Body:
Because TypeScript have loaded base typings where method with name sort is defined you can't redefine it with the same name. If you consider to use some little different name (in example I choose mySort) you can do that. You need to define it in Array interface and assign your function to Array prototype.
Define extend with new name is best practise because you cant call base method anytimesince you override some base method. If you consider to call base method sometime in the future you will get into big trouble.

Recommended way to do it:

interface Array<T> {
    mySort(property: string): void;
}

Array.prototype.mySort = function (property: string): void {
    this.isDescending = !this.isDescending;
    this.column = property;
    const direction = this.isDescending ? 1 : -1;

    this.searchResults.sort(function (a, b) {
        if (a[property] < b[property]) {
            return -1 * direction;
        } else if (a[property] > b[property]) {
            return 1 * direction;
        } else {
            return 0;
        }
    });
    this.currentPage = 0;
}


问:
Rspec tests fail in Namespace
I've just converted some existing rails tests to rspec, and now the tests that are in a namespace fail.

I.e. in the example below, AccountController spec passes, while the ChildrenController fails with the following error:

```<code>in `load_missing_constant': Expected /.../app/controllers/admin/children_controller.rb to define Admin::ChildrenController (LoadError)
</code>```

app/controllers/account_controller.rb

```<code>class AccountController < ApplicationController
</code>```

spec/controllers/account_controller_spec.rb

```<code>require 'spec_helper'

describe AccountController do
  #...
end
</code>```

app/controllers/admin/children_controller.rb

```<code>class Admin::ChildrenController < ApplicationController
</code>```

spec/controllers/admin/children_controller_spec.rb

```<code>require 'spec_helper'

describe Admin::ChildrenController do
   include ::ControllerHelper
   #...
end
</code>```

I'm using

ruby-1.9.2-p0

Rails 3.0.3

rspec 2.3.0

I've tried playing with the namespace definitions, but no luck so far - any ideas???

答:
Posting answer in case anyone stumbles over this another time!

In the end I fixed it by flattening the specs like following:

```<code>app>controllers>admin>children_controller.rb
class Admin::ChildrenController < ApplicationController

spec>controllers>children_controller_spec.rb
require 'spec_helper'
describe Admin::ChildrenController do
</code>```

Title: Rspec tests fail in Namespace

Body:
I've just converted some existing rails tests to rspec, and now the tests that are in a namespace fail.

I.e. in the example below, AccountController spec passes, while the ChildrenController fails with the following error:

in `load_missing_constant': Expected /.../app/controllers/admin/children_controller.rb to define Admin::ChildrenController (LoadError)

app/controllers/account_controller.rb

class AccountController < ApplicationController

spec/controllers/account_controller_spec.rb

require 'spec_helper'

describe AccountController do
  #...
end

app/controllers/admin/children_controller.rb

class Admin::ChildrenController < ApplicationController

spec/controllers/admin/children_controller_spec.rb

require 'spec_helper'

describe Admin::ChildrenController do
   include ::ControllerHelper
   #...
end

I'm using

ruby-1.9.2-p0

Rails 3.0.3

rspec 2.3.0

I've tried playing with the namespace definitions, but no luck so far - any ideas???

Body:
Posting answer in case anyone stumbles over this another time!

In the end I fixed it by flattening the specs like following:

app>controllers>admin>children_controller.rb
class Admin::ChildrenController < ApplicationController

spec>controllers>children_controller_spec.rb
require 'spec_helper'
describe Admin::ChildrenController do

ContentLicense: CC BY-SA 2.5


问:
why the php Session wont work for me
Page1.php

```<code><?php
  session_start();
  $_SESSION['test'] = 'abc';
  echo "the Session are set = ".$_SESSION['test'];
?>
</code>```

Result: the Session are set = abc

page2.php

```<code><?php
  session_start();

  if(isset($_SESSION['test'])){
    echo "Session = ";
    echo $_SESSION['test'];
  }else{
    echo "Session are not set";
  }
?>
</code>```

Result: Session are not set

答:
On page1.php

```<code><?php
  session_start();
  $_SESSION['test'] = 'abc';
  header("Location: page2.php");//Well we know that this session here works so lets try redirecting...
?>
</code>```

On page2.php Please try

```<code><?php
  if( !session_id() )
  {
    session_start();
    session_regenerate_id(true);
  }
  if(isset($_SESSION['test'])){
    echo "Session = ";
    echo $_SESSION['test'];
  }else{
    echo "Session are not set";
  }
?>
</code>```

Title: why the php Session wont work for me

Body:
Page1.php

<?php
  session_start();
  $_SESSION['test'] = 'abc';
  echo "the Session are set = ".$_SESSION['test'];
?>

Result: the Session are set = abc

page2.php

<?php
  session_start();

  if(isset($_SESSION['test'])){
    echo "Session = ";
    echo $_SESSION['test'];
  }else{
    echo "Session are not set";
  }
?>

Result: Session are not set

Body:
On page1.php

<?php
  session_start();
  $_SESSION['test'] = 'abc';
  header("Location: page2.php");//Well we know that this session here works so lets try redirecting...
?>

On page2.php Please try

<?php
  if( !session_id() )
  {
    session_start();
    session_regenerate_id(true);
  }
  if(isset($_SESSION['test'])){
    echo "Session = ";
    echo $_SESSION['test'];
  }else{
    echo "Session are not set";
  }
?>


问:
Is it possible to prioritise a lock?
I have a multiprocessing program where

one process adds elements to a shared list (multiprocessing.Manager().list())

several other processes consume these elements from that list (and remove them); they run until there is something to process in the list and the process above is still adding to the list.

I implemented locking (via multiprocessing.Lock()) when adding to the list, or removing from it. Since there is one "feeder" process and several (10-40) "consumer" ones all competing for the lock, and that the consumer processes are fast, I end up with the "feeder" process having a hard time acquiring the lock.

Is there a concept of "priority" when acquiring a lock? I would like the "feeder" process to acquire it with more priority than the others.

Right now I mitigated the issue by having the "consumer" processes wait a random time before trying to acquire the lock while the "feeder" process is there (when it ends it sets a flag). This is a workaround which works but it is ugly and  hardly effective (I have the processes wait random.random()*n seconds, where n is the number of processes. This is a completely made up number, probably wrong).

答:
Instead of trying to change the locking priority, try changing the process priority itself such that feeder has a higher priority than the consumer. The workaround you used basically simulates this but with less efficiency.

To change process priority,

On Unix: use os.setpriority()

Refer the docs

On windows, use a third party module psutil.

Refer to this thread and Psutil Docs.

Title: Is it possible to prioritise a lock?


问:
incorrect syntax near where but all the brackets are in the right places
```<code>SELECT
    [GMI Division#], [GMI Division],
    [Type_Mapping],
    SUM(Delv_EQC_Fctr) AS Delv_EQC_Fctr,
    SUM(Cuts_EQC_Fctr) AS Cuts_EQC_Fctr
FROM
    (SELECT
         [GMI Division#], [GMI Division],
         [Type_Mapping], [Base Product#],
         SUM([BUoM_Delivery Quantity]) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Delv_EQC_Fctr,
         (SUM([BUoM_GMI Order Cut Total]) + SUM([BUoM_GMI Delivery Cut Total])) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Cuts_EQC_Fctr
     FROM
         [dbo].[CF_Weekly_Casefill_Final_TY]
     LEFT JOIN
         [dbo].[CF_VEDW_PRD_MATL_DIM_N] ON [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#] = CAST([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] AS BIGINT)
     GROUP BY
         [GMI Division#], [GMI Division], [Type_Mapping], [Base Product#],
         [EQC_FCTR], [BUoM_Delivery Quantity], [BUoM_GMI Order Cut Total], [BUoM_GMI Delivery Cut Total])
WHERE
    (([GMI Division#] IN (01, 03, 12, 16, 50)
      AND [Distribution channel] IN ('RT', 'ML')) OR
     ([GMI Division#] IN (08) AND [Distribution channel] IN ('FS')))
    AND RIGHT([Fiscal Year/Period], 4) IN (2018)
GROUP BY
    [GMI Division#], [GMI Division], [Type_Mapping], [EQC_FCTR]
</code>```

This throws an error "incorrect syntax near where"

答:
dose this work?</p>

```<code>Select
[GMI Division#]
,[GMI Division]
,[Type_Mapping]
,Sum(Delv_EQC_Fctr) as Delv_EQC_Fctr
,Sum(Cuts_EQC_Fctr) as Cuts_EQC_Fctr
from (
    select
    [GMI Division#]
    ,[GMI Division]
    ,[Type_Mapping]
    ,[Base Product#]
    ,Sum([BUoM_Delivery Quantity])
        ,([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Delv_EQC_Fctr
    ,(Sum([BUoM_GMI Order Cut Total])+Sum([BUoM_GMI Delivery Cut Total]))
        ,([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Cuts_EQC_Fctr
    from[dbo].[CF_Weekly_Casefill_Final_TY]
    left join [dbo].[CF_VEDW_PRD_MATL_DIM_N]
        on [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#]=cast([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] as bigint)
    group by[GMI Division#]
    ,[GMI Division]
    ,[Type_Mapping]
    ,[Base Product#]
    ,[EQC_FCTR]
    ,[BUoM_Delivery Quantity]
    ,[BUoM_GMI Order Cut Total]
    ,[BUoM_GMI Delivery Cut Total]
    ) as tbl
    where (([GMI Division#] in (01,03,12,16,50)
    and [Distribution channel]in ('RT','ML'))
    or([GMI Division#] in (08)and [Distribution channel]in ('FS')))
    and right([Fiscal Year/Period],4) in (2018)
    group by [GMI Division#],[GMI Division],[Type_Mapping],[EQC_FCTR]
</code>```

Body:
SELECT
    [GMI Division#], [GMI Division],
    [Type_Mapping],
    SUM(Delv_EQC_Fctr) AS Delv_EQC_Fctr,
    SUM(Cuts_EQC_Fctr) AS Cuts_EQC_Fctr
FROM
    (SELECT
         [GMI Division#], [GMI Division],
         [Type_Mapping], [Base Product#],
         SUM([BUoM_Delivery Quantity]) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Delv_EQC_Fctr,
         (SUM([BUoM_GMI Order Cut Total]) + SUM([BUoM_GMI Delivery Cut Total])) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Cuts_EQC_Fctr
     FROM
         [dbo].[CF_Weekly_Casefill_Final_TY]
     LEFT JOIN
         [dbo].[CF_VEDW_PRD_MATL_DIM_N] ON [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#] = CAST([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] AS BIGINT)
     GROUP BY
         [GMI Division#], [GMI Division], [Type_Mapping], [Base Product#],
         [EQC_FCTR], [BUoM_Delivery Quantity], [BUoM_GMI Order Cut Total], [BUoM_GMI Delivery Cut Total])
WHERE
    (([GMI Division#] IN (01, 03, 12, 16, 50)
      AND [Distribution channel] IN ('RT', 'ML')) OR
     ([GMI Division#] IN (08) AND [Distribution channel] IN ('FS')))
    AND RIGHT([Fiscal Year/Period], 4) IN (2018)
GROUP BY
    [GMI Division#], [GMI Division], [Type_Mapping], [EQC_FCTR]

This throws an error "incorrect syntax near where"

Body:
dose this work?

Select
[GMI Division#]
,[GMI Division]
,[Type_Mapping]
,Sum(Delv_EQC_Fctr) as Delv_EQC_Fctr
,Sum(Cuts_EQC_Fctr) as Cuts_EQC_Fctr
from (
    select
    [GMI Division#]
    ,[GMI Division]
    ,[Type_Mapping]
    ,[Base Product#]
    ,Sum([BUoM_Delivery Quantity])
        ,([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Delv_EQC_Fctr
    ,(Sum([BUoM_GMI Order Cut Total])+Sum([BUoM_GMI Delivery Cut Total]))
        ,([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Cuts_EQC_Fctr
    from[dbo].[CF_Weekly_Casefill_Final_TY]
    left join [dbo].[CF_VEDW_PRD_MATL_DIM_N]
        on [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#]=cast([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] as bigint)
    group by[GMI Division#]
    ,[GMI Division]
    ,[Type_Mapping]
    ,[Base Product#]
    ,[EQC_FCTR]
    ,[BUoM_Delivery Quantity]
    ,[BUoM_GMI Order Cut Total]
    ,[BUoM_GMI Delivery Cut Total]
    ) as tbl
    where (([GMI Division#] in (01,03,12,16,50)
    and [Distribution channel]in ('RT','ML'))
    or([GMI Division#] in (08)and [Distribution channel]in ('FS')))
    and right([Fiscal Year/Period],4) in (2018)
    group by [GMI Division#],[GMI Division],[Type_Mapping],[EQC_FCTR]


问:
Save stdout, stderr and stdout+stderr synchronously
For testing purposes, I would like to save stdout and stderr separately for inspection by subsequent code. For example, a test run with erroneous input should result in output to stderr, but nothing on stdout, while a test run with correct input should result in output to stdout, but nothing to stderr. The saving has to be synchronous, to avoid race conditions with the tests (so I can't use process substitution).

To be able to debug the test after the fact, I also need to see stdout and stderr in the sequence they were output. So I have to either save them both to the same file/variable/whatever or send them to the terminal at the same time as saving them separately.

To test which error happened, I also need the exit code of the command.

For reasons of efficiency and accuracy, I of course cannot run each test twice.

Is it for example possible to redirect stdout to stdout.log, stderr to stderr.log, and both of them to output.log in the same command? Or to use a synchronous tee command separately for stdout and stderr? Or to save a copy of stdout and stderr to separate variables?

Update: It looks like tim's solution almost works (modified to output on terminal instead of logging to all.log):

```<code>$ set -o pipefail
$ {
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
foo
$ cat stderr.log
$ {
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
$ cat stderr.log
foo
$ bar=$({
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ echo "$bar"
foo
$ cat stdout.log
foo
$ cat stderr.log
$ bar=$({
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ cat stdout.log
$ cat stderr.log
foo
$ echo "$bar"
foo
</code>```

This seems to work except for the last iteration, where the value of bar is set to the contents of stderr. Any suggestions for all of these to work?

答:
Please see BashFAQ/106. It's not easy to have your cake and eat it, too.

From that page:

But some people won't accept either the loss of separation between stdout and stderr, or the desynchronization of lines. They are purists, and so they ask for the most difficult form of all -- I want to log stdout and stderr together into a single file, BUT I also want them to maintain their original, separate destinations.

In order to do this, we first have to make a few notes:

If there are going to be two separate stdout and stderr streams, then some process has to write each of them.

There is no way to write a process in shell script that reads from two separate FDs whenever one of them has input available, because the shell has no poll(2) or select(2) interface.

Therefore, we'll need two separate writer processes.

The only way to keep output from two separate writers from destroying each other is to make sure they both open their output in append mode. A FD that is opened in append mode has the guaranteed property that every time data is written to it, it will jump to the end first.

So:

```<code># Bash
> mylog
exec > >(tee -a mylog) 2> >(tee -a mylog >&2)

echo A >&2
cat file
echo B >&2
</code>```

This ensures that the log file is correct. It does not guarantee that the writers finish before the next shell prompt:

```<code>~$ ./foo
A
hi mom
B
~$ cat mylog
A
hi mom
B
~$ ./foo
A
hi mom
~$ B
</code>```

Also, see BashFAQ/002 and BashFAQ/047.

Body:
For testing purposes, I would like to save stdout and stderr separately for inspection by subsequent code. For example, a test run with erroneous input should result in output to stderr, but nothing on stdout, while a test run with correct input should result in output to stdout, but nothing to stderr. The saving has to be synchronous, to avoid race conditions with the tests (so I can't use process substitution).

To be able to debug the test after the fact, I also need to see stdout and stderr in the sequence they were output. So I have to either save them both to the same file/variable/whatever or send them to the terminal at the same time as saving them separately.

To test which error happened, I also need the exit code of the command.

For reasons of efficiency and accuracy, I of course cannot run each test twice.

Is it for example possible to redirect stdout to stdout.log, stderr to stderr.log, and both of them to output.log in the same command? Or to use a synchronous tee command separately for stdout and stderr? Or to save a copy of stdout and stderr to separate variables?

Update: It looks like tim's solution almost works (modified to output on terminal instead of logging to all.log):

$ set -o pipefail
$ {
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
foo
$ cat stderr.log
$ {
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
$ cat stderr.log
foo
$ bar=$({
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ echo "$bar"
foo
$ cat stdout.log
foo
$ cat stderr.log
$ bar=$({
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ cat stdout.log
$ cat stderr.log
foo
$ echo "$bar"
foo

This seems to work except for the last iteration, where the value of bar is set to the contents of stderr. Any suggestions for all of these to work?

Body:
Please see BashFAQ/106. It's not easy to have your cake and eat it, too.

From that page:

But some people won't accept either the loss of separation between stdout and stderr, or the desynchronization of lines. They are purists, and so they ask for the most difficult form of all -- I want to log stdout and stderr together into a single file, BUT I also want them to maintain their original, separate destinations.

In order to do this, we first have to make a few notes:

If there are going to be two separate stdout and stderr streams, then some process has to write each of them.

There is no way to write a process in shell script that reads from two separate FDs whenever one of them has input available, because the shell has no poll(2) or select(2) interface.

Therefore, we'll need two separate writer processes.

The only way to keep output from two separate writers from destroying each other is to make sure they both open their output in append mode. A FD that is opened in append mode has the guaranteed property that every time data is written to it, it will jump to the end first.

So:

# Bash
> mylog
exec > >(tee -a mylog) 2> >(tee -a mylog >&2)

echo A >&2
cat file
echo B >&2

This ensures that the log file is correct. It does not guarantee that the writers finish before the next shell prompt:

~$ ./foo
A
hi mom
B
~$ cat mylog
A
hi mom
B
~$ ./foo
A
hi mom
~$ B

Also, see BashFAQ/002 and BashFAQ/047.


问:
Build error trying to get fb sdk working
My goal: create a page that logs in via facebook

What I've done so far: followed the instructions at https://developers.facebook.com/docs/facebook-login/android

The problem that I need help with: when I add

```<code>compile 'com.facebook.android:facebook-android-sdk:[4,5)'
</code>```

to the dependencies in app | Gradle Scripts | build.gradle (Module: app)

it fails to build and presents the error message

Error:Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.1) from [com.android.support:cardview-v7:25.3.1] AndroidManifest.xml:24:9-31
      is also present at [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:22:5-24:34 to override.

The two other compiles in the dependencies by default are:

```<code>compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
</code>```

Hovering over the top statement presents the message:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 26.0.0-alpha1, 25.3.1. Examples include com.android.support:animated-vector-drawable:26.0.0-alpha1 and com.android.support:cardview-v7:25.3.

Android studio version is 2.3.3 and facebook SDK is 4.24.0

Does anyone know why these errors are occurring and/or how to fix them? Thanks

答: add compile 'com.android.support:cardview-v7:26.0.0-alpha1' if you don't use it.

Body:
My goal: create a page that logs in via facebook

What I've done so far: followed the instructions at https://developers.facebook.com/docs/facebook-login/android

The problem that I need help with: when I add

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

to the dependencies in app | Gradle Scripts | build.gradle (Module: app)

it fails to build and presents the error message

Error:Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.1) from [com.android.support:cardview-v7:25.3.1] AndroidManifest.xml:24:9-31
      is also present at [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:22:5-24:34 to override.

The two other compiles in the dependencies by default are:

compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'

Hovering over the top statement presents the message:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 26.0.0-alpha1, 25.3.1. Examples include com.android.support:animated-vector-drawable:26.0.0-alpha1 and com.android.support:cardview-v7:25.3.

Android studio version is 2.3.3 and facebook SDK is 4.24.0

Does anyone know why these errors are occurring and/or how to fix them? Thanks


问:
twitter api issue
I'm integrating "Sign in with twitter account" function at my site.

So, I'm sending request to https ://twitter.com/oauth/request_token, getting token, making redirect to https ://twitter.com/oauth/authenticate?oauth_token=%oauth_token%

Then I recieving call back with oauth_token and oauth_verifier

This goes fine.

But than I need to call https ://api.twitter.com/1/account/verify_credentials.json to get authorizated client details

I'm sending:

```<code>GET https ://api.twitter.com/1/account/verify_credentials.json
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: q=0.8,en-us;q=0.5,en;q=0.3
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
X-Auth-Service-Provider: https ://api.twitter.com/1/account/verify_credentials.json
X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/", oauth_signature="acYFjEgUrTcyb4FMBoJF8MlwZGw%3D", oauth_timestamp="1286899670", oauth_consumer_key="%CONSUMER_KEY%", oauth_nonce="268310006", oauth_token="%oauth_token%", oauth_version="1.0", oauth_signature_method="HMAC-SHA1"

%oauth_token% - token got when twitter redirects me back the cleint
%CONSUMER_KEY% - my twitter account's consumer key
</code>```

And getting back

```<code>HTTP/1.1 401 Unauthorized
Cache-Control: no-cache, max-age=300
Connection: close
Date: Tue, 12 Oct 2010 16:07:45 GMT
Server: hi
Vary: Accept-Encoding
WWW-Authenticate: Basic realm="Twitter API"

{"error":"Could not authenticate you.","request":"/1/account/verify_credentials.json"}
</code>```

Can anyone plz advice me what's wrong here?

Thanks!

答:
You are using header to pass parameters (X-Verify-Credentials-Authorization), instead you should be using GET method. If you are using php Zend framework's OAuth component, then it should look like

```<code>$client->setMethod(Zend_Http_Client::GET);
</code>```

Title: twitter api issue

Body:
I'm integrating "Sign in with twitter account" function at my site.

So, I'm sending request to https ://twitter.com/oauth/request_token, getting token, making redirect to https ://twitter.com/oauth/authenticate?oauth_token=%oauth_token%

Then I recieving call back with oauth_token and oauth_verifier

This goes fine.

But than I need to call https ://api.twitter.com/1/account/verify_credentials.json to get authorizated client details

I'm sending:

GET https ://api.twitter.com/1/account/verify_credentials.json
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: q=0.8,en-us;q=0.5,en;q=0.3
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
X-Auth-Service-Provider: https ://api.twitter.com/1/account/verify_credentials.json
X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/", oauth_signature="acYFjEgUrTcyb4FMBoJF8MlwZGw%3D", oauth_timestamp="1286899670", oauth_consumer_key="%CONSUMER_KEY%", oauth_nonce="268310006", oauth_token="%oauth_token%", oauth_version="1.0", oauth_signature_method="HMAC-SHA1"

%oauth_token% - token got when twitter redirects me back the cleint
%CONSUMER_KEY% - my twitter account's consumer key

And getting back

HTTP/1.1 401 Unauthorized
Cache-Control: no-cache, max-age=300
Connection: close
Date: Tue, 12 Oct 2010 16:07:45 GMT
Server: hi
Vary: Accept-Encoding
WWW-Authenticate: Basic realm="Twitter API"

{"error":"Could not authenticate you.","request":"/1/account/verify_credentials.json"}

Can anyone plz advice me what's wrong here?

Thanks!

Body:
You are using header to pass parameters (X-Verify-Credentials-Authorization), instead you should be using GET method. If you are using php Zend framework's OAuth component, then it should look like

$client->setMethod(Zend_Http_Client::GET);


问:
Why groovy closure refers to for loop iteration counter with reference
I am wondering why the following two snippets output different results. It looks like the iteration counter is a special case handled by closure. </p>

```<code>int i = 1
def closures = (1..3).collect {
    return { println i; ++i }
}

for (int j = 0; j < 3; ++j) {
    closures += { println j }
}

closures*.call()

1
2
3
3
3
3
</code>```

答:
It's a question of when the variable is updated

In the first example, i is only incremented when the closure is executed, so even though each closure is bound to the same instance of i, each output is different

In the second example, j is incremented outside the closures, so by the time you run them, the for loop has finished, and the value of j is 3

Body:
I am wondering why the following two snippets output different results. It looks like the iteration counter is a special case handled by closure.

int i = 1
def closures = (1..3).collect {
    return { println i; ++i }
}

for (int j = 0; j < 3; ++j) {
    closures += { println j }
}

closures*.call()

1
2
3
3
3
3


问:
Arduino to C++ Serial Reads Gibberish
I'm working on a C++ program to communicate with an Arduino that's running an automated system.  I'm using the serial library from this:

https://playground.arduino.cc/Interfacing/CPPWindows

I'm trying to send the Arduino a string which it will then parse into a command that will tell it how the system should move.  The code for reading the command from the serial is this:

`void serialEvent() {

```<code>  while (Serial.available()) {
    char in = (char)Serial.read();
    input.concat(in);
  }
  int endChar = input.indexOf('\r');
  if (endChar != -1) {
    //inputLog.concat(input);
    //inputLog.concat('\n');
    String command = input.substring(0,endChar);
    command.toLowerCase();
    input.remove(0, endChar+1);
    String keyword = command.substring(0,4);
    if(keyword == "move"){
          int i = command.indexOf('x');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            xMove = command.substring(i + 1, endChar).toFloat();
          }
          i = command.indexOf('y');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            yMove = command.substring(i + 1, endChar).toFloat();
          }
    } else if (keyword == "stop") {
      xMove = 0;
      yMove = 0;
    } else if (keyword == "xpos") {
      Serial.print("X: ");
      Serial.println(xPos);
    } else if (keyword == "ypos") {
      Serial.print("Y: ");
      Serial.println(yPos);
    } else if (keyword == "getp") {
      Serial.print("X: ");
      Serial.print(xPos);
      Serial.print(", Y: ");
      Serial.println(yPos);
    } else if (keyword == "setx") {
      xPos = command.substring(4).toFloat();
    } else if (keyword == "sety") {
      yPos = command.substring(4).toFloat();
    } else if (keyword == "setp") {
      int i = command.indexOf('x');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            xPos = command.substring(i + 1, endChar).toFloat();
          }
          i = command.indexOf('y');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            yPos = command.substring(i + 1, endChar).toFloat();
          }
    } else if (keyword == "getl") {
      Serial.println(inputLog);
      inputLog = "";
    } else {
      Serial.println("error: 1");
      return;
    }
    Serial.println("ok\r");
    //Serial.print(nc);
  }
</code>```

}`

This part seems to be running correctly, because I can run it with the Arduino Serial Monitor and it works.  Here is a short test of the code I wrote in C++:

```<code>while (SP->IsConnected())
{
    string outputData = "";
    cin >> outputData;
    outputData.append(pcr);
    //outputData.append(pnc);
    writeResult = SP->WriteData((char*)outputData.c_str(), outputData.length());
    //writeResult = writeResult && SP->WriteData(pnc, 1);
    //writeResult = writeResult & SP->WriteData(pcr, 1);

    while (true) {
        Sleep(500);
        char incomingData[256] = "";
        readResult = SP->ReadData(incomingData, dataLength);
        //printf("Bytes read: (0 means no data available) %i\n", readResult);
        //incomingData[readResult] = 0;
        input.append(incomingData, 0, readResult);

        check_ok = input.find(pcr);
        check_error = input.find(error);

        if (check_ok != string::npos || check_error != string::npos || readResult == 0) {
            cout << "Receiving: " << input << '\n';
            input.clear();
            break;
        }
    }
}
</code>```

The variable, pcr is defined earlier in the code as a pointer to the carriage return character, which the Arduino uses to identify the end of a command.  My results of running this code is that the Arduino seems to read off the first command and execute it; however, it also reads off several gibberish characters, most of which equate to -52 as a numerical value.  Any following commands don't seem to do anything and the arduino continues getting the gibberish characters. Additionally it seems that the ReadData function in C++ works fine.  Does anyone know why this occurs?  Is the Arduino's serial buffer getting corrupted by the WriteData function somehow?

Solved

I appear to have found the issue.  The statement outputData(pcr) needed to be outputData(pcr, 0, 1) because the pointer was not null terminating.  Thus the string was appending extra characters until it reached a null character.

答:
How long your data line is?
Are you using TTL levels to send the data or not?
If your line is longer than several meters and you are using TTL level communication (routing wires directly between devices)  then you definitely will receive garbage from other device. Long line communication lines should use RS232 or RS485 instead,  which are specially designed for it. </p>

ContentLicense: CC BY-SA 4.0

Title: Arduino to C++ Serial Reads Gibberish

Body:
I'm working on a C++ program to communicate with an Arduino that's running an automated system.  I'm using the serial library from this:

https://playground.arduino.cc/Interfacing/CPPWindows

I'm trying to send the Arduino a string which it will then parse into a command that will tell it how the system should move.  The code for reading the command from the serial is this:

`void serialEvent() {

  while (Serial.available()) {
    char in = (char)Serial.read();
    input.concat(in);
  }
  int endChar = input.indexOf('\r');
  if (endChar != -1) {
    //inputLog.concat(input);
    //inputLog.concat('\n');
    String command = input.substring(0,endChar);
    command.toLowerCase();
    input.remove(0, endChar+1);
    String keyword = command.substring(0,4);
    if(keyword == "move"){
          int i = command.indexOf('x');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            xMove = command.substring(i + 1, endChar).toFloat();
          }
          i = command.indexOf('y');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            yMove = command.substring(i + 1, endChar).toFloat();
          }
    } else if (keyword == "stop") {
      xMove = 0;
      yMove = 0;
    } else if (keyword == "xpos") {
      Serial.print("X: ");
      Serial.println(xPos);
    } else if (keyword == "ypos") {
      Serial.print("Y: ");
      Serial.println(yPos);
    } else if (keyword == "getp") {
      Serial.print("X: ");
      Serial.print(xPos);
      Serial.print(", Y: ");
      Serial.println(yPos);
    } else if (keyword == "setx") {
      xPos = command.substring(4).toFloat();
    } else if (keyword == "sety") {
      yPos = command.substring(4).toFloat();
    } else if (keyword == "setp") {
      int i = command.indexOf('x');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            xPos = command.substring(i + 1, endChar).toFloat();
          }
          i = command.indexOf('y');
          if (i != -1) {
            endChar = command.indexOf(i, ',');
            yPos = command.substring(i + 1, endChar).toFloat();
          }
    } else if (keyword == "getl") {
      Serial.println(inputLog);
      inputLog = "";
    } else {
      Serial.println("error: 1");
      return;
    }
    Serial.println("ok\r");
    //Serial.print(nc);
  }

}`

This part seems to be running correctly, because I can run it with the Arduino Serial Monitor and it works.  Here is a short test of the code I wrote in C++:

while (SP->IsConnected())
{
    string outputData = "";
    cin >> outputData;
    outputData.append(pcr);
    //outputData.append(pnc);
    writeResult = SP->WriteData((char*)outputData.c_str(), outputData.length());
    //writeResult = writeResult && SP->WriteData(pnc, 1);
    //writeResult = writeResult & SP->WriteData(pcr, 1);

    while (true) {
        Sleep(500);
        char incomingData[256] = "";
        readResult = SP->ReadData(incomingData, dataLength);
        //printf("Bytes read: (0 means no data available) %i\n", readResult);
        //incomingData[readResult] = 0;
        input.append(incomingData, 0, readResult);

        check_ok = input.find(pcr);
        check_error = input.find(error);

        if (check_ok != string::npos || check_error != string::npos || readResult == 0) {
            cout << "Receiving: " << input << '\n';
            input.clear();
            break;
        }
    }
}

The variable, pcr is defined earlier in the code as a pointer to the carriage return character, which the Arduino uses to identify the end of a command.  My results of running this code is that the Arduino seems to read off the first command and execute it; however, it also reads off several gibberish characters, most of which equate to -52 as a numerical value.  Any following commands don't seem to do anything and the arduino continues getting the gibberish characters. Additionally it seems that the ReadData function in C++ works fine.  Does anyone know why this occurs?  Is the Arduino's serial buffer getting corrupted by the WriteData function somehow?

Solved

I appear to have found the issue.  The statement outputData(pcr) needed to be outputData(pcr, 0, 1) because the pointer was not null terminating.  Thus the string was appending extra characters until it reached a null character.


问:
npm install : specify package.json?
How can I tell npm to use another package.json when running "npm install" ?

All I need is npm install -f packages-win32.json Or is there a trick or another approach to achieve the same?

Because not all npm modules are cross-platform and I'd like to use other packages per platform.

答:
You cannot specify a different package.json file as the specs are literally only for a file called package.json.

If you have some issues with packages that only work on either os try them out with

```<code>try {
  thing = require('thing');
}
catch( error ) {
  thing = require('other');
}
</code>```

You can also sniff out the os via:

```<code>const _isWin = /^win/.test( process.platform );
</code>```

Or use os.platform() if you don't have to support node <= 5...

Maybe that helps?

Title: npm install : specify package.json?

Body:
You cannot specify a different package.json file as the specs are literally only for a file called package.json.

If you have some issues with packages that only work on either os try them out with

try {
  thing = require('thing');
}
catch( error ) {
  thing = require('other');
}

You can also sniff out the os via:

const _isWin = /^win/.test( process.platform );

Or use os.platform() if you don't have to support node <= 5...

Maybe that helps?


问:
How to set a function into a variable and call from it?
I wonder if it is possible to do this in C ++?

e.g:

```<code>varFunction = void TestFunction();
RunCode(varFunction);
</code>```

答:
For the sake of completeness, you can declare a C-style function type as follows:

```<code>typedef int (*inttoint)(int);
</code>```

This creates a type inttoint that can store any function that takes an int as parameter and returns an int. You can use it as follows.

```<code>// Define a function
int square(int x) { return x*x; }

// Save the function in sq variable
inttoint sq { square };

// Execute the function
sq(4);
</code>```

Since C++11, these variables can also store lambda functions, like so

```<code>inttoint half { [](int x) { return x/2; } };
</code>```

And use it same as above.

Body:
I wonder if it is possible to do this in C ++?

e.g:

varFunction = void TestFunction();
RunCode(varFunction);

Body:
For the sake of completeness, you can declare a C-style function type as follows:

typedef int (*inttoint)(int);

This creates a type inttoint that can store any function that takes an int as parameter and returns an int. You can use it as follows.

// Define a function
int square(int x) { return x*x; }

// Save the function in sq variable
inttoint sq { square };

// Execute the function
sq(4);

Since C++11, these variables can also store lambda functions, like so

inttoint half { [](int x) { return x/2; } };

And use it same as above.


问:
Multiple Times load of image from API in ImageView in IOS
I have made a custom Tableview which has an image view and some labels that takes values from API.

It's a custom table in which images and labels recieve data from API related to real estate .

When my custom table loads, values start coming from API.

The actual issue ocurr in image view . I have set a local image in an image view , when the data coming from API has no image than it should show local image otherwise data should show its original image submitted by customer in the forms.

Now when data start coming from API first in image view it shows local image than when images start coming from API it start showing that but when we scroll down in image view it shows same images in image view and repeats many times and we cannot identify that which is original image.

I can provide the code if anyone sent me his email , he can get all the senario of work.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier=@"Cell";
    CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    StringData* cust = [_Title objectAtIndex:indexPath.row];

    cell.Title.text = cust.title1;
    cell.area.text=cust.Area;
    cell.city.text=cust.City;
    cell.phone.text=cust.phoneno;
    cell.price.text=cust.Price;
    cell.location1.text=cust.location;
    cell.name1.text=cust.dealer_name;
    cell.email1.text=cust.dealer_email;
    cell.type1.text=cust.property_type;
    cell.status1.text=cust.status;
    cell.room1.text=cust.rooms;
    cell.washrooms.text=cust.bath;
    cell.floor1.text=cust.floors;
    cell.imagetext.text = cust.images;

    tii=cell.Title.text;
    NSLog(@"Tittttttle is %@",tii);

    NSURL *url = [NSURL URLWithString:cust.images];
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.images1.image = image;
                });
            }
        }
    }];
    [task resume];

    return cell;
}
</code>```

答:
Well, its because your cell is getting re-used and the previous image is being displayed. You can override prepareForReuse() method of your tableviewcell subclass or consider setting placeholder for the url image using SDWebImage

Edit: Explaination

You are downloading your image asyc and setting it to your imageview of your tableviewcell, what is happening here is while your next image is being downloaded, before that your cell is re-used and displays previous image.

Body:
I have made a custom Tableview which has an image view and some labels that takes values from API.

It's a custom table in which images and labels recieve data from API related to real estate .

When my custom table loads, values start coming from API.

The actual issue ocurr in image view . I have set a local image in an image view , when the data coming from API has no image than it should show local image otherwise data should show its original image submitted by customer in the forms.

Now when data start coming from API first in image view it shows local image than when images start coming from API it start showing that but when we scroll down in image view it shows same images in image view and repeats many times and we cannot identify that which is original image.

I can provide the code if anyone sent me his email , he can get all the senario of work.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier=@"Cell";
    CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    StringData* cust = [_Title objectAtIndex:indexPath.row];

    cell.Title.text = cust.title1;
    cell.area.text=cust.Area;
    cell.city.text=cust.City;
    cell.phone.text=cust.phoneno;
    cell.price.text=cust.Price;
    cell.location1.text=cust.location;
    cell.name1.text=cust.dealer_name;
    cell.email1.text=cust.dealer_email;
    cell.type1.text=cust.property_type;
    cell.status1.text=cust.status;
    cell.room1.text=cust.rooms;
    cell.washrooms.text=cust.bath;
    cell.floor1.text=cust.floors;
    cell.imagetext.text = cust.images;

    tii=cell.Title.text;
    NSLog(@"Tittttttle is %@",tii);

    NSURL *url = [NSURL URLWithString:cust.images];
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.images1.image = image;
                });
            }
        }
    }];
    [task resume];

    return cell;
}


问:
How to pass data from Activity to fragment inside fragment
I have an Activity. It adds Fragment A dynamically. Fragment A contains static added (by xml) child Fragment B. How can I pass data from Activity to Fragment B when i add Fragment A to Activity?

I know next approach:

Implement interface getter in Activity and call getter method from Fragment B

I'd like to know, are there another ways to do it?

I tried set arguments from Activity to Fragment A, find Fragment B by child fragment manager and set arguments from Fragment A to Fragment B.
But Fragment B created earlier than Fragment A, so i had exceptions..

答:
Well there are more than one ways to accomplish that. one of the way is
Create a function public void setData(Data data) in your Fragment B

Transfer your data from Activity to Fragment A. Since your Fragment B is added by fragment tag in xml. create ref to your Fragment B object in Fragment A. Now you have the reference to Fragment B in A.

Now Simply call the function (created in Fragment B) in Fragment A and pass the data which you have received by the Activity

Other way..

In Fragment B you can call getActivity() and type cast it in to your Activity class type and call its method which can return the desired data


问:
Why does this code return a list index error?
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

```<code>if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)
</code>```

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

```<code>def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result
</code>```

答:
Use a list comprehension to remove the invalid points. For example:</p>

```<code>result = [coords for coords in result
          if all(0 <= c < board.dimension for c in coords)]
</code>```

Body:
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result

Body:
Use a list comprehension to remove the invalid points. For example:

result = [coords for coords in result
          if all(0 <= c < board.dimension for c in coords)]


答:
This sample by google should resolve all your Issues:

https://developer.android.com/training/basics/fragments/communicating.html

Title: How to pass data from Activity to fragment inside fragment

Body:
I have an Activity. It adds Fragment A dynamically. Fragment A contains static added (by xml) child Fragment B. How can I pass data from Activity to Fragment B when i add Fragment A to Activity?

I know next approach:

Implement interface getter in Activity and call getter method from Fragment B

I'd like to know, are there another ways to do it?

I tried set arguments from Activity to Fragment A, find Fragment B by child fragment manager and set arguments from Fragment A to Fragment B.
But Fragment B created earlier than Fragment A, so i had exceptions..


问:
Extract multiple protein sequences from a Protein Data Bank along with Secondary Structure
I want to extract protein sequences and their corresponding secondary structure from any Protein Data bank, say RCSB. I just need short sequences and their secondary structure. Something like,

```<code>ATRWGUVT     Helix
</code>```

It is fine even if the sequences are long, but I want a tag at the end that denotes its secondary structure. Is there any programming tool or anything available for this.

As I've shown above I want only this much minimal information. How can I achieve this?

答:
```<code>from Bio.PDB import *
from distutils import spawn
</code>```

Extract sequence:

```<code>def get_seq(pdbfile):
 p = PDBParser(PERMISSIVE=0)
 structure = p.get_structure('test', pdbfile)
 ppb = PPBuilder()
 seq = ''
 for pp in ppb.build_peptides(structure):
  seq += pp.get_sequence()

 return seq
</code>```

Extract secondary structure with DSSP as explained earlier:

```<code>def get_secondary_struc(pdbfile):
    # get secondary structure info for whole pdb.
    if not spawn.find_executable("dssp"):
        sys.stderr.write('dssp executable needs to be in folder')
        sys.exit(1)
    p = PDBParser(PERMISSIVE=0)
    ppb = PPBuilder()
    structure = p.get_structure('test', pdbfile)
    model = structure[0]
    dssp = DSSP(model, pdbfile)
    count = 0
    sec = ''
    for residue in model.get_residues():
        count = count + 1
        # print residue,count
        a_key = list(dssp.keys())[count - 1]
        sec += dssp[a_key][2]
    print sec
    return sec
</code>```

This should print both sequence and secondary structure.

Body:
I want to extract protein sequences and their corresponding secondary structure from any Protein Data bank, say RCSB. I just need short sequences and their secondary structure. Something like,

ATRWGUVT     Helix

It is fine even if the sequences are long, but I want a tag at the end that denotes its secondary structure. Is there any programming tool or anything available for this.

As I've shown above I want only this much minimal information. How can I achieve this?

Body:
from Bio.PDB import *
from distutils import spawn

Extract sequence:

def get_seq(pdbfile):
 p = PDBParser(PERMISSIVE=0)
 structure = p.get_structure('test', pdbfile)
 ppb = PPBuilder()
 seq = ''
 for pp in ppb.build_peptides(structure):
  seq += pp.get_sequence()

 return seq

Extract secondary structure with DSSP as explained earlier:

def get_secondary_struc(pdbfile):
    # get secondary structure info for whole pdb.
    if not spawn.find_executable("dssp"):
        sys.stderr.write('dssp executable needs to be in folder')
        sys.exit(1)
    p = PDBParser(PERMISSIVE=0)
    ppb = PPBuilder()
    structure = p.get_structure('test', pdbfile)
    model = structure[0]
    dssp = DSSP(model, pdbfile)
    count = 0
    sec = ''
    for residue in model.get_residues():
        count = count + 1
        # print residue,count
        a_key = list(dssp.keys())[count - 1]
        sec += dssp[a_key][2]
    print sec
    return sec

This should print both sequence and secondary structure.


问:
How to achive true parallelism with thread in Python?
I'm learning about threading library in Python. I don't understand, how to run two threads in parallel?

Here are my python programs:

Program without threading (fibsimple.py)

```<code>def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

fib(35)
fib(35)

print "Done"
</code>```

Running time:

```<code>$ time python fibsimple.py
Done

real    0m7.935s
user    0m7.922s
sys 0m0.008s
</code>```

Same program with threading(fibthread.py)

```<code>from threading import Thread
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

t1 = Thread(target = fib, args = (35, ))
t1.start()

t2 = Thread(target = fib, args = (35, ))
t2.start()

t1.join()
t2.join()

print "Done"
</code>```

Running time:

```<code>$ time python fibthread.py
Done

real    0m12.313s
user    0m10.894s
sys 0m5.043s
</code>```

I don't understand why thread program is taking more time? It should be almost half, if threads are running in parallel.

But If I implement the same program with multiprocessing library, time will become half.

program with multiprocess(fibmultiprocess.py)

```<code>from multiprocessing import Process

def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

p1 = Process(target = fib, args = (35, ))
p1.start()

p2 = Process(target = fib, args = (35, ))
p2.start()

p1.join()
p2.join()

print "Done"
</code>```

Running time

```<code> $ time python fibmultiporcess.py
 Done

 real   0m4.303s
 user   0m8.065s
 sys    0m0.007s
</code>```

Can someone explain, How to run threads in parallel? How multiprocessing and thread-parallelism are different? Any help would be appreciated.

答:
To explain the weird running time of multithread, you have to know GIL.

GIL stands for Global Interpreter Lock which intends to serialize access to interpreter internals from different threads. That is, only ONE thread is running by a interpreter at a time. On multi-core systems, it means that multiple threads can't effectively make use of multiple cores.

But why is the running time longer than the one without multithread?

That's because there're extra time consumed during switching between threads.

And of course, since using multiprocessing creates multiple interpreters, it is not affected by GIL. That's why the speed can double as expected.

Reference

Good comparison between multithread and multiprocess in python link

To know more about GIL and some other experiments, checkout Understanding the Python GIL - David Beazley. This is the best explanation you can have.

Body:
I'm learning about threading library in Python. I don't understand, how to run two threads in parallel?

Here are my python programs:

Program without threading (fibsimple.py)

def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

fib(35)
fib(35)

print "Done"

Running time:

$ time python fibsimple.py
Done

real    0m7.935s
user    0m7.922s
sys 0m0.008s

Same program with threading(fibthread.py)

from threading import Thread
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

t1 = Thread(target = fib, args = (35, ))
t1.start()

t2 = Thread(target = fib, args = (35, ))
t2.start()

t1.join()
t2.join()

print "Done"

Running time:

$ time python fibthread.py
Done

real    0m12.313s
user    0m10.894s
sys 0m5.043s

I don't understand why thread program is taking more time? It should be almost half, if threads are running in parallel.

But If I implement the same program with multiprocessing library, time will become half.

program with multiprocess(fibmultiprocess.py)

from multiprocessing import Process

def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

p1 = Process(target = fib, args = (35, ))
p1.start()

p2 = Process(target = fib, args = (35, ))
p2.start()

p1.join()
p2.join()

print "Done"

Running time

 $ time python fibmultiporcess.py
 Done

 real   0m4.303s
 user   0m8.065s
 sys    0m0.007s

Can someone explain, How to run threads in parallel? How multiprocessing and thread-parallelism are different? Any help would be appreciated.


问:
How can I show a div, then hide the other divs when a link is clicked?
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

```<code><div id="resourceLinks">
  <a href="#" name="resource" id="resource1">General Information</a><br />
  <a href="#" name="resource" id="resource2">Automatic 401(k)</a><br />
  <a href="#" name="resource" id="resource3">Consumer Fraud</a><br />
  <a href="#" name="resource" id="resource4">Direct Deposit</a><br />
  <a href="#" name="resource" id="resource5">Diversity</a><br />
  <a href="#" name="resource" id="resource6">Women</a><br />
  <a href="#" name="resource" id="resource7">Young Adults (20s - 40s)</a>
  </div>

<div id="resource1></div>
<div id="resource2></div>
<div id="resource3></div>
<div id="resource4></div>
<div id="resource5></div>
<div id="resource6></div>
<div id="resource7></div>
</code>```

CSS:

```<code>#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}
</code>```

jQuery:

```<code>$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});
</code>```

答:
Given:

```<code><div id="resourceLinks">
  <a href="#" data-child="resource1">General Information</a><br />
  <a href="#" data-child="resource2">Automatic 401(k)</a><br />
  <a href="#" data-child="resource3">Consumer Fraud</a><br />
  <a href="#" data-child="resource4">Direct Deposit</a><br />
  <a href="#" data-child="resource5">Diversity</a><br />
  <a href="#" data-child="resource6">Women</a><br />
  <a href="#" data-child="resource7">Young Adults (20s - 40s)</a>
  </div>

<div class="resource" id="resource1">1</div>
<div class="resource" id="resource2">2</div>
<div class="resource" id="resource3">3</div>
<div class="resource" id="resource4">4</div>
<div class="resource" id="resource5">5</div>
<div class="resource" id="resource6">6</div>
<div class="resource" id="resource7">7</div>
</code>```

You can:

```<code>$(function() {
    var $resLinks = $('#resourceLinks a'),
        $res = $('.resource');

    // Hide all but first
    $res.not(':first').hide();
    $resLinks.first().addClass('current');

    $resLinks.click(function() {
        var $elm = $(this),
            childId = $elm.data('child');

        // Hide all (only one is visible, though)
        $res.hide();

        // Reset and set .current class on links
        $resLinks.removeClass('current');
        $elm.addClass('current');

        // Show related
        $('#' + childId).show();

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

Update #1: Code is tested.

Update #2: Showing first on init.

Body:
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

  General Information

  Automatic 401(k)

  Consumer Fraud

  Direct Deposit

  Diversity

  Women

  Young Adults (20s - 40s)

CSS:

#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}

jQuery:

$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});

Body:
Given:

<div id="resourceLinks">
  <a href="#" data-child="resource1">General&nbsp;Information</a><br />
  <a href="#" data-child="resource2">Automatic&nbsp;401(k)</a><br />
  <a href="#" data-child="resource3">Consumer&nbsp;Fraud</a><br />
  <a href="#" data-child="resource4">Direct&nbsp;Deposit</a><br />
  <a href="#" data-child="resource5">Diversity</a><br />
  <a href="#" data-child="resource6">Women</a><br />
  <a href="#" data-child="resource7">Young&nbsp;Adults&nbsp;(20s&nbsp;-&nbsp;40s)</a>
  </div>

<div class="resource" id="resource1">1</div>
<div class="resource" id="resource2">2</div>
<div class="resource" id="resource3">3</div>
<div class="resource" id="resource4">4</div>
<div class="resource" id="resource5">5</div>
<div class="resource" id="resource6">6</div>
<div class="resource" id="resource7">7</div>

You can:

$(function() {
    var $resLinks = $('#resourceLinks a'),
        $res = $('.resource');

    // Hide all but first
    $res.not(':first').hide();
    $resLinks.first().addClass('current');

    $resLinks.click(function() {
        var $elm = $(this),
            childId = $elm.data('child');

        // Hide all (only one is visible, though)
        $res.hide();

        // Reset and set .current class on links
        $resLinks.removeClass('current');
        $elm.addClass('current');

        // Show related
        $('#' + childId).show();

        return false;
    });
});

Update #1: Code is tested.

Update #2: Showing first on init.


问:
Aggregating in panda dataframe
I have the below panda dataframe

Now I want to sum the count for [user 1][user 2] and [user 2][user 1]. For example, the count value for [user 1 = 1][user 2 = 92] is count = 1 and [user 1 = 92][user 2 = 1] is count = 2, so I want the final output as user 1 = 1, user 2 = 92 and count = 3. Also, there might not be [user 2][user 1] for every [user 1][user 2]. For example, for [user 1 = 29][user 2 = 56] count value is 3 but there is no [user 1 = 56][user 2 = 29], so the final output would be user 1 = 29, user 2 = 56 and count = 3.

So final output should look like this

Can someone please guide me how to do this?

答:
A solution grouping sorted tuples:</p>

```<code>df['users'] = list(zip(df.user1,df.user2))
df['users'] = df.users.apply(lambda t:tuple(sorted(t)))
counts = df.groupby('users', as_index=False)['count'].sum()
counts[['user1','user2']] = counts.users.apply(pd.Series)
counts = counts[['user1','user2','count']] # Select and reorder columns
</code>```

Title: Aggregating in panda dataframe

Body:
A solution grouping sorted tuples:

df['users'] = list(zip(df.user1,df.user2))
df['users'] = df.users.apply(lambda t:tuple(sorted(t)))
counts = df.groupby('users', as_index=False)['count'].sum()
counts[['user1','user2']] = counts.users.apply(pd.Series)
counts = counts[['user1','user2','count']] # Select and reorder columns