问:
accessing variables from custom ArrayAdapter in yes/no dialog
Hi i want my code to have separated methods to create yes/no dialog and to create its onClickListener separated from ArrayAdapter (I'm not sure if dialogCreator() is done well but that's not the case in that question)

Here is what I'd like to achieve:

```<code>public class FlashCardsAdapter extends ArrayAdapter<FileManager> {
interface Callback {
    void onFileDeleted(String fileName);
}

private final Callback mCallback;

public FlashCardsAdapter(Context context, ArrayList<FileManager> users, final Callback callback) {
    super(context, 0, users);
    mCallback = callback;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final FileManager manager = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item, parent, false);
    }

    TextView mainTextView = convertView.findViewById(R.id.deck_name_id);

    Button addCardButton = convertView.findViewById(R.id.action_add_card);

    Button deleteDeckButton = convertView.findViewById(R.id.action_delete);

    mainTextView.setText(manager.getFileName());

    mainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), FlashCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    addCardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), AddCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    return convertView;
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                manager.deleteFile(); // I want to access manager in here
                mCallback.onFileDeleted(manager.getFileName()); // and here
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
        }
    }
};

private void dialogCreator(){
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();
    builder.create();
}

}
</code>```

manager is the variable I'd like to access in my methods

答:
If you want to access a variable outside a method in the same class, you have to set the focus of the variable to class (at the moment your variable is method-private).

You can achieve it simply moving your manager variable outside the getView method:

```<code>public class FlashCardsAdapter extends ArrayAdapter<FileManager> {
interface Callback {
    void onFileDeleted(String fileName);
}

private final Callback mCallback;
private FileManager manager; //in this way this variable is accessible to all method inside the class

public FlashCardsAdapter(Context context, ArrayList<FileManager> users, final Callback callback) {
    super(context, 0, users);
    mCallback = callback;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    manager = getItem(position); //here you initialize it

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item, parent, false);
    }

    TextView mainTextView = convertView.findViewById(R.id.deck_name_id);

    Button addCardButton = convertView.findViewById(R.id.action_add_card);

    Button deleteDeckButton = convertView.findViewById(R.id.action_delete);

    mainTextView.setText(manager.getFileName());

    mainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), FlashCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    addCardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), AddCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    return convertView;
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                manager.deleteFile(); // and here you can access it
                mCallback.onFileDeleted(manager.getFileName()); // and here too
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
        }
    }
};

private void dialogCreator(){
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();
    builder.create();
}

}
</code>```

Hope this helps, if I miss-understood tell me

Note:

Probably would be a better approach to save a reference of the list in your adapter and retrieve items (FileManager) from the position (overriding getItem(position) methos too) to avoid recycler related problems.

Body:
Hi i want my code to have separated methods to create yes/no dialog and to create its onClickListener separated from ArrayAdapter (I'm not sure if dialogCreator() is done well but that's not the case in that question)

Here is what I'd like to achieve:

public class FlashCardsAdapter extends ArrayAdapter<FileManager> {
interface Callback {
    void onFileDeleted(String fileName);
}

private final Callback mCallback;

public FlashCardsAdapter(Context context, ArrayList<FileManager> users, final Callback callback) {
    super(context, 0, users);
    mCallback = callback;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final FileManager manager = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item, parent, false);
    }

    TextView mainTextView = convertView.findViewById(R.id.deck_name_id);

    Button addCardButton = convertView.findViewById(R.id.action_add_card);

    Button deleteDeckButton = convertView.findViewById(R.id.action_delete);

    mainTextView.setText(manager.getFileName());

    mainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), FlashCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    addCardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), AddCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    return convertView;
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                manager.deleteFile(); // I want to access manager in here
                mCallback.onFileDeleted(manager.getFileName()); // and here
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
        }
    }
};

private void dialogCreator(){
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();
    builder.create();
}

}

manager is the variable I'd like to access in my methods

Body:
If you want to access a variable outside a method in the same class, you have to set the focus of the variable to class (at the moment your variable is method-private).

You can achieve it simply moving your manager variable outside the getView method:

public class FlashCardsAdapter extends ArrayAdapter<FileManager> {
interface Callback {
    void onFileDeleted(String fileName);
}

private final Callback mCallback;
private FileManager manager; //in this way this variable is accessible to all method inside the class

public FlashCardsAdapter(Context context, ArrayList<FileManager> users, final Callback callback) {
    super(context, 0, users);
    mCallback = callback;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    manager = getItem(position); //here you initialize it

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item, parent, false);
    }

    TextView mainTextView = convertView.findViewById(R.id.deck_name_id);

    Button addCardButton = convertView.findViewById(R.id.action_add_card);

    Button deleteDeckButton = convertView.findViewById(R.id.action_delete);

    mainTextView.setText(manager.getFileName());

    mainTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), FlashCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    addCardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), AddCardActivity.class);
            intent.putExtra("fileName", manager.getFileName());
            getContext().startActivity(intent);
        }
    });

    deleteDeckButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    return convertView;
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                manager.deleteFile(); // and here you can access it
                mCallback.onFileDeleted(manager.getFileName()); // and here too
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
        }
    }
};

private void dialogCreator(){
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();
    builder.create();
}

}

Hope this helps, if I miss-understood tell me

Note:

Probably would be a better approach to save a reference of the list in your adapter and retrieve items (FileManager) from the position (overriding getItem(position) methos too) to avoid recycler related problems.


来源: stackexchange

问:
Retrieving Image URL from HTML code
```<code>private String getPersonImageUrl(Document doc){
    String result = "";
    Elements wrapper = doc.getElementsByClass("article name-overview");

    return result;
}
</code>```

Hello, I am kind of new to this information gathering from the website. I've encountered a problem I can't solve.

What I need is to retrieve the "src" image url to string "result". The "src" can be found in the link below. I've selected the class "article name-overview", because "image" can be found multiple times in the website there. What I don't know is how to proceed to retrieve the image link, located in src= value. Any help perhaps? Thank you.

P.S. Document doc = Jsoup.connect(url).get() in other class passed to getPersonImageUrl method. Also getting person's name is working, only struggling with picture url itself.
P.S.S. Information retrieved are for personal, non-commercial use.

src value

答:
Specifically for that image, select it by its id then return its src.

```<code>return doc.select("#name-poster").attr("src");
</code>```

Same approach works for other attributes like alt which appears to store a name.

```<code>String alt = doc.select("#name-poster").attr("alt");
String src = doc.select("#name-poster").attr("src");
</code>```

ContentLicense: CC BY-SA 3.0

Title: Retrieving Image URL from HTML code

Body:
private String getPersonImageUrl(Document doc){
    String result = "";
    Elements wrapper = doc.getElementsByClass("article name-overview");

    return result;
}

Hello, I am kind of new to this information gathering from the website. I've encountered a problem I can't solve.

What I need is to retrieve the "src" image url to string "result". The "src" can be found in the link below. I've selected the class "article name-overview", because "image" can be found multiple times in the website there. What I don't know is how to proceed to retrieve the image link, located in src= value. Any help perhaps? Thank you.

P.S. Document doc = Jsoup.connect(url).get() in other class passed to getPersonImageUrl method. Also getting person's name is working, only struggling with picture url itself.
P.S.S. Information retrieved are for personal, non-commercial use.

src value

Body:
Specifically for that image, select it by its id then return its src.

return doc.select("#name-poster").attr("src");

Same approach works for other attributes like alt which appears to store a name.

String alt = doc.select("#name-poster").attr("alt");
String src = doc.select("#name-poster").attr("src");


问:
Backup a mysql [xampp] database in java
So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.</p>

```<code>...
String path = null;
String filename;

//choose where to backup

 private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt)   {
    JFileChooser fc = new JFileChooser();
    fc.showOpenDialog(this);
    String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());

    try {
        File f = fc.getSelectedFile();
        path = f.getAbsolutePath();
        path = path.replace('\\', '/');
        path = path+"_"+date+".sql";
        jTextField1.setText(path);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
    Process p = null;

    try{
        Runtime runtime = Runtime.getRuntime();

        p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);

        int processComplete = p.waitFor();
        if (processComplete==0) {
            jLabel1.setText("Backup Created Success!");
        } else {
            jLabel1.setText("Can't create backup.");
        }
    } catch (Exception e) {

    }

}
</code>```

答: You use a try-catch block in the jButtonBackUpActionPerformed, but the catch statement is empty. Therefore, if an exception is raised for whatever reason, no file would be written and you would get no output. You can try to use e.printStackTrace() like in the catch statement of the other button for debugging.

Title: Backup a mysql [xampp] database in java

Body:
So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.

...
String path = null;
String filename;

//choose where to backup

 private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt)   {
    JFileChooser fc = new JFileChooser();
    fc.showOpenDialog(this);
    String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());

    try {
        File f = fc.getSelectedFile();
        path = f.getAbsolutePath();
        path = path.replace('\\', '/');
        path = path+"_"+date+".sql";
        jTextField1.setText(path);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
    Process p = null;

    try{
        Runtime runtime = Runtime.getRuntime();

        p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);

        int processComplete = p.waitFor();
        if (processComplete==0) {
            jLabel1.setText("Backup Created Success!");
        } else {
            jLabel1.setText("Can't create backup.");
        }
    } catch (Exception e) {

    }

}


问:
Why doing someVar in someArray in an If always give false value
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  Is Extension Allowed : {{isAllowed}}
</div>
</body>
</html></code>```

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

答:
The in operator i used to check for properties /keys.
 In your case you can use Array.indexOf():

```<code>if(allowedExtensions.indexOf(testExt)) $scope.isAllowed = true;
</code>```

Body:
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}

  Is Extension Allowed : {{isAllowed}}

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

Body:
The in operator i used to check for properties /keys.
 In your case you can use Array.indexOf():

if(allowedExtensions.indexOf(testExt)) $scope.isAllowed = true;


问:
SharedPreferances in Spinners
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.</p>

```<code>public class MyAndroidAppActivity extends AppCompatActivity {

    String india[]={"humains","elfes","hobbits"};
    String m[]={"PUNE","Mumbai","yoo"};
    String b[]={"Arwen","Elrond","Galadriel","Legolas"};
    String u[]={"sup","trankill","Conor","Mcgregor","Nate Diaz"};

    Spinner s,s1,s2;
    private Button btnSubmit;
   SharedPreferences mypref;
    final String KEY_SavedSel = "Saved Selection";
    final String KEY_SavedSe2 = "Saved Selection";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_android_app);
        s=(Spinner)findViewById(R.id.spinner1);
        s1=(Spinner)findViewById(R.id.spinner2);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        final ArrayAdapter<String>ia=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,india);

        final ArrayAdapter<String>ma=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);

        final ArrayAdapter<String>ba=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,b);

        final ArrayAdapter<String>ua=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,u);

        ia.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(ia);
        mypref = getPreferences(MODE_PRIVATE);
        int prefsInt = mypref.getInt(KEY_SavedSel, -1);
        int prefsInt1 = mypref.getInt(KEY_SavedSe2,-1);
        if(prefsInt != -1){
            s.setSelection(prefsInt);

        }

        if(prefsInt1 != -1){
            s1.setSelection(prefsInt1);
        }

        s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (parent.getId()){
                    case R.id.spinner1:{
                        SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
                        editor.putInt(KEY_SavedSel, position);
                        editor.putInt(KEY_SavedSe2, position);
                        editor.commit();
                        if(india[position].equals("humains")){
                            ma.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ma);

                        }
                        if(india[position].equals("elfes")){

                            ba.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ba);

                        }
                        if(india[position].equals("hobbits")){

                            ua.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ua);

                        }

                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(MyAndroidAppActivity.this,

                        "Resultat : " +

                                "\nSpinner 1 : "+ String.valueOf(s.getSelectedItem()) +

                                "\nSpinner 2 : "+ String.valueOf(s1.getSelectedItem()),

                        Toast.LENGTH_SHORT).show();

            }

        });

    }

}
</code>```

答:
You have to take two different keys :

both of followings are same :

```<code>final String KEY_SavedSel = "Saved Selection";
final String KEY_SavedSe2 = "Saved Selection";
</code>```

Change them as follows :

```<code>final String KEY_SavedSel = "Saved Selection1";
final String KEY_SavedSe2 = "Saved Selection2";
</code>```

and while setting adapter you have not considered item selection of spinner2. you need to put value for spinner 2 as well. add following case as well.

```<code>     case R.id.spinner2:{
                    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
                  //  editor.putInt(KEY_SavedSel, position);

                 // your remaining code.

                    editor.putInt(KEY_SavedSe2, position);
                    editor.commit();
                    }
</code>```

Title: SharedPreferances in Spinners

Body:
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.
i have a probleme with sharedpreferances in spinners, i have 2 spinners, i want to save my spinners with shared preferances i can save the first spinner but i can't save the second one, sombody can help me please
thanks to all.

public class MyAndroidAppActivity extends AppCompatActivity {

    String india[]={"humains","elfes","hobbits"};
    String m[]={"PUNE","Mumbai","yoo"};
    String b[]={"Arwen","Elrond","Galadriel","Legolas"};
    String u[]={"sup","trankill","Conor","Mcgregor","Nate Diaz"};

    Spinner s,s1,s2;
    private Button btnSubmit;
   SharedPreferences mypref;
    final String KEY_SavedSel = "Saved Selection";
    final String KEY_SavedSe2 = "Saved Selection";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_android_app);
        s=(Spinner)findViewById(R.id.spinner1);
        s1=(Spinner)findViewById(R.id.spinner2);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        final ArrayAdapter<String>ia=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,india);

        final ArrayAdapter<String>ma=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);

        final ArrayAdapter<String>ba=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,b);

        final ArrayAdapter<String>ua=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,u);

        ia.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(ia);
        mypref = getPreferences(MODE_PRIVATE);
        int prefsInt = mypref.getInt(KEY_SavedSel, -1);
        int prefsInt1 = mypref.getInt(KEY_SavedSe2,-1);
        if(prefsInt != -1){
            s.setSelection(prefsInt);

        }

        if(prefsInt1 != -1){
            s1.setSelection(prefsInt1);
        }

        s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (parent.getId()){
                    case R.id.spinner1:{
                        SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
                        editor.putInt(KEY_SavedSel, position);
                        editor.putInt(KEY_SavedSe2, position);
                        editor.commit();
                        if(india[position].equals("humains")){
                            ma.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ma);

                        }
                        if(india[position].equals("elfes")){

                            ba.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ba);

                        }
                        if(india[position].equals("hobbits")){

                            ua.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            s1.setAdapter(ua);

                        }

                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(MyAndroidAppActivity.this,

                        "Resultat : " +

                                "\nSpinner 1 : "+ String.valueOf(s.getSelectedItem()) +

                                "\nSpinner 2 : "+ String.valueOf(s1.getSelectedItem()),

                        Toast.LENGTH_SHORT).show();

            }

        });

    }

}

Body:
You have to take two different keys :

both of followings are same :

final String KEY_SavedSel = "Saved Selection";
final String KEY_SavedSe2 = "Saved Selection";

Change them as follows :

final String KEY_SavedSel = "Saved Selection1";
final String KEY_SavedSe2 = "Saved Selection2";

and while setting adapter you have not considered item selection of spinner2. you need to put value for spinner 2 as well. add following case as well.

     case R.id.spinner2:{
                    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
                  //  editor.putInt(KEY_SavedSel, position);

                 // your remaining code.

                    editor.putInt(KEY_SavedSe2, position);
                    editor.commit();
                    }


问:
use rollaply without current row
I have a simple data.frame where I want to compute some summary statistics on a rolling basis. For example, a rolling median over a window of five observations (2 lags, current one and 2 ahead) is achieved by

```<code>library(dplyr)
x <- data.frame("vals" = rnorm(3e04))
y <- x %>%
         mutate(med5 = rollapply(data = vals,
                width = 5,
                FUN = median,
                align = "center",
                fill = NA,
                na.rm = TRUE))
</code>```

However, I would like to exclude the current row from this computation. I found the following approach:

```<code>z <- x %>%
      mutate(N=1:n()) %>%
      do(data.frame(., prmed = sapply(.$N, function(i) median(.$vals[.$N %in% c((i - 2):(i - 1), (i + 1):(i + 2))]))))
</code>```

This does what I want, if I subsequently set the first two values to NA.

So far so good, the only problem is that the latter approach is terribly slow compared to rollapply.

Is there a way to achieve the outcome of the latter with the speed of the former?

答:
The width= argument of rollapply can be a one element list containing a vector of offsets.

```<code>y <- x %>%
  mutate(med5 = rollapply(data = vals,
                          width = list(c(-2, -1, 1, 2)),
                          FUN = median,
                          na.rm = TRUE,
                          fill = NA))
</code>```

Note that align = "center" is the default and so does not have to specified. In addition, if we use offsets then align= is ignored. For safety, TRUE should be written out in full since T can also be a variable name.

Title: use rollaply without current row

Body:
I have a simple data.frame where I want to compute some summary statistics on a rolling basis. For example, a rolling median over a window of five observations (2 lags, current one and 2 ahead) is achieved by

library(dplyr)
x <- data.frame("vals" = rnorm(3e04))
y <- x %>%
         mutate(med5 = rollapply(data = vals,
                width = 5,
                FUN = median,
                align = "center",
                fill = NA,
                na.rm = TRUE))

However, I would like to exclude the current row from this computation. I found the following approach:

z <- x %>%
      mutate(N=1:n()) %>%
      do(data.frame(., prmed = sapply(.$N, function(i) median(.$vals[.$N %in% c((i - 2):(i - 1), (i + 1):(i + 2))]))))

This does what I want, if I subsequently set the first two values to NA.

So far so good, the only problem is that the latter approach is terribly slow compared to rollapply.

Is there a way to achieve the outcome of the latter with the speed of the former?

Body:
The width= argument of rollapply can be a one element list containing a vector of offsets.

y <- x %>%
  mutate(med5 = rollapply(data = vals,
                          width = list(c(-2, -1, 1, 2)),
                          FUN = median,
                          na.rm = TRUE,
                          fill = NA))

Note that align = "center" is the default and so does not have to specified. In addition, if we use offsets then align= is ignored. For safety, TRUE should be written out in full since T can also be a variable name.


问:
Gaussian Process Posterior (Python)
I have created and sampled a jointly Gaussian prior with mean=0 using the code below:

```<code>import numpy as np
import matplotlib.pyplot as plt
from math import pi
from scipy.spatial.distance import cdist
import scipy.stats as sts

x_prior = np.linspace(-10,10,101)
x_prior = x_prior.reshape(-1,1)
mu = np.zeros(x_prior.shape)

#defining the Kernel for the covariance function

def sec(a,b, length_scale , sigma) :
    K = sigma * np.exp(-1/(2*length_scale) * cdist(a,b)**2)
    return K

#defining the Gaussian Process prior

def GP(a , b, mu , kernel , length_scale, sigma , samples ) :
    f = np.random.multivariate_normal(mu.flatten(), kernel(a ,b , length_scale , sigma ) , samples)
    return f

prior = GP(x_prior ,x_prior, mu , sec , 100, 1 , 5)

plt.figure()
plt.grid()
plt.title('samples from the Gaussian prior')
plt.plot(x_prior , prior.T)
plt.show()
</code>```

Then, when adding in some 'observed' data, I wish to compute the posterior over these points but this is where I become stuck.

Here's my code for introducing new data:

```<code>x_train = np.array([-10,-8,5,-1,2])
x_train = x_train.reshape(-1,1)
def straight_line(m , x , c):
    y = 5*x + c
    return y
ytrain = straight_line(5 , x_train , 0)
</code>```

It's my understanding that you calculate a conditional distribution over the new data given the prior and new x values associated with the observed data.

Do you then wish to update the multivariate prior to become the posterior by performing some sort of change to the mean values to include the new y values?

I have used the following resources to try and attempt this:

http://katbailey.github.io/post/gaussian-processes-for-dummies/
https://www.robots.ox.ac.uk/~mebden/reports/GPtutorial.pdf

but I'm really trying to understand what happens at each stage, and why, so that when I get a posterior (which I can't do) I know exactly how I got there.

Here's some solutions I've been trying to implement but so far no avail:

```<code>K_train = sec(x_train , x_train , 1,1)
K_prior = sec(x_prior , x_prior , 1,1)
K_pt =  sec(x_prior , x_train , 1,1)
K_tp = sec(x_train , x_prior ,  1,1)  ## = k_tp transpose
prior = sts.multivariate_normal(mu.flatten(), K_prior)
#mean_test = np.dot(K_p , np.linalg.inv(K_prior))
mean_function = np.dot(np.dot(K_tp ,np.linalg.inv(K_prior).T) , prior )
covariance_function = K_train - np.dot(np.dot(K_tp ,np.linalg.inv(K_prior).T) , K_pt)
</code>```

答:
Just for additional follow-up. I have written my code into a Juypiter format here:

https://github.com/SpaceMeerkat/Scariff

with associated read-through material here:

https://spacemeerkat.wordpress.com/

Just in case anyone wanted to work through this kind of material and became stuck like I did.

Title: Gaussian Process Posterior (Python)

Body:
I have created and sampled a jointly Gaussian prior with mean=0 using the code below:

import numpy as np
import matplotlib.pyplot as plt
from math import pi
from scipy.spatial.distance import cdist
import scipy.stats as sts

x_prior = np.linspace(-10,10,101)
x_prior = x_prior.reshape(-1,1)
mu = np.zeros(x_prior.shape)

#defining the Kernel for the covariance function

def sec(a,b, length_scale , sigma) :
    K = sigma * np.exp(-1/(2*length_scale) * cdist(a,b)**2)
    return K

#defining the Gaussian Process prior

def GP(a , b, mu , kernel , length_scale, sigma , samples ) :
    f = np.random.multivariate_normal(mu.flatten(), kernel(a ,b , length_scale , sigma ) , samples)
    return f

prior = GP(x_prior ,x_prior, mu , sec , 100, 1 , 5)

plt.figure()
plt.grid()
plt.title('samples from the Gaussian prior')
plt.plot(x_prior , prior.T)
plt.show()

Then, when adding in some 'observed' data, I wish to compute the posterior over these points but this is where I become stuck.

Here's my code for introducing new data:

x_train = np.array([-10,-8,5,-1,2])
x_train = x_train.reshape(-1,1)
def straight_line(m , x , c):
    y = 5*x + c
    return y
ytrain = straight_line(5 , x_train , 0)

It's my understanding that you calculate a conditional distribution over the new data given the prior and new x values associated with the observed data.

Do you then wish to update the multivariate prior to become the posterior by performing some sort of change to the mean values to include the new y values?

I have used the following resources to try and attempt this:

http://katbailey.github.io/post/gaussian-processes-for-dummies/
https://www.robots.ox.ac.uk/~mebden/reports/GPtutorial.pdf

but I'm really trying to understand what happens at each stage, and why, so that when I get a posterior (which I can't do) I know exactly how I got there.

Here's some solutions I've been trying to implement but so far no avail:

K_train = sec(x_train , x_train , 1,1)
K_prior = sec(x_prior , x_prior , 1,1)
K_pt =  sec(x_prior , x_train , 1,1)
K_tp = sec(x_train , x_prior ,  1,1)  ## = k_tp transpose
prior = sts.multivariate_normal(mu.flatten(), K_prior)
#mean_test = np.dot(K_p , np.linalg.inv(K_prior))
mean_function = np.dot(np.dot(K_tp ,np.linalg.inv(K_prior).T) , prior )
covariance_function = K_train - np.dot(np.dot(K_tp ,np.linalg.inv(K_prior).T) , K_pt)


问:
Redirect HTTP to HTTPS in Azure Application Gateway
I have configured an Application Gateway (AG) to do SSL termination/offload. The AG is configured to only listen on port 443 for HTTPS connections. Is it possible to redirect HTTP to HTTPS without having to:

Create a new VM that contains a webserver that redirects the traffic and configure AG to listen on port 80 with the new VM in its backend pool, or

Also allow HTTP connections to my application VM's and handle redirect in my application code

I'm hoping I overlooked a flag/feature in AG.

答:
EDIT ~2019+: Now done via Azure Portal. See/upvote Matt Sullivan's answer. Commandline-based approach kept below.

Command line approach (like Jonathan Mast's answer but with AZ CLI):

Create a listener for your HTTP traffic (e.g. FE-HTTP-80-Site). This can be done using Azure portal or CLI.

Create a listener for your HTTPS traffic (e.g. FE-HTTPS-443-Site). This can be done in the Azure portal or CLI.

Create a redirect configuration:

```<code>az network application-gateway redirect-config create \
--gateway-name AppGateway \
-g RSgroupAppGateway \
-n Redirect-Site-toHTTPS \
--type Permanent \
--include-path true \
--include-query-string true \
--target-listener FE-HTTPS-443-Site
</code>```

Create a rule for the HTTP traffic:

```<code>az network application-gateway rule create \
--gateway-name AppGateway \
-g RSgroupAppGateway \
-n Rule-HTTP-80-Site \
--rule-type Basic \
--http-listener FE-HTTP-80-Site \
--redirect-config Redirect-Site-toHTTPS
</code>```

Reference on Concept: Create an application gateway with URL path-based redirection using Azure PowerShell

AZ CLI Reference: Azure Command-Line Interface (CLI) documentation

GUI method (added ~2019+): Create an application gateway with HTTP to HTTPS redirection using the Azure portal

Body:
EDIT ~2019+: Now done via Azure Portal. See/upvote Matt Sullivan's answer. Commandline-based approach kept below.

Command line approach (like Jonathan Mast's answer but with AZ CLI):

Create a listener for your HTTP traffic (e.g. FE-HTTP-80-Site). This can be done using Azure portal or CLI.

Create a listener for your HTTPS traffic (e.g. FE-HTTPS-443-Site). This can be done in the Azure portal or CLI.

Create a redirect configuration:

az network application-gateway redirect-config create \
--gateway-name AppGateway \
-g RSgroupAppGateway \
-n Redirect-Site-toHTTPS \
--type Permanent \
--include-path true \
--include-query-string true \
--target-listener FE-HTTPS-443-Site

Create a rule for the HTTP traffic:

az network application-gateway rule create \
--gateway-name AppGateway \
-g RSgroupAppGateway \
-n Rule-HTTP-80-Site \
--rule-type Basic \
--http-listener FE-HTTP-80-Site \
--redirect-config Redirect-Site-toHTTPS

Reference on Concept: Create an application gateway with URL path-based redirection using Azure PowerShell

AZ CLI Reference: Azure Command-Line Interface (CLI) documentation

GUI method (added ~2019+): Create an application gateway with HTTP to HTTPS redirection using the Azure portal

ContentLicense: CC BY-SA 4.0


问:
How can I print the possible combinations of a list in Python?
My list is:

```<code>groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
</code>```

So I want to print all the unique combinations of teams that will play each other:

```<code>Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay
</code>```

Can I do this with a for loop?

答:
This should do what you want:

```<code>groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

for i in range(len(groupA)):
  for j in range(i+1, len(groupA)):
    print("{} Vs. {}".format(groupA[i], groupA[j]))
</code>```

If you prefer using itertools:

```<code>from itertools import combinations

groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

for combo in combinations(groupA, 2):
  print("{} Vs. {}".format(combo[0], combo[1]))
</code>```

Body:
My list is:

groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

So I want to print all the unique combinations of teams that will play each other:

Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay

Can I do this with a for loop?

Body:
This should do what you want:

groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

for i in range(len(groupA)):
  for j in range(i+1, len(groupA)):
    print("{} Vs. {}".format(groupA[i], groupA[j]))

If you prefer using itertools:

from itertools import combinations

groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

for combo in combinations(groupA, 2):
  print("{} Vs. {}".format(combo[0], combo[1]))


问:
Passing parameters to a window call in Windows
I'm new to programming against Windows calls, and I'm trying to figure out a way to pass a parameter to the lpfnWndProc function.  I have the following code:

```<code>HWND hwnd;
WNDCLASS wc1 = {0};

wc1.lpszClassName = TEXT( "sample" );
wc1.hInstance     = 0;
wc1.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc1.lpfnWndProc   = DepthWndProc;
</code>```

Note the line wc1.lpfnWndProc = DepthWndProc;  Am I able to pass DepthWndProc a parameter?  If so, what does the syntax look like?

Thanks!

答:
You can call DepthWndProc directly and pass its parameters, but why on earth would you do that?  That's not how windows programming works.

You are giving windows a function to call whenever it has a message to send to your window.

ContentLicense: CC BY-SA 2.5

Body:
I'm new to programming against Windows calls, and I'm trying to figure out a way to pass a parameter to the lpfnWndProc function.  I have the following code:

HWND hwnd;
WNDCLASS wc1 = {0};

wc1.lpszClassName = TEXT( "sample" );
wc1.hInstance     = 0;
wc1.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc1.lpfnWndProc   = DepthWndProc;

Note the line wc1.lpfnWndProc = DepthWndProc;  Am I able to pass DepthWndProc a parameter?  If so, what does the syntax look like?

Thanks!


问:
tel: & callto html not working with iphone for service numbers like *000#
Hi I'm trying to make mobile website that contains service link as the following:

```<code><a href="tel:*000#">*000#</a>
</code>```

I tried to encode the special characters & htmlentetries with no results, The call box appears but there is no action after you click call.

答:
The tel: URI scheme (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

Here is a simple example:

```<code><a href="tel:+15555551212">Call us free!</a>
</code>```

Body:
Hi I'm trying to make mobile website that contains service link as the following:

*000#

I tried to encode the special characters & htmlentetries with no results, The call box appears but there is no action after you click call.

Body:
The tel: URI scheme (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

Here is a simple example:

<a href="tel:+15555551212">Call us free!</a>


问:
Error:Execution failed for task ':transformClassesWithJarMergingForRelease'
I am implementing facebook native ads in unity that needs gradle build from unity. After importing to Android Studio and gradle sync it runs well but during signed APK it produces the error which is.

Error:Execution failed for task ':transformClassesWithJarMergingForRelease'.
   com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/unity3d/ads/android/BuildConfig.class

答:
This error means you have duplicate class definition for:

```<code>com.unity3d.ads.android.BuildConfig
</code>```

Try look into your jar/aar to see if the class is present at multiple places.

I like to use grep (linux/osx) or 7-Zip to quickly explores my jar/aar files

Body:
This error means you have duplicate class definition for:

com.unity3d.ads.android.BuildConfig

Try look into your jar/aar to see if the class is present at multiple places.

I like to use grep (linux/osx) or 7-Zip to quickly explores my jar/aar files


问:
leaflet geojson coordinates to array

var mymap = L.map('map').setView([53.7983587, -1.6191674], 11);
    mymap.createPane('labels');
    mymap.getPane('labels').style.zIndex = 650;
    mymap.getPane('labels').style.pointerEvents = 'none';

    var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
        attribution: '©OpenStreetMap, ©CartoDB'
}).addTo(mymap);

var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
        attribution: '©OpenStreetMap, ©CartoDB',
        pane: 'labels'
}).addTo(mymap);

 L.tileLayer('https://api.mapbox.com/styles/v1/adam97x/cjavcj1680vgz2sqshn70q5pg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWRhbTk3eCIsImEiOiJjamF2Y2k1NmswYzhuMnZtazlpNXU2NDExIn0.RifBBI5nelL-4d21mkn7Wg', {
  maxZoom: 18,
  attribution: 'Map data © OpenStreetMap contributors, ' +
   'CC-BY-SA, ' +
   'Imagery © Mapbox',
  id: 'mapbox.streets'
 }).addTo(mymap);

  // control that shows state info on hover
 var info = L.control();

 info.onAdd = function (mymap) {
  this._div = L.DomUtil.create('div', 'info');
  this.update();
  return this._div;
 };

 info.update = function (props) {
  this._div.innerHTML = '
Highlighted Postcode
' +  (props ?
   ' Postcode: ' + props.Name
   : 'Hover over a state');
 };

 info.addTo(mymap);

function style(feature) {
    return {
        fillColor: 'grey',
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.5
    };
}

L.geoJson(statesdata, {style: style}).addTo(mymap);

 function highlightFeature(e) {
  var layer = e.target;

  layer.setStyle({
   weight: 5,
   opacity: 1,
   color: '#000',
   dashArray: '',
   fillOpacity: 0.7
  });

  if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
   layer.bringToFront();
  }

  info.update(layer.feature.properties);
 }

 var geojson;

 function resetHighlight(e) {
  geojson.resetStyle(e.target);
  info.update();
 }
     function zoomToFeature(e) {
    mymap.fitBounds(e.target.getBounds());
                var coords = layer.feature.geometry.coordinates;
                console.log(coords);
 }
 coords = []; //define an array to store coordinates
 function onEachFeature(feature, layer) {
  layer.on({
   mouseover: highlightFeature,
   mouseout: resetHighlight,
   click: zoomToFeature
  });
 }

 geojson = L.geoJson(statesdata, {
  style: style,
  onEachFeature: onEachFeature
 }).addTo(mymap);
 test = [];
geojson.eachLayer(function (layer) {
    layer.bindPopup(layer.feature.properties.Name);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
  .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }</code>```

<!DOCTYPE html>

<meta charset=utf-8 />
<title>KML Data</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />

```
</div>
</div>
</p>

<p>I'm trying to output the geojson file's coordinates into an array upon clicking a sector (post code) of the map so i can flip them to lat,lng instead of lng,lat however I am struggling to do so.</p>

```function zoomToFeature(e) {
    mymap.fitBounds(e.target.getBounds());
                var coords = layer.feature.geometry.coordinates;
                console.log(coords);
}
```

I would have though it is something along these lines however I am getting feature is not defined as a result in the console, if anybody has any suggestions please let me know. Thank you in advanced!

答:
To get different details associated with click simply inspect event object passed to your click listener. For example:

```<code>function zoomToFeature(e) {
    mymap.fitBounds(e.target.getBounds());
    console.log(e.latlng); // {lat: 53.80551690917758, lng: -1.68365478515625}
    console.log(e.target.feature); // {type: "Feature", properties: {…}, geometry: {…}}
}
</code>```

To see what you can get from that event simply print it out as console.log(e) and unfold its subobject to see what you can get from it.

Title: leaflet geojson coordinates to array

Body:
var mymap = L.map('map').setView([53.7983587, -1.6191674], 11);
    mymap.createPane('labels');
    mymap.getPane('labels').style.zIndex = 650;
    mymap.getPane('labels').style.pointerEvents = 'none';

    var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
        attribution: '©OpenStreetMap, ©CartoDB'
}).addTo(mymap);

var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
        attribution: '©OpenStreetMap, ©CartoDB',
        pane: 'labels'
}).addTo(mymap);

 L.tileLayer('https://api.mapbox.com/styles/v1/adam97x/cjavcj1680vgz2sqshn70q5pg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWRhbTk3eCIsImEiOiJjamF2Y2k1NmswYzhuMnZtazlpNXU2NDExIn0.RifBBI5nelL-4d21mkn7Wg', {
  maxZoom: 18,
  attribution: 'Map data © OpenStreetMap contributors, ' +
   'CC-BY-SA, ' +
   'Imagery © Mapbox',
  id: 'mapbox.streets'
 }).addTo(mymap);

  // control that shows state info on hover
 var info = L.control();

 info.onAdd = function (mymap) {
  this._div = L.DomUtil.create('div', 'info');
  this.update();
  return this._div;
 };

 info.update = function (props) {
  this._div.innerHTML = '
Highlighted Postcode
' +  (props ?
   ' Postcode: ' + props.Name
   : 'Hover over a state');
 };

 info.addTo(mymap);

function style(feature) {
    return {
        fillColor: 'grey',
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.5
    };
}

L.geoJson(statesdata, {style: style}).addTo(mymap);

 function highlightFeature(e) {
  var layer = e.target;

  layer.setStyle({
   weight: 5,
   opacity: 1,
   color: '#000',
   dashArray: '',
   fillOpacity: 0.7
  });

  if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
   layer.bringToFront();
  }

  info.update(layer.feature.properties);
 }

 var geojson;

 function resetHighlight(e) {
  geojson.resetStyle(e.target);
  info.update();
 }
     function zoomToFeature(e) {
    mymap.fitBounds(e.target.getBounds());
                var coords = layer.feature.geometry.coordinates;
                console.log(coords);
 }
 coords = []; //define an array to store coordinates
 function onEachFeature(feature, layer) {
  layer.on({
   mouseover: highlightFeature,
   mouseout: resetHighlight,
   click: zoomToFeature
  });
 }

 geojson = L.geoJson(statesdata, {
  style: style,
  onEachFeature: onEachFeature
 }).addTo(mymap);
 test = [];
geojson.eachLayer(function (layer) {
    layer.bindPopup(layer.feature.properties.Name);

});

  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
  .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }

<!DOCTYPE html>

<meta charset=utf-8 />
<title>KML Data</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />

I'm trying to output the geojson file's coordinates into an array upon clicking a sector (post code) of the map so i can flip them to lat,lng instead of lng,lat however I am struggling to do so.

function zoomToFeature(e) {
    mymap.fitBounds(e.target.getBounds());
                var coords = layer.feature.geometry.coordinates;
                console.log(coords);
}

I would have though it is something along these lines however I am getting feature is not defined as a result in the console, if anybody has any suggestions please let me know. Thank you in advanced!

Body:
To get different details associated with click simply inspect event object passed to your click listener. For example:

function zoomToFeature(e) {
    mymap.fitBounds(e.target.getBounds());
    console.log(e.latlng); // {lat: 53.80551690917758, lng: -1.68365478515625}
    console.log(e.target.feature); // {type: "Feature", properties: {…}, geometry: {…}}
}

To see what you can get from that event simply print it out as console.log(e) and unfold its subobject to see what you can get from it.


问:
JavaScript - href vs onclick for callback function on Hyperlink
I want to run a simple JavaScript function on a click without any redirection.

Is there any difference or benefit between putting the JavaScript call in the href attribute  (like this):

```<code><a href="javascript:my_function();window.print();">....</a>
</code>```

vs. putting it in the onclick attribute (binding it to the onclick event)?

答:
```<code> <hr>
            <h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
            <button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
            <div class="pull-right">
                <button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
            </div>
        </div>
            <script type="text/javascript">
                $(document).ready(function(){
                $('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
                });
            </script>
            <script type="text/javascript">
                $(document).ready(function(){
                $('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
                });
            </script>
</code>```

Body:
I want to run a simple JavaScript function on a click without any redirection.

Is there any difference or benefit between putting the JavaScript call in the href attribute  (like this):

....

vs. putting it in the onclick attribute (binding it to the onclick event)?


问:
Why does JavaScript map function return undefined?
My code

```<code> var arr = ['a','b',1];
 var results = arr.map(function(item){
                if(typeof item ==='string'){return item;}
               });
</code>```

This gives the following results

```<code>["a","b",undefined]
</code>```

I don't want undefined in the results array. How can I do it?

答:
Filter works for this specific case where the items are not modified. But in many cases when you use map you want to make some modification to the items passed.

if that is your intent, you can use reduce:

```<code>var arr = ['a','b',1];
var results = arr.reduce((results, item) => {
    if (typeof item === 'string') results.push(modify(item)) // modify is a fictitious function that would apply some change to the items in the array
    return results
}, [])
</code>```

Body:
My code

 var arr = ['a','b',1];
 var results = arr.map(function(item){
                if(typeof item ==='string'){return item;}
               });

This gives the following results

["a","b",undefined]

I don't want undefined in the results array. How can I do it?

Body:
Filter works for this specific case where the items are not modified. But in many cases when you use map you want to make some modification to the items passed.

if that is your intent, you can use reduce:

var arr = ['a','b',1];
var results = arr.reduce((results, item) => {
    if (typeof item === 'string') results.push(modify(item)) // modify is a fictitious function that would apply some change to the items in the array
    return results
}, [])


问:
Rewrite foreach loops into linq query?
I tried to rewrite the following loops in one "elegant" linq query but no success!

```<code>foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }
</code>```

Could anyone suggest a query (if even possible)?

Thanks in advance

答:
You can do something like

List2.SingleOrDefault(x => List1.Any(c => c == x));

Obviosly insert what ever properties you want to compare. This would return the match or null. If you have multiple results, change SingleOrDefault to Where.

Title: Rewrite foreach loops into linq query?

Body:
I tried to rewrite the following loops in one "elegant" linq query but no success!

foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }

Could anyone suggest a query (if even possible)?

Thanks in advance


问:
Keep a parent process waiting and run linux command as many times as wanted
I have the below C code in linux (using gcc):

```<code>void doWho(void)
{
        char entry[10];
        int ret, i;
        ret = read(0, entry, 10);
        if (*entry == 'u')
        {
                for(i=0; i<3; i++)
                {
                execl("/usr/bin/who","who",NULL);
                }
        }
}

int main(int argc, char *argv[])
{
        int childpid;

        printf("Before it forks\n");
        childpid = fork();

        if(childpid == 0)
        {
                printf("This is a child process\n");
                doWho();
                exit(0);
        } else
        {
                printf("This is the parent process\n");
                wait(NULL);
        }

        return 0;
}
</code>```

I want the parent process to keep waiting indefinitely and run "who" every time I press the "u" key. I only get the desired effect one time and then the child and parent processes exit. Any help on this?

答:
Observe below loop :

```<code>for(i=0; i<3; i++)
{
    execl("/usr/bin/who","who",NULL);
}
</code>```

It doesn't matter how many times you rotate the loop , it will execute only once because when child process starts running(PCB created), you are calling function doWho then control will come to doWho function and in doWho function what you are doing ? execl(). what execl() does is that " it replaces current process(child) with new process, after when i = 0 whole child process image got replaced with new one using execl(), so there is nothing left in child process that's why it will execute only once.

If you want to execute  as many as you should use fork() in the function because then exec will replace every process created by fork(), but it's not advised to run fork() in loop because your program may crash when there are no more resource available.

So replace your doWho function as

```<code>void doWho(void)
{
        char entry[10] = {0};
        int ret, i;

        for(; ;) {
        /** who command will be executed when ever condition is true **/
                ret = read(0, entry, 10);
                __fpurge(stdin);//to clear stdin buffer everytime
                if (*entry == 'u') {

                        if(fork()==0)//only this newly created process will be replaces by execl not one was in main()
                                execl("/usr/bin/who","who",NULL);
                        else
                                ;// this parents does nothing
                }
        }
}
</code>```

I hope it helps.

Body:
I have the below C code in linux (using gcc):

void doWho(void)
{
        char entry[10];
        int ret, i;
        ret = read(0, entry, 10);
        if (*entry == 'u')
        {
                for(i=0; i<3; i++)
                {
                execl("/usr/bin/who","who",NULL);
                }
        }
}

int main(int argc, char *argv[])
{
        int childpid;

        printf("Before it forks\n");
        childpid = fork();

        if(childpid == 0)
        {
                printf("This is a child process\n");
                doWho();
                exit(0);
        } else
        {
                printf("This is the parent process\n");
                wait(NULL);
        }

        return 0;
}

I want the parent process to keep waiting indefinitely and run "who" every time I press the "u" key. I only get the desired effect one time and then the child and parent processes exit. Any help on this?

Body:
Observe below loop :

for(i=0; i<3; i++)
{
    execl("/usr/bin/who","who",NULL);
}

It doesn't matter how many times you rotate the loop , it will execute only once because when child process starts running(PCB created), you are calling function doWho then control will come to doWho function and in doWho function what you are doing ? execl(). what execl() does is that " it replaces current process(child) with new process, after when i = 0 whole child process image got replaced with new one using execl(), so there is nothing left in child process that's why it will execute only once.

If you want to execute  as many as you should use fork() in the function because then exec will replace every process created by fork(), but it's not advised to run fork() in loop because your program may crash when there are no more resource available.

So replace your doWho function as

void doWho(void)
{
        char entry[10] = {0};
        int ret, i;

        for(; ;) {
        /** who command will be executed when ever condition is true **/
                ret = read(0, entry, 10);
                __fpurge(stdin);//to clear stdin buffer everytime
                if (*entry == 'u') {

                        if(fork()==0)//only this newly created process will be replaces by execl not one was in main()
                                execl("/usr/bin/who","who",NULL);
                        else
                                ;// this parents does nothing
                }
        }
}

I hope it helps.


问:
Querying varchars as decimals in SQL Server
I have a problem in SQL Server, I am trying to query

```<code>where x.numbers >= '9'
</code>```

where x.numbers was stored as varchar and some of the values I have in that field are

```<code>8.9
9.3
6.7
>10
8.3
>= 9
</code>```

If I try isnumeric(x.numbers), then it is excluding those values that start with > or >=. and I tried cast(x.numbers as decimal) but it is not working as well. Please advise

答:
This is my attempt. It's not pretty, but might get you what you're after. It increases/decreases the values of values that have either < or >:

```<code>CREATE TABLE #Sample (N varchar(5));
INSERT INTO #Sample
VALUES ('7.9'),('4.5'),('9'),('>10'),('6.7'),('11.7'),('>12'),('<=10'),('<9');
GO

SELECT *
FROM #Sample;
GO
WITH CTE AS (
    SELECT *,
           CASE WHEN N LIKE '>=%' OR N LIKE '<=%' THEN TRY_CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=',''))
                WHEN N LIKE '>%' THEN TRY_CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) + 0.1 --Adding .1 as it needs to be more than it's value
                WHEN N LIKE '<%' THEN TRY_CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) - 0.1
                ELSE TRY_CONVERT(decimal(5,1),N)
           END AS Nr
    FROM #Sample S)
SELECT N
FROM CTE
WHERE Nr >= 9;

GO
DROP TABLE #Sample;

--SQL 2008, just CONVERT
WITH CTE AS (
    SELECT *,
           CASE WHEN N LIKE '>=%' OR N LIKE '<=%' THEN CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=',''))
                WHEN N LIKE '>%' THEN CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) + 0.1 --Adding .1 as it needs to be more than it's value
                WHEN N LIKE '<%' THEN CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) - 0.1
                ELSE CONVERT(decimal(5,1),N)
           END AS Nr
    FROM #Sample S)
SELECT N
FROM CTE
WHERE Nr >= 9;
</code>```

Body:
I have a problem in SQL Server, I am trying to query

where x.numbers >= '9'

where x.numbers was stored as varchar and some of the values I have in that field are

8.9
9.3
6.7
>10
8.3
>= 9

If I try isnumeric(x.numbers), then it is excluding those values that start with > or >=. and I tried cast(x.numbers as decimal) but it is not working as well. Please advise

Body:
This is my attempt. It's not pretty, but might get you what you're after. It increases/decreases the values of values that have either < or >:

CREATE TABLE #Sample (N varchar(5));
INSERT INTO #Sample
VALUES ('7.9'),('4.5'),('9'),('>10'),('6.7'),('11.7'),('>12'),('<=10'),('<9');
GO

SELECT *
FROM #Sample;
GO
WITH CTE AS (
    SELECT *,
           CASE WHEN N LIKE '>=%' OR N LIKE '<=%' THEN TRY_CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=',''))
                WHEN N LIKE '>%' THEN TRY_CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) + 0.1 --Adding .1 as it needs to be more than it's value
                WHEN N LIKE '<%' THEN TRY_CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) - 0.1
                ELSE TRY_CONVERT(decimal(5,1),N)
           END AS Nr
    FROM #Sample S)
SELECT N
FROM CTE
WHERE Nr >= 9;

GO
DROP TABLE #Sample;

--SQL 2008, just CONVERT
WITH CTE AS (
    SELECT *,
           CASE WHEN N LIKE '>=%' OR N LIKE '<=%' THEN CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=',''))
                WHEN N LIKE '>%' THEN CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) + 0.1 --Adding .1 as it needs to be more than it's value
                WHEN N LIKE '<%' THEN CONVERT(decimal(5,1),REPLACE(REPLACE(REPLACE(N,'>',''),'<',''),'=','')) - 0.1
                ELSE CONVERT(decimal(5,1),N)
           END AS Nr
    FROM #Sample S)
SELECT N
FROM CTE
WHERE Nr >= 9;


问:
Error in Hangman Game
I am trying to make a hangman game where the computer randomly pulls a word from the array, but I can't seem to connect it to the main class.

```<code>public class Main {

public static void main(String[] args) {
    Game game = new Game();
    game.getRandom(args);
    Prompter prompter = new Prompter(game);
    while(game.getRemainingTries() > 0) {
        game.display();
        prompter.promptForGuess();
    }
}

}

//Prompter class
public boolean promptForGuess() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a letter to guess: ");
    String guessInput = scanner.nextLine();
    char guess = guessInput.charAt(0);
    return game.applyGuess(guess);
}

public void displayProgress(String progress) {
    System.out.printf("You have %d tries left to solve: %s%n",
                      game.getRemainingTries(),
                      game.getCurrentProgress(progress));

//Game class
public String getRandom(String[] array) {
    random = myString[(int) (Math.random() * myString.length)];
    return random;
}
public String display(String random) {
    StringBuilder str = new StringBuilder();
    for(int i = 0; i < random.length(); i++ ) {
        str.append("-");
    }
    System.out.println(str.toString());
    return str.toString();
</code>```

I'm expecting it to show up as dashes for the amount of letters in each random word(fluctuates depending on the length of the random word)

This is the error I get:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method display(String) in the type Game is not applicable for the arguments () at Main.main(Main.java:9)

Do I need to pass an argument into the game.display()? Any help would be appreciated!

答: Remove the String paramater from your display method as it's not needed.</p>

Title: Error in Hangman Game

Body:
I am trying to make a hangman game where the computer randomly pulls a word from the array, but I can't seem to connect it to the main class.

public class Main {

public static void main(String[] args) {
    Game game = new Game();
    game.getRandom(args);
    Prompter prompter = new Prompter(game);
    while(game.getRemainingTries() > 0) {
        game.display();
        prompter.promptForGuess();
    }
}

}

//Prompter class
public boolean promptForGuess() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a letter to guess: ");
    String guessInput = scanner.nextLine();
    char guess = guessInput.charAt(0);
    return game.applyGuess(guess);
}

public void displayProgress(String progress) {
    System.out.printf("You have %d tries left to solve: %s%n",
                      game.getRemainingTries(),
                      game.getCurrentProgress(progress));

//Game class
public String getRandom(String[] array) {
    random = myString[(int) (Math.random() * myString.length)];
    return random;
}
public String display(String random) {
    StringBuilder str = new StringBuilder();
    for(int i = 0; i < random.length(); i++ ) {
        str.append("-");
    }
    System.out.println(str.toString());
    return str.toString();

I'm expecting it to show up as dashes for the amount of letters in each random word(fluctuates depending on the length of the random word)

This is the error I get:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method display(String) in the type Game is not applicable for the arguments () at Main.main(Main.java:9)

Do I need to pass an argument into the game.display()? Any help would be appreciated!


问:
PHP - How to re-encode a URI
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.

Here is the situation:

JavaScript passes encoded uri as query string parameter to php script.

PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:

```<code>http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great
</code>```

Is there a pre-built php function for this or should I just write my own?

PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.

Thanks,
Macy

Title: PHP - How to re-encode a URI

Body:
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.

Here is the situation:

JavaScript passes encoded uri as query string parameter to php script.

PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:

http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great

Is there a pre-built php function for this or should I just write my own?

PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.

Thanks,
Macy

Body:
urldecode:

http://www.php.net/manual/en/function.urldecode.php


问:
Making asynchronous HTTP calls from flows
In Corda, how can I make an asynchronous HTTP request from within a flow? Is there an API to suspend a flow while awaiting the response to the HTTP call, or a way to provide a callback?</p>

答:
Corda doesn't currently provide a mechanism for making an asynchronous HTTP request and then either suspending the flow while awaiting a response, or providing a callback that will be called when the response is received.

Instead, it is recommended that you make the HTTP request before initiating the flow, then pass in the response as an argument when instantiating the flow.

Sometimes, this isn't possible. For example, the HTTP request may be required by a response flow that is initiated automatically, or it may depend on the contents of a message received from a counterparty.

In this case, you can still support this kind of workflow as follows. Suppose you are writing a CorDapp for loan applications, which are represented as LoanApplicationStates. Without an HTTP call, the responder doesn't know whether to accept the loan application or not.

Instead of creating a LoanApplicationState directly, the flow would create an UnacceptedLoanApplicationState, which the responder would store on their ledger. Once the flow ends, the responder can make an HTTP call outside of the flow framework. Based on the result of the HTTP call, the responder will either kick off an approve flow that creates a transaction to transform the UnacceptedLoanApplicationState into an LoanApplicationState, or kick off a reject flow to consume the UnacceptedLoanApplicationState state without issuing an accepted LoanApplicationState.

Alternatively, you could add a status field to the LoanApplicationState, specifying whether the loan is approved or not. Initially, the loan state would have the field set to unapproved. Then, based on the result of the HTTP request, the responder would initiate one of two flows to update the LoanApplicationState, updating it with either an approved or a rejected status.


答:
You should pass a String to you display method.

Example:

```<code>game.display("String value here");
</code>```

Title: Error in Hangman Game

Body:
You should pass a String to you display method.

Example:

game.display("String value here");


问:
Setting number in list that's less than 1% to 1% while keeping total 100%
I'm running into a logic issue with my web application.

Background: There will be a bunch of div's in a row across the page. Their CSS width: percentage is equal to the percentage the item's int value divided by the list's total int value.

The problem: I don't want any of the widths to be less than 1%.  This means I have to increase the width of items lower than 1% to 1%, and reduce the widths of all of the other items so the percentage total adds back up to 100% exactly.

This creates an issue where an item that was already exactly 1% gets reduced to less than 1%.

I've tried so many ways to do this, but this is my current iteration.  I made it simple for myself and you guys by putting it into a console application.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PercentageOfTotal
{
    public class Item
    {
        public int Value { get; set; }
        public double Percent { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var items = new List<Item>();

            items.Add(new Item { Value = 26 });
            items.Add(new Item { Value = 31 });
            items.Add(new Item { Value = 47 });
            items.Add(new Item { Value = 175 });
            items.Add(new Item { Value = 50 });
            items.Add(new Item { Value = 1 });
            items.Add(new Item { Value = 74 });
            items.Add(new Item { Value = 8 });
            items.Add(new Item { Value = 219 });
            items.Add(new Item { Value = 169 });

            int sum = items.Sum(x => x.Value);
            double minPercentage = 0.01;

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                item.Percent = item.Value / (double)sum;
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.WriteLine("\n");

            var itemsLessThanOnePercent = items.Where(x => x.Percent < minPercentage).ToList();
            var itemsGreaterThanOrEqualToOnePercent = items.Where(x => x.Percent >= minPercentage).ToList();
            double totalPercentageLessThanOne = itemsLessThanOnePercent.Sum(x => x.Percent);
            double reduceEachGreaterThanOneBy = ((itemsLessThanOnePercent.Count() * minPercentage) - totalPercentageLessThanOne) / itemsGreaterThanOrEqualToOnePercent.Count();

            foreach (var item in itemsGreaterThanOrEqualToOnePercent)
            {
                item.Percent = item.Percent - reduceEachGreaterThanOneBy;
            }

            foreach (var item in itemsLessThanOnePercent)
            {
                item.Percent = minPercentage;
            }

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.ReadLine();
        }
    }
}
</code>```

As you can see, this case it reduces the item with Value = 8 to less than 1% (0.009) because the item.Value was already 1% in the first place.

Basically, I want the item's percentage to be relative to the overall sum of item.Value without having any percentages less than 1% and the total of percentages equaling 100%.

Any help would be appreciated.

答:
You can enumerate items in order of increasing Value. For each item, assign percentage and if less that minimum - carry over that overflow to distribute to the rest of items. Well it's hard to explain in words I admit, so here is sample code:

```<code>double overflow = 0;
int left = items.Count;
// loop in order of ascending value
foreach (var item in items.OrderBy(c => c.Value))
{
    // calculate part of overflow to assign to this item, based on total and how much items still left
    var overflowForItem = overflow / left;
    // assign a bit less than expected if there is overflow
    item.Percent = (item.Value - overflowForItem) / (double)sum;
    // reduce overflow (we just assigned part of it above)
    overflow -= overflowForItem;
    if (item.Percent < minPercentage) {
        overflow += (minPercentage - item.Percent) * sum;
        item.Percent = minPercentage;
    }
    left--;
}
</code>```

Body:
I'm running into a logic issue with my web application.

Background: There will be a bunch of div's in a row across the page. Their CSS width: percentage is equal to the percentage the item's int value divided by the list's total int value.

The problem: I don't want any of the widths to be less than 1%.  This means I have to increase the width of items lower than 1% to 1%, and reduce the widths of all of the other items so the percentage total adds back up to 100% exactly.

This creates an issue where an item that was already exactly 1% gets reduced to less than 1%.

I've tried so many ways to do this, but this is my current iteration.  I made it simple for myself and you guys by putting it into a console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PercentageOfTotal
{
    public class Item
    {
        public int Value { get; set; }
        public double Percent { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var items = new List<Item>();

            items.Add(new Item { Value = 26 });
            items.Add(new Item { Value = 31 });
            items.Add(new Item { Value = 47 });
            items.Add(new Item { Value = 175 });
            items.Add(new Item { Value = 50 });
            items.Add(new Item { Value = 1 });
            items.Add(new Item { Value = 74 });
            items.Add(new Item { Value = 8 });
            items.Add(new Item { Value = 219 });
            items.Add(new Item { Value = 169 });

            int sum = items.Sum(x => x.Value);
            double minPercentage = 0.01;

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                item.Percent = item.Value / (double)sum;
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.WriteLine("\n");

            var itemsLessThanOnePercent = items.Where(x => x.Percent < minPercentage).ToList();
            var itemsGreaterThanOrEqualToOnePercent = items.Where(x => x.Percent >= minPercentage).ToList();
            double totalPercentageLessThanOne = itemsLessThanOnePercent.Sum(x => x.Percent);
            double reduceEachGreaterThanOneBy = ((itemsLessThanOnePercent.Count() * minPercentage) - totalPercentageLessThanOne) / itemsGreaterThanOrEqualToOnePercent.Count();

            foreach (var item in itemsGreaterThanOrEqualToOnePercent)
            {
                item.Percent = item.Percent - reduceEachGreaterThanOneBy;
            }

            foreach (var item in itemsLessThanOnePercent)
            {
                item.Percent = minPercentage;
            }

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.ReadLine();
        }
    }
}

As you can see, this case it reduces the item with Value = 8 to less than 1% (0.009) because the item.Value was already 1% in the first place.

Basically, I want the item's percentage to be relative to the overall sum of item.Value without having any percentages less than 1% and the total of percentages equaling 100%.

Any help would be appreciated.

Body:
You can enumerate items in order of increasing Value. For each item, assign percentage and if less that minimum - carry over that overflow to distribute to the rest of items. Well it's hard to explain in words I admit, so here is sample code:

double overflow = 0;
int left = items.Count;
// loop in order of ascending value
foreach (var item in items.OrderBy(c => c.Value))
{
    // calculate part of overflow to assign to this item, based on total and how much items still left
    var overflowForItem = overflow / left;
    // assign a bit less than expected if there is overflow
    item.Percent = (item.Value - overflowForItem) / (double)sum;
    // reduce overflow (we just assigned part of it above)
    overflow -= overflowForItem;
    if (item.Percent < minPercentage) {
        overflow += (minPercentage - item.Percent) * sum;
        item.Percent = minPercentage;
    }
    left--;
}


问:
Python read/write/seek operations under the hood
While creating a character device on a Linux system, I interacted with it using Python and its basic file operations.

After experiencing several crashes, I started printing debug messages and noticed a strange behavior: it seems that Python "optimizes" file operations in a weird sense.

Let's peek at an example; here's a basic code and output of an interaction:

Kernel module

```<code>// Several includes and kernel module initialization

static ssize_t dev_read(struct file *filep, char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_read with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_write with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static long long dev_llseek(struct file *filep, long long offset, int orig){
    printk(KERN_INFO "[DEBUGGER] - dev_llseek with offset: 0x%llx, orig: %d\n", offset, orig);
    return offset;
}

static int dev_release(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static int dev_open(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static struct file_operations fops =
{
   .open = dev_open,
   .read = dev_read,
   .write = dev_write,
   .release = dev_release,
   .llseek = dev_llseek,
};

int init_module(void){
   // Code to create character device
   return 0;
}

void cleanup_module(void){
   // Code to delete character device
}
</code>```

Python

with open("/dev/chardevice", "r+b") as character:
   character.seek(1)
   character.read(4)
   character.seek(0x7f123456)
   character.read(20)
   character.write("\xff" * 4)
```

<h3>Output</h3>

```# seek(1)
[DEBUGGER] - dev_llseek with offset: 0x0, orig: 0
[DEBUGGER] - dev_read with len: 1, offset: 0x0.
[DEBUGGER] - dev_llseek with offset: 0x1, orig: 0
# read(4)
[DEBUGGER] - dev_read with len: 4, offset: 0x0.
# seek(0x7f123456)
[DEBUGGER] - dev_llseek with offset: 0x7f123000, orig: 0
[DEBUGGER] - dev_read with len: 1110, offset: 0x0.
# read(20)
[DEBUGGER] - dev_read with len: 4096, offset: 0x0.
# write("\xff" * 4)
[DEBUGGER] - dev_write with len: 4, offset: 0x0.
```

It is clear that the basic file operations do not translate directly to the same operations on file, with the clearest examples being that seek to 0x7f123000 instead of 0x7f123456 and the read of 4096 bytes while only a read on 20 bytes was requested.

This raises the following questions:

Why is this a feature?

What optimization does it achieve, as most of it doesn't look like a good "next-operation" prediction?

Is it documented anywhere, to know what to expect when programming a read/write functionality beforehand?

Besides pure interest about this area, I still wish to use Python for easier access - so is there any way to disable this optimization, and force Python to behave like a C code executing these operations?

Thanks!

答:
Python's file objects are actually wrappers around FILE* object (in C language), so they are buffered streams. Because of buffering, Python's operations with file don't translate them into the syscalls with the same parameters, but attempt to optimize request time (both for current and future operations).

Method open() accepts buffering parameter as 3d argument. Passing 0 should disable the buffering, so python will translate all file's requests directly to the underlying system:

```<code>open("/dev/chardevice", "r+b", 0)
</code>```

Body:
While creating a character device on a Linux system, I interacted with it using Python and its basic file operations.

After experiencing several crashes, I started printing debug messages and noticed a strange behavior: it seems that Python "optimizes" file operations in a weird sense.

Let's peek at an example; here's a basic code and output of an interaction:

Kernel module

// Several includes and kernel module initialization

static ssize_t dev_read(struct file *filep, char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_read with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_write with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static long long dev_llseek(struct file *filep, long long offset, int orig){
    printk(KERN_INFO "[DEBUGGER] - dev_llseek with offset: 0x%llx, orig: %d\n", offset, orig);
    return offset;
}

static int dev_release(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static int dev_open(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static struct file_operations fops =
{
   .open = dev_open,
   .read = dev_read,
   .write = dev_write,
   .release = dev_release,
   .llseek = dev_llseek,
};

int init_module(void){
   // Code to create character device
   return 0;
}

void cleanup_module(void){
   // Code to delete character device
}

Python

with open("/dev/chardevice", "r+b") as character:
   character.seek(1)
   character.read(4)
   character.seek(0x7f123456)
   character.read(20)
   character.write("\xff" * 4)

Output

# seek(1)
[DEBUGGER] - dev_llseek with offset: 0x0, orig: 0
[DEBUGGER] - dev_read with len: 1, offset: 0x0.
[DEBUGGER] - dev_llseek with offset: 0x1, orig: 0
# read(4)
[DEBUGGER] - dev_read with len: 4, offset: 0x0.
# seek(0x7f123456)
[DEBUGGER] - dev_llseek with offset: 0x7f123000, orig: 0
[DEBUGGER] - dev_read with len: 1110, offset: 0x0.
# read(20)
[DEBUGGER] - dev_read with len: 4096, offset: 0x0.
# write("\xff" * 4)
[DEBUGGER] - dev_write with len: 4, offset: 0x0.

It is clear that the basic file operations do not translate directly to the same operations on file, with the clearest examples being that seek to 0x7f123000 instead of 0x7f123456 and the read of 4096 bytes while only a read on 20 bytes was requested.

This raises the following questions:

Why is this a feature?

What optimization does it achieve, as most of it doesn't look like a good "next-operation" prediction?

Is it documented anywhere, to know what to expect when programming a read/write functionality beforehand?

Besides pure interest about this area, I still wish to use Python for easier access - so is there any way to disable this optimization, and force Python to behave like a C code executing these operations?

Thanks!

Body:
Python's file objects are actually wrappers around FILE* object (in C language), so they are buffered streams. Because of buffering, Python's operations with file don't translate them into the syscalls with the same parameters, but attempt to optimize request time (both for current and future operations).

Method open() accepts buffering parameter as 3d argument. Passing 0 should disable the buffering, so python will translate all file's requests directly to the underlying system:

open("/dev/chardevice", "r+b", 0)


答:
Try this</p>

```<code>declare @minDate Datetime
declare @maxdate Datetime

select @minDate = min(hashDate), @maxdate = max(hashDate)
from table
where hash in (@starthash, @endhash)

select * from table
where hashDate > @minDate and hashDate <= @maxdate
</code>```

Title: SQL Server : find rows between 2 rows

Body:
Modifying to more accurately represent the problem I am trying to solve. I over simplified the question the first time.

I have 2 SQL Server 2012 tables with data like so:

Table CommitBranch

Hash                                        HashDate                 BranchName
-----------------------------------------------------------------------------------
4191737d919e599690a8b9efd691ffc5165908f9    2013-01-26 15:24:44.000  B1
4191737d919e599690a8b9efd691ffc5165908f9    2013-01-26 15:24:44.000  B2
59503c5e22914b4926e8b5352ef254ebf67b1245    2013-01-28 19:28:12.000  B1
b3052d0c950a731d7221bab8825ba5787a9eb372    2013-01-29 17:05:02.000  B1
54752ce05b2c7784ff22c6161f9ecc33d4b1149f    2013-01-29 17:42:16.000  B2
d7c008d807d3439539b98dccf4c93ee6bc33405c    2013-01-29 21:29:32.000  B1
c890ca6ab1735ee391407ca80aa789a560632709    2013-01-31 04:39:57.000  B2
bf75a42b88782b0dc084a5642cc98876ad3ef41d    2013-01-31 04:41:30.000  B3
e54982d42d2b87e35d47536cd2017c18117afc28    2013-01-31 15:54:20.000  B1
e54982d42d2b87e35d47536cd2017c18117afc28    2013-01-31 15:54:20.000  B2
e54982d42d2b87e35d47536cd2017c18117afc28    2013-01-31 15:54:20.000  B3

Hash and BranchName are the primary key.

Table Build

BuildID  LastCommitHash                            BranchName
------------------------------------------------------------
1        4191737d919e599690a8b9efd691ffc5165908f9  B1
2        b3052d0c950a731d7221bab8825ba5787a9eb372  B1
3        e54982d42d2b87e35d47536cd2017c18117afc28  B1
4        bf75a42b88782b0dc084a5642cc98876ad3ef41d  B3

LastCommitHash is the Hash of the CommitBranch record used at the time the Build was created. Note that not every Commit hash will appear in the Build table - there will be gaps as the example shows (59503c5e22914b4926e8b5352ef254ebf67b1245 is missing, for example). The only reliable sorting for the CommitBranch table is by HashDate - the hashes themselves are effectively random.

I am trying to write a query to be used in a view called BuildCommit to give me all of the CommitBranch records between the LastCommitHash in the Build table and the Previous Build's LastCommitHash (but not including that build). I'm basically trying to answer the question, what Commits have been made on this branch since the last build.

The query would return the following:

BuildID CommitHash                                  BranchName
------------------------------------------------------------------
1       4191737d919e599690a8b9efd691ffc5165908f9    B1
2       b3052d0c950a731d7221bab8825ba5787a9eb372    B1
2       59503c5e22914b4926e8b5352ef254ebf67b1245    B1
3       e54982d42d2b87e35d47536cd2017c18117afc28    B1
3       d7c008d807d3439539b98dccf4c93ee6bc33405c    B1
4       bf75a42b88782b0dc084a5642cc98876ad3ef41d    B3
...

Edge conditions (like there being only 1 build for a branch and therefore no "since" record) must be dealt with.

Answers to date have been helpful and appreciated, but unfortunately not quite what I needed due to me oversimplifying the original question.

Thanks in advance!

Body:
Try this

declare @minDate Datetime
declare @maxdate Datetime

select @minDate = min(hashDate), @maxdate = max(hashDate)
from table
where hash in (@starthash, @endhash)

select * from table
where hashDate > @minDate and hashDate <= @maxdate


问:
python : convert tuple to generator and free memory
i have a python script that get huge data from database (millions) but it takes a lot of memory and slows the entire server

```<code>#open connection with database
#execute query in database
data = tuple(cursor.fetchall())
def dataGenerator(self, data):
    for i in data:
        yield i
del data
</code>```

i tried to create a generator from the tuple and delete the data to free the memory but it wont work
i also tried using the cursor but i need to close the connection with the database
is there a way to do it please?

答:
Looking at your requirements I think this solution will work best for you. FIrst fetch the data from DB:

```<code>import psycopg2
con = connect(user='root', host = 'localhost', database='pricing_db_new')
cur = con.cursor()
cur.execute('SELECT * from accounts')
</code>```

Now I have the cursor we can write it to a temp file:

```<code>import json
from tempfile import NamedTemporaryFile
tmp = NamedTemporaryFile()
_ = [tmp.write(json.dumps(c) + '\n') for c in cur.fetchall()]
</code>```

This temp file exists as long as it is open and it gets deleted when you close it.

```<code>In [38]: tmp.name
Out[38]: '/tmp/tmpEQsoKt'
</code>```

Now you can read your file line by line and yield result.

```<code>In [77]: tmp.seek(0) # seek to beginning to read again

In [78]: def read_file(file_obj):
    ...:     for row in file_obj.readlines(): # read line by line
    ...:         yield json.loads(row.strip())
    ...:

In [79]: gen = read_file(tmp)

In [80]: gen.next()
Out[80]:
[40507,
 None,
 3,
 107,
 None
]
</code>```

Body:
i have a python script that get huge data from database (millions) but it takes a lot of memory and slows the entire server

#open connection with database
#execute query in database
data = tuple(cursor.fetchall())
def dataGenerator(self, data):
    for i in data:
        yield i
del data

i tried to create a generator from the tuple and delete the data to free the memory but it wont work
i also tried using the cursor but i need to close the connection with the database
is there a way to do it please?

Body:
Looking at your requirements I think this solution will work best for you. FIrst fetch the data from DB:

import psycopg2
con = connect(user='root', host = 'localhost', database='pricing_db_new')
cur = con.cursor()
cur.execute('SELECT * from accounts')

Now I have the cursor we can write it to a temp file:

import json
from tempfile import NamedTemporaryFile
tmp = NamedTemporaryFile()
_ = [tmp.write(json.dumps(c) + '\n') for c in cur.fetchall()]

This temp file exists as long as it is open and it gets deleted when you close it.

In [38]: tmp.name
Out[38]: '/tmp/tmpEQsoKt'

Now you can read your file line by line and yield result.

In [77]: tmp.seek(0) # seek to beginning to read again

In [78]: def read_file(file_obj):
    ...:     for row in file_obj.readlines(): # read line by line
    ...:         yield json.loads(row.strip())
    ...:

In [79]: gen = read_file(tmp)

In [80]: gen.next()
Out[80]:
[40507,
 None,
 3,
 107,
 None
]