问:
React - Check if function returns true but always runs code for false
I bet this has something to do with asynchronicity.

Basically, I am checking if a string (an answer to a question) already exists, and if so, the page should just display a message, otherwise should add the new question to an array.

So in order to refactor the code, I have created a function called isDuplicateAnswer (yes, it's bound to the component). Here is the code for it:

```<code> isDuplicateAnswer() {
    if (this.state.answersToCurrentQuestion.length > 0) {
      this.state.answersToCurrentQuestion.map(answer => {
        if (this.state.answerTextTyped === answer.text) {
          console.log("true"); // executed twice but then adds it to the array (not supposed to)
          return true;
        }
      });
    }
  }
</code>```

Based on this check the code will do the following:

```<code>if (
      event.target.id === "submitAnswer" &&
      this.state.answerTextTyped !== null &&
      this.isDuplicateAnswer()
    ) {
      console.log("Something is wrong"); // This line is never executed (no log, no message)
      return this.props.handleMessage(
        "There is already another answer with this text. Please add a different one."
      );
    } else if (
      event.target.id === "submitAnswer" &&
      this.state.answerTextTyped !== null &&
      !this.isDuplicateAnswer()
    ) {
      console.log("Everything OK"); // not displayed but rest of the code goes through (answer added)
      this.setState({ answerText: this.state.answerTextTyped }, () => {
        (() => {
          let answersToCurrentQuestion = [
            ...this.state.answersToCurrentQuestion,
          ];
          answersToCurrentQuestion.push({
            text: this.state.answerText,
            isCorrect: this.state.isCorrectAnswer,
          });
          this.setState({ answersToCurrentQuestion });
          if (this.state.isCorrectAnswer === true) {
            this.incrementCorrectAnswers();
          }
        })();
        (() => {
          this.props.handleMessage("");
          this.setState({
            isValid: true,
            isCorrectAnswer: false,
            answerTextTyped: null,
          });
          this.refreshAnswerTypedForm();
          this.getAnswerTypedForm();
        })();
      });
    }
</code>```

My problem is that if isDuplicateAnswer is false, as my log says "Everything is Ok", but when it returns true, the answer is created, resulting in an error due to the HTML key being not unique, even though the log from isDuplicateAnswer is displayed twice.

Given that the other two checks in the guard are working correctly, what am I doing wrong here?

EDIT

this is the state right before clicking on "Add Answer", which id is submitAnswer

答:
There are multiple things wrong in your code. I will list the ones that are most obvious to me:

1) Your isDuplicateAnswer() method will always return undefined which under if condition will always evaluate to false. That is why Something is wrong is never executed - it will never go to that block.

2) This one is linked to 1) above. Basically map doesn't return a boolean, moreover you have to return the result of the function which you're not doing as well. To fix this, use a method like some which does return a boolean:

```<code>isDuplicateAnswer() {
       return this.state.answersToCurrentQuestion.some(answer => this.state.answerTextTyped === answer.text);
        // If we find that answer already exists, some will return true, otherwise false.
  }
</code>```

3) In the 2nd block, do not check for event.target.id === "submitAnswer" && this.state.answerTextTyped !== null twice. Just do:

```<code>if (event.target.id === "submitAnswer" && this.state.answerTextTyped !== null) {
    if (isDuplicateAnswer()) {
        console.log("Something is wrong");
        return this.props.handleMessage("There is already another answer with this text. Please add a different one.");
        // No setState call to change anything.
    } else {
        // Call setState and add your answer.
    }

</code>```

Body:
I bet this has something to do with asynchronicity.

Basically, I am checking if a string (an answer to a question) already exists, and if so, the page should just display a message, otherwise should add the new question to an array.

So in order to refactor the code, I have created a function called isDuplicateAnswer (yes, it's bound to the component). Here is the code for it:

 isDuplicateAnswer() {
    if (this.state.answersToCurrentQuestion.length > 0) {
      this.state.answersToCurrentQuestion.map(answer => {
        if (this.state.answerTextTyped === answer.text) {
          console.log("true"); // executed twice but then adds it to the array (not supposed to)
          return true;
        }
      });
    }
  }

Based on this check the code will do the following:

if (
      event.target.id === "submitAnswer" &&
      this.state.answerTextTyped !== null &&
      this.isDuplicateAnswer()
    ) {
      console.log("Something is wrong"); // This line is never executed (no log, no message)
      return this.props.handleMessage(
        "There is already another answer with this text. Please add a different one."
      );
    } else if (
      event.target.id === "submitAnswer" &&
      this.state.answerTextTyped !== null &&
      !this.isDuplicateAnswer()
    ) {
      console.log("Everything OK"); // not displayed but rest of the code goes through (answer added)
      this.setState({ answerText: this.state.answerTextTyped }, () => {
        (() => {
          let answersToCurrentQuestion = [
            ...this.state.answersToCurrentQuestion,
          ];
          answersToCurrentQuestion.push({
            text: this.state.answerText,
            isCorrect: this.state.isCorrectAnswer,
          });
          this.setState({ answersToCurrentQuestion });
          if (this.state.isCorrectAnswer === true) {
            this.incrementCorrectAnswers();
          }
        })();
        (() => {
          this.props.handleMessage("");
          this.setState({
            isValid: true,
            isCorrectAnswer: false,
            answerTextTyped: null,
          });
          this.refreshAnswerTypedForm();
          this.getAnswerTypedForm();
        })();
      });
    }

My problem is that if isDuplicateAnswer is false, as my log says "Everything is Ok", but when it returns true, the answer is created, resulting in an error due to the HTML key being not unique, even though the log from isDuplicateAnswer is displayed twice.

Given that the other two checks in the guard are working correctly, what am I doing wrong here?

EDIT

this is the state right before clicking on "Add Answer", which id is submitAnswer

Body:
There are multiple things wrong in your code. I will list the ones that are most obvious to me:

1) Your isDuplicateAnswer() method will always return undefined which under if condition will always evaluate to false. That is why Something is wrong is never executed - it will never go to that block.

2) This one is linked to 1) above. Basically map doesn't return a boolean, moreover you have to return the result of the function which you're not doing as well. To fix this, use a method like some which does return a boolean:

isDuplicateAnswer() {
       return this.state.answersToCurrentQuestion.some(answer => this.state.answerTextTyped === answer.text);
        // If we find that answer already exists, some will return true, otherwise false.
  }

3) In the 2nd block, do not check for event.target.id === "submitAnswer" && this.state.answerTextTyped !== null twice. Just do:

if (event.target.id === "submitAnswer" && this.state.answerTextTyped !== null) {
    if (isDuplicateAnswer()) {
        console.log("Something is wrong");
        return this.props.handleMessage("There is already another answer with this text. Please add a different one.");
        // No setState call to change anything.
    } else {
        // Call setState and add your answer.
    }


来源: stackexchange

问:
Automatically tick checkbox when clicking on another form input field
I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

```<code><input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>
</code>```

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

答:
    document.querySelector("#box").addEventListener('click',function(){
        document.querySelector("#checkbox").checked = true;
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div>
        <input type="checkbox" id="checkbox">
        <input type="text" id="box">
    </div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

<input type="checkbox" id="box">

  <input type="text">

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

Body:
    document.querySelector("#box").addEventListener('click',function(){
        document.querySelector("#checkbox").checked = true;
    });

    <div>
        <input type="checkbox" id="checkbox">
        <input type="text" id="box">
    </div>


问:
Constructor Event in class Event<T> cannot be applied to given types; cannot find symbol method getTitle()
I am trying to connect my app with the Firebase database but it gives me a Fatal exception error: ( i did not post the rest of the code that I implemented before because it was working perfectly well. Just after the implementation of the code bellow I got an error )

```<code>package com.example.guideme;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.common.api.Status;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.example.guideme.Event;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    EditText locationEditText, titleEditText,descriptionEditText;
    Button publish, inviteFriends;
    TextView tvDate;
    ListView listView;
    private static final String TAG ="MainActivity";
    private DatabaseReference mDatabase;
    private DatePickerDialog.OnDateSetListener mDateSetListener;

    public String title, description, date, location;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //hooks to all elements in activity_main.xml
        locationEditText = findViewById(R.id.locationEditText);
        titleEditText = (EditText) findViewById(R.id.titleEditText);
        descriptionEditText = (EditText) findViewById(R.id.descriptionEditText);
        publish = (Button) findViewById(R.id.publish);
        tvDate = (TextView) findViewById(R.id.tvDate);
        inviteFriends = (Button) findViewById(R.id.inviteFriends);
        listView = (ListView) findViewById(R.id.listView);

        mDatabase = FirebaseDatabase.getInstance().getReference();

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                getAllTasks(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                //Failed to read value
               Log.w("events", "Failed to read value.", error.toException());
            }
        });

                publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                title = titleEditText.getText().toString();
                date = tvDate.getText().toString();
                description = descriptionEditText.getText().toString();
                location = locationEditText.getText().toString();

                String id = title.replaceAll("\\s","");

                writeNewUser(id, title, date, location, description);

                titleEditText.setText("");
                descriptionEditText.setText("");
                tvDate.setText("");
                locationEditText.setText("");

            }
        });

    private void writeNewUser (String eventId, String title, String location, String date, String description){
            Event event = new Event (title, location, date, description);
            mDatabase.child(eventId).setValue(event);
        }

        private void getAllTasks (DataSnapshot dataSnapshot){
        ListView listView = (ListView) findViewById(R.id.listView);
            ArrayList<String> aEvents = new ArrayList<String>();

            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                Event event = singleSnapshot.getValue(Event.class);
                aEvents.add(event.getTitle());
            }

            ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, aEvents);
            listView.setAdapter(arrayAdapter);
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == 100 && resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            locationEditText.setText(place.getAddress());

        }else if (resultCode == AutocompleteActivity.RESULT_ERROR){
            Status status = Autocomplete.getStatusFromIntent(data);
            Toast.makeText(getApplicationContext(),status.getStatusMessage(),Toast.LENGTH_SHORT).show();
        }
    }
    //set the Gmail SDK
    public void open (View view) {
        Intent sendIntent = new Intent ();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(new StringBuilder()
                .append("<body><p>Content</p></body>")
                .toString()));
        sendIntent.setType("text/html");
        startActivity(sendIntent);

    }
}
</code>```

I should have a null object reference (non-existant) that I am trying to convert to string, but I can not see this problem. Thank you.

error:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

答:
You get the following error:

cannot find symbol method getTitle()

Because in this class com.google.firebase.events.Event, there is no getTitle() method. However, in your project, there is an Event class that should be imported. To solve this, simply change the following lines of code:

```<code>import com.google.firebase.events.Event;
</code>```

To:

```<code>import com.example.guideme.Event;
</code>```

Body:
I am trying to connect my app with the Firebase database but it gives me a Fatal exception error: ( i did not post the rest of the code that I implemented before because it was working perfectly well. Just after the implementation of the code bellow I got an error )

package com.example.guideme;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.common.api.Status;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.example.guideme.Event;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    EditText locationEditText, titleEditText,descriptionEditText;
    Button publish, inviteFriends;
    TextView tvDate;
    ListView listView;
    private static final String TAG ="MainActivity";
    private DatabaseReference mDatabase;
    private DatePickerDialog.OnDateSetListener mDateSetListener;

    public String title, description, date, location;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //hooks to all elements in activity_main.xml
        locationEditText = findViewById(R.id.locationEditText);
        titleEditText = (EditText) findViewById(R.id.titleEditText);
        descriptionEditText = (EditText) findViewById(R.id.descriptionEditText);
        publish = (Button) findViewById(R.id.publish);
        tvDate = (TextView) findViewById(R.id.tvDate);
        inviteFriends = (Button) findViewById(R.id.inviteFriends);
        listView = (ListView) findViewById(R.id.listView);

        mDatabase = FirebaseDatabase.getInstance().getReference();

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                getAllTasks(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                //Failed to read value
               Log.w("events", "Failed to read value.", error.toException());
            }
        });

                publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                title = titleEditText.getText().toString();
                date = tvDate.getText().toString();
                description = descriptionEditText.getText().toString();
                location = locationEditText.getText().toString();

                String id = title.replaceAll("\\s","");

                writeNewUser(id, title, date, location, description);

                titleEditText.setText("");
                descriptionEditText.setText("");
                tvDate.setText("");
                locationEditText.setText("");

            }
        });

    private void writeNewUser (String eventId, String title, String location, String date, String description){
            Event event = new Event (title, location, date, description);
            mDatabase.child(eventId).setValue(event);
        }

        private void getAllTasks (DataSnapshot dataSnapshot){
        ListView listView = (ListView) findViewById(R.id.listView);
            ArrayList<String> aEvents = new ArrayList<String>();

            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                Event event = singleSnapshot.getValue(Event.class);
                aEvents.add(event.getTitle());
            }

            ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, aEvents);
            listView.setAdapter(arrayAdapter);
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == 100 && resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            locationEditText.setText(place.getAddress());

        }else if (resultCode == AutocompleteActivity.RESULT_ERROR){
            Status status = Autocomplete.getStatusFromIntent(data);
            Toast.makeText(getApplicationContext(),status.getStatusMessage(),Toast.LENGTH_SHORT).show();
        }
    }
    //set the Gmail SDK
    public void open (View view) {
        Intent sendIntent = new Intent ();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(new StringBuilder()
                .append("
Content
")
                .toString()));
        sendIntent.setType("text/html");
        startActivity(sendIntent);

    }
}

I should have a null object reference (non-existant) that I am trying to convert to string, but I can not see this problem. Thank you.

error:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

Body:
You get the following error:

cannot find symbol method getTitle()

Because in this class com.google.firebase.events.Event, there is no getTitle() method. However, in your project, there is an Event class that should be imported. To solve this, simply change the following lines of code:

import com.google.firebase.events.Event;

To:

import com.example.guideme.Event;


问:
Check the repeated words in a string and keep a count in javascript
I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive"; ```
</div>
</div>
</p>

<p>I am looking for output like this <strong>I = 3</strong>, <strong>am = 2</strong>, <strong>not = 1</strong> and so on, also is it possible to find the individual letter as <strong>I = 3</strong>, <strong>a = 6</strong>, <strong>m = 2</strong>. </p>

<p>I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)</code>```

答:
How to count the number of times each word appears in a string:

strip punctuation from the string with .replace()

change all character to lowercase with .toLowerCase()

convert string into array of words with .split()

loop through each word (.forEach), adding it to a word count object

const result = document.getElementById('result');

let str = "I am not gonna live forever, but I wanna live while I am alive.";

// strip all punctuation from string
let strStripped = str.replace(/[,.!]/g, '');
result.innerHTML = `strStripped: "${strStripped}"\n`;

// separate string into array of lowercase words
let words = strStripped.toLowerCase().split(' ');
result.innerHTML += 'words: ' + JSON.stringify(words, null, 2);

// form object of word counts
let wordCounts = {};
words.forEach(word => {
  wordCounts[word] = (wordCounts[word] || 0) + 1;
});
result.innerHTML += '\nwordCounts: ' +
  JSON.stringify(wordCounts, null, 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="result">``````

Body:
I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive";

I am looking for output like this I = 3, am = 2, not = 1 and so on, also is it possible to find the individual letter as I = 3, a = 6, m = 2.

I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here

let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)

Body:
How to count the number of times each word appears in a string:

strip punctuation from the string with .replace()

change all character to lowercase with .toLowerCase()

convert string into array of words with .split()

loop through each word (.forEach), adding it to a word count object

const result = document.getElementById('result');

let str = "I am not gonna live forever, but I wanna live while I am alive.";

// strip all punctuation from string
let strStripped = str.replace(/[,.!]/g, '');
result.innerHTML = `strStripped: "${strStripped}"\n`;

// separate string into array of lowercase words
let words = strStripped.toLowerCase().split(' ');
result.innerHTML += 'words: ' + JSON.stringify(words, null, 2);

// form object of word counts
let wordCounts = {};
words.forEach(word => {
  wordCounts[word] = (wordCounts[word] || 0) + 1;
});
result.innerHTML += '\nwordCounts: ' +
  JSON.stringify(wordCounts, null, 2);

<pre id="result"></pre>


问:
Securing PHP MySQL code
I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.

Here is my code:

```<code><?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
    $query=$database->real_escape_string($_POST['query']);
    if(strlen($query)>0){
        $suggestions=$database->query(
            "SELECT * FROM search WHERE name LIKE '%" . $query .
             "%' ORDER BY value DESC LIMIT 5");
        if($suggestions){
            while($result=$suggestions->fetch_object()){
                 echo '<a>'.$result->name.'</a>';
            }
        }
    }
}
?>
</code>```

答:
Actually there aren't, considering you are escaping the only external value in the SQL

Anyway I suggest you to use PDO::prepare for queries. Go here for further infos

http://it.php.net/manual/en/pdo.prepare.php

Example:

```<code>$sth = $dbh->prepare('SELECT * FROM article WHERE id = ?');
$sth->execute(array(1));
$red = $sth->fetchAll();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Securing PHP MySQL code

Body:
I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.

Here is my code:

<?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
    $query=$database->real_escape_string($_POST['query']);
    if(strlen($query)>0){
        $suggestions=$database->query(
            "SELECT * FROM search WHERE name LIKE '%" . $query .
             "%' ORDER BY value DESC LIMIT 5");
        if($suggestions){
            while($result=$suggestions->fetch_object()){
                 echo ''.$result->name.'';
            }
        }
    }
}
?>

Body:
Actually there aren't, considering you are escaping the only external value in the SQL

Anyway I suggest you to use PDO::prepare for queries. Go here for further infos

http://it.php.net/manual/en/pdo.prepare.php

Example:

$sth = $dbh->prepare('SELECT * FROM article WHERE id = ?');
$sth->execute(array(1));
$red = $sth->fetchAll();


问:
Kotlin multiplatform cannot resolved references while gradle sync succeeds
When I compile my kotlin multiplatform project I get Unresolved reference on stuffs that I use in the common module. But the gradle synchronisation works fine. You can found my project here

In details:

I followed the tutorial from Jetbrain to build a mobile multiplatform project. Everything works fine.

Then I implemented inside the common module a ktor client to request an api (jsonplaceholder). I added all the required dependencies and everything seems good. All references are resolved, I have no errors.

But when I compile my project with make Project then all the dependencies added to get ktor and so on cannot be resolved.

I guess I have a problem with the configuration of my project, when I run ./gradlew androidDependencies it seems that there is a problem with SharedCode since it is sometimes marked in the command´s output as \--- :SharedCode.

The build.gradle for the project is:

```<code>buildscript {
    ext.kotlin_version = '1.3.71'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0-rc01'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

The build.gradle.kts for the common SharedCode module is:

import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget

plugins {
    kotlin("multiplatform")
    kotlin("plugin.serialization")
}

kotlin {
    //select iOS target platform depending on the Xcode environment variables
    val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
    if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
    ::iosArm64
    else
    ::iosX64

    iOSTarget("ios") {
        binaries {
            framework {
                baseName = "SharedCode"
            }
        }
    }

    jvm("android")

    val serializationVersion = "0.20.0"
    val ktorVersion = "1.3.2"

    sourceSets["commonMain"].dependencies {
        implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
        implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serializationVersion")
        implementation("io.ktor:ktor-client-core:$ktorVersion")
        implementation("io.ktor:ktor-client-json:$ktorVersion")
        implementation("io.ktor:ktor-client-serialization:$ktorVersion")//Kotlinxserializer
    }

    sourceSets["androidMain"].dependencies {
        implementation("org.jetbrains.kotlin:kotlin-stdlib")
    }
}

val packForXcode by tasks.creating(Sync::class) {
    val targetDir = File(buildDir, "xcode-frameworks")

    /// selecting the right configuration for the iOS
    /// framework depending on the environment
    /// variables set by Xcode build
    val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
    val framework = kotlin.targets
            .getByName<KotlinNativeTarget>("ios")
            .binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn(framework.linkTask)

    from({ framework.outputDirectory })
    into(targetDir)

    /// generate a helpful ./gradlew wrapper with embedded Java path
    doLast {
        val gradlew = File(targetDir, "gradlew")
        gradlew.writeText("#!/bin/bash\n"
                + "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
                + "cd '${rootProject.rootDir}'\n"
                + "./gradlew \$@\n")
        gradlew.setExecutable(true)
    }
}

tasks.getByName("build").dependsOn(packForXcode)
```

<p>And the <code>build.gradle</code> for the android app is:</p>

```apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.mpp.mpptest"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation project(':SharedCode')
}
```

Do you know what I am doing wrong?

I read Building Multiplatform Projects with Gradle but it did not help.

The only working project that I found is from KaMPKit. I have set my build.gradle(.kts) files as they are in KaMPKit (see the branch Set_build_gradle_as_KaMPKit) but the `unresolved references´ problem remains.

答:
I fixed my problem. The error came because I did not declare the plugin android.lybrary.

Even if it is not necessary to fix the problem, I have decided to switch my build.gradle files to kotlin DLS, I rewrote all the build.gradle and I made the following changes for the shared module:

I created a AndroidManifest.xml

I added the com.android.library plugins

I added a block android

At the end the build.gradle.kts for the shared module looks like this:

import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget

plugins {
    kotlin("multiplatform")
    kotlin("plugin.serialization")
    id("kotlinx-serialization")
    id("com.android.library")
}

android {
    compileSdkVersion(29)
    defaultConfig {
        minSdkVersion(Versions.min_sdk)
        targetSdkVersion(Versions.target_sdk)
        versionCode = 1
        versionName = "1.0"
        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }
}

kotlin {
    //select iOS target platform depending on the Xcode environment variables
    val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
    if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
    ::iosArm64
    else
    ::iosX64

    iOSTarget("ios") {
        binaries {
            framework {
                baseName = "SharedCode"
            }
        }
    }

    jvm("android")

    sourceSets["commonMain"].dependencies {
        implementation(kotlin("stdlib-common", Versions.kotlin))
        implementation(Deps.Ktor.commonCore)
        implementation(Deps.Ktor.commonJson)
        implementation(Deps.Coroutines.common)
        implementation(Deps.Ktor.commonSerialization)
    }

    sourceSets["androidMain"].dependencies {
        implementation(kotlin("stdlib", Versions.kotlin))
        implementation(Deps.Coroutines.jdk)
        implementation(Deps.Ktor.androidSerialization)
    }

    sourceSets["iosMain"].dependencies {
        implementation(Deps.Ktor.iosSerialization)
    }
}

val packForXcode by tasks.creating(Sync::class) {
    val targetDir = File(buildDir, "xcode-frameworks")

    /// selecting the right configuration for the iOS
    /// framework depending on the environment
    /// variables set by Xcode build
    val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
    val framework = kotlin.targets
            .getByName<KotlinNativeTarget>("ios")
            .binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn(framework.linkTask)

    from({ framework.outputDirectory })
    into(targetDir)

    /// generate a helpful ./gradlew wrapper with embedded Java path
    doLast {
        val gradlew = File(targetDir, "gradlew")
        gradlew.writeText("#!/bin/bash\n"
                + "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
                + "cd '${rootProject.rootDir}'\n"
                + "./gradlew \$@\n")
        gradlew.setExecutable(true)
    }
}

tasks.getByName("build").dependsOn(packForXcode)
```

All dependency version numbers come from a Dependencies.kt files (see KaMPKit)

All dependencies are now resolved.

Body:
When I compile my kotlin multiplatform project I get Unresolved reference on stuffs that I use in the common module. But the gradle synchronisation works fine. You can found my project here

In details:

I followed the tutorial from Jetbrain to build a mobile multiplatform project. Everything works fine.

Then I implemented inside the common module a ktor client to request an api (jsonplaceholder). I added all the required dependencies and everything seems good. All references are resolved, I have no errors.

But when I compile my project with make Project then all the dependencies added to get ktor and so on cannot be resolved.

I guess I have a problem with the configuration of my project, when I run ./gradlew androidDependencies it seems that there is a problem with SharedCode since it is sometimes marked in the command´s output as \--- :SharedCode.

The build.gradle for the project is:

buildscript {
    ext.kotlin_version = '1.3.71'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0-rc01'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The build.gradle.kts for the common SharedCode module is:

import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget

plugins {
    kotlin("multiplatform")
    kotlin("plugin.serialization")
}

kotlin {
    //select iOS target platform depending on the Xcode environment variables
    val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
    if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
    ::iosArm64
    else
    ::iosX64

    iOSTarget("ios") {
        binaries {
            framework {
                baseName = "SharedCode"
            }
        }
    }

    jvm("android")

    val serializationVersion = "0.20.0"
    val ktorVersion = "1.3.2"

    sourceSets["commonMain"].dependencies {
        implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
        implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serializationVersion")
        implementation("io.ktor:ktor-client-core:$ktorVersion")
        implementation("io.ktor:ktor-client-json:$ktorVersion")
        implementation("io.ktor:ktor-client-serialization:$ktorVersion")//Kotlinxserializer
    }

    sourceSets["androidMain"].dependencies {
        implementation("org.jetbrains.kotlin:kotlin-stdlib")
    }
}

val packForXcode by tasks.creating(Sync::class) {
    val targetDir = File(buildDir, "xcode-frameworks")

    /// selecting the right configuration for the iOS
    /// framework depending on the environment
    /// variables set by Xcode build
    val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
    val framework = kotlin.targets
            .getByName<KotlinNativeTarget>("ios")
            .binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn(framework.linkTask)

    from({ framework.outputDirectory })
    into(targetDir)

    /// generate a helpful ./gradlew wrapper with embedded Java path
    doLast {
        val gradlew = File(targetDir, "gradlew")
        gradlew.writeText("#!/bin/bash\n"
                + "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
                + "cd '${rootProject.rootDir}'\n"
                + "./gradlew \$@\n")
        gradlew.setExecutable(true)
    }
}

tasks.getByName("build").dependsOn(packForXcode)

And the build.gradle for the android app is:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.mpp.mpptest"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation project(':SharedCode')
}

Do you know what I am doing wrong?

I read Building Multiplatform Projects with Gradle but it did not help.

The only working project that I found is from KaMPKit. I have set my build.gradle(.kts) files as they are in KaMPKit (see the branch Set_build_gradle_as_KaMPKit) but the `unresolved references´ problem remains.

Body:
I fixed my problem. The error came because I did not declare the plugin android.lybrary.

Even if it is not necessary to fix the problem, I have decided to switch my build.gradle files to kotlin DLS, I rewrote all the build.gradle and I made the following changes for the shared module:

I created a AndroidManifest.xml

I added the com.android.library plugins

I added a block android

At the end the build.gradle.kts for the shared module looks like this:

import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget

plugins {
    kotlin("multiplatform")
    kotlin("plugin.serialization")
    id("kotlinx-serialization")
    id("com.android.library")
}

android {
    compileSdkVersion(29)
    defaultConfig {
        minSdkVersion(Versions.min_sdk)
        targetSdkVersion(Versions.target_sdk)
        versionCode = 1
        versionName = "1.0"
        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }
}

kotlin {
    //select iOS target platform depending on the Xcode environment variables
    val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
    if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
    ::iosArm64
    else
    ::iosX64

    iOSTarget("ios") {
        binaries {
            framework {
                baseName = "SharedCode"
            }
        }
    }

    jvm("android")

    sourceSets["commonMain"].dependencies {
        implementation(kotlin("stdlib-common", Versions.kotlin))
        implementation(Deps.Ktor.commonCore)
        implementation(Deps.Ktor.commonJson)
        implementation(Deps.Coroutines.common)
        implementation(Deps.Ktor.commonSerialization)
    }

    sourceSets["androidMain"].dependencies {
        implementation(kotlin("stdlib", Versions.kotlin))
        implementation(Deps.Coroutines.jdk)
        implementation(Deps.Ktor.androidSerialization)
    }

    sourceSets["iosMain"].dependencies {
        implementation(Deps.Ktor.iosSerialization)
    }
}

val packForXcode by tasks.creating(Sync::class) {
    val targetDir = File(buildDir, "xcode-frameworks")

    /// selecting the right configuration for the iOS
    /// framework depending on the environment
    /// variables set by Xcode build
    val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
    val framework = kotlin.targets
            .getByName<KotlinNativeTarget>("ios")
            .binaries.getFramework(mode)
    inputs.property("mode", mode)
    dependsOn(framework.linkTask)

    from({ framework.outputDirectory })
    into(targetDir)

    /// generate a helpful ./gradlew wrapper with embedded Java path
    doLast {
        val gradlew = File(targetDir, "gradlew")
        gradlew.writeText("#!/bin/bash\n"
                + "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
                + "cd '${rootProject.rootDir}'\n"
                + "./gradlew \$@\n")
        gradlew.setExecutable(true)
    }
}

tasks.getByName("build").dependsOn(packForXcode)

All dependency version numbers come from a Dependencies.kt files (see KaMPKit)

All dependencies are now resolved.


问:
How do I build docker-compose container from source for x86_64 and an arm arch? (Please provide a source image with `from` prior to commit)
I am trying to build the docker-compose container from source. Ultimately I want two of these containers, one for x86_64 and one for an arm arch. I see that I can get the x86 compatible container with this script https://github.com/docker/compose/releases/download/1.25.5/run.sh, but I need to be able to build from source. I have cloned the compose repository and have tried two things, first just trying to build with the Dockerfile in the repo. The result:

```<code>>docker build -t docker-compose .
Sending build context to Docker daemon 1.872 MB
Step 1/39 : ARG DOCKER_VERSION=19.03.8
Please provide a source image with `from` prior to commit
</code>```

I was then looking at the build scripts in script/build and tried executing the linux build script.

```<code>> script/build/linux
+ ./script/clean
++ script/build/write-git-sha
+ DOCKER_COMPOSE_GITSHA=9c5351cf
+ TAG=docker/compose:tmp-glibc-linux-binary-9c5351cf
+ docker build -t docker/compose:tmp-glibc-linux-binary-9c5351cf . --build-arg BUILD_PLATFORM=debian --build-arg GIT_COMMIT=9c5351cf
Sending build context to Docker daemon 1.872 MB
Step 1/39 : ARG DOCKER_VERSION=19.03.8
Please provide a source image with `from` prior to commit
</code>```

I'm stuck here. My plan for the arm container is to use the linux build script but swap the ARCH to my arm architecture. Any help would be appreciated

答: I will answer this question if anyone happens upon it, because I have solve it. The issue was with my docker-version. You need an up to date docker version, and then clone the docker-compose repo and do docker build like shown above. To build an ARM version I had to make an ARM emulator with Qemu and do the same steps there.</p>

Body:
I am trying to build the docker-compose container from source. Ultimately I want two of these containers, one for x86_64 and one for an arm arch. I see that I can get the x86 compatible container with this script https://github.com/docker/compose/releases/download/1.25.5/run.sh, but I need to be able to build from source. I have cloned the compose repository and have tried two things, first just trying to build with the Dockerfile in the repo. The result:

>docker build -t docker-compose .
Sending build context to Docker daemon 1.872 MB
Step 1/39 : ARG DOCKER_VERSION=19.03.8
Please provide a source image with `from` prior to commit

I was then looking at the build scripts in script/build and tried executing the linux build script.

> script/build/linux
+ ./script/clean
++ script/build/write-git-sha
+ DOCKER_COMPOSE_GITSHA=9c5351cf
+ TAG=docker/compose:tmp-glibc-linux-binary-9c5351cf
+ docker build -t docker/compose:tmp-glibc-linux-binary-9c5351cf . --build-arg BUILD_PLATFORM=debian --build-arg GIT_COMMIT=9c5351cf
Sending build context to Docker daemon 1.872 MB
Step 1/39 : ARG DOCKER_VERSION=19.03.8
Please provide a source image with `from` prior to commit

I'm stuck here. My plan for the arm container is to use the linux build script but swap the ARCH to my arm architecture. Any help would be appreciated


问:
Using xpath in rvest to scrape content between two h5 headings?
I'm in the process of extracting content from local html files by using rvest. I would like to extract a certain segment of content between two h5 headings, the only 'specifying' detail being the textual title of the initial h5 heading. The problem is, that the documents vary in their headings – both the IDs and the textual content are subject to many variations – the only exception being the textual title ”Details” I’m interested in. Please see an example of the document structure:

```<code><div id=”document”>
<h3>Title of the document</h3>
<h4 id=”id11111”>Focus of the document</h4>
<p>This document focuses on…</p>
<p>And also…</p>
<h5 id=”id22222”> 1. Introduction </h5>
<p>Text here.</p>
<h6 id=”33333”> 1.1 Preliminary introduction </h6>
<p> Text here. </p>
<h5 id=”id44444”> 2. Details </h5>
<p>Text here.</p>
<h6 id=”id55555”> 2.1 Details about A </h6>
<p> Text here. </p>
<h6 id=”id66666”> 2.2 Details about B </h6>
<p> Text here. </p>
<h5 id=”id77777”> 3. Timeline </h5>
<p>Text here.</p>
<h6 id=”id88888”> 3.1 Timeline A </h5>
<p>Text here.</p>
</div>
</code>```

From the preceding example, I'd like to extract only, and only, the content from h5 tag with id44444, textual title "2. Details" until the next h5 heading (h5 id 77777, 3, Timeline).

I've managed to pinpoint my scraping to begin from the wished h5 tag (see example below) by using contains and following-sibling::* but it returns all siblings until the end of the document, whereas my goal is to stop the return to the following h5 heading.

I haven’t figured out how to use ”preceding-sibling”, because the following h5 tag does not have a standard id, xpath or textual content and the order of the headings is not standard. The h5 headings can appear with a varying order.

```<code>#loading rvest
library('rvest')

files <- list.files(”C:/htmldocuments”)

#performing the scrape
scraping <- sapply(files, function (x)
read_html(x, encoding = "utf-8") %>%
html_nodes(xpath = '//h5[contains(., ”Details”)]/following-sibling::*') %>%
html_text())
</code>```

This returns results which begin at the correct place, but how can it be stopped to the first following h5 tag after the h5 tag of "Details"? The id and title of the following h5 tag vary and thus is unknown.

I've reviewed multiple similar questions – the answers often point to using preceding-sibling – however I can't seem to figure out how to use it, as I have no way of knowing what the following h5 is.

答:
You can use the following XPath expression :

```<code>//p[preceding::*[1][contains(.,"Details")]]
</code>```

This will select all p elements which are preceded by a heading element which contains the word "Details".

Output : 3 nodes

If you need to keep the headings, you can use :

```<code>//*[preceding::*[1][contains(.,"Details")] or contains(text(),"Details")]
</code>```

Output : 6 nodes

Body:
I'm in the process of extracting content from local html files by using rvest. I would like to extract a certain segment of content between two h5 headings, the only 'specifying' detail being the textual title of the initial h5 heading. The problem is, that the documents vary in their headings – both the IDs and the textual content are subject to many variations – the only exception being the textual title ”Details” I’m interested in. Please see an example of the document structure:

Title of the document

Focus of the document

This document focuses on…

And also…

 1. Introduction

Text here.

 1.1 Preliminary introduction

 Text here.

 2. Details

Text here.

 2.1 Details about A

 Text here.

 2.2 Details about B

 Text here.

 3. Timeline

Text here.

 3.1 Timeline A

Text here.

From the preceding example, I'd like to extract only, and only, the content from h5 tag with id44444, textual title "2. Details" until the next h5 heading (h5 id 77777, 3, Timeline).

I've managed to pinpoint my scraping to begin from the wished h5 tag (see example below) by using contains and following-sibling::* but it returns all siblings until the end of the document, whereas my goal is to stop the return to the following h5 heading.

I haven’t figured out how to use ”preceding-sibling”, because the following h5 tag does not have a standard id, xpath or textual content and the order of the headings is not standard. The h5 headings can appear with a varying order.

#loading rvest
library('rvest')

files <- list.files(”C:/htmldocuments”)

#performing the scrape
scraping <- sapply(files, function (x)
read_html(x, encoding = "utf-8") %>%
html_nodes(xpath = '//h5[contains(., ”Details”)]/following-sibling::*') %>%
html_text())

This returns results which begin at the correct place, but how can it be stopped to the first following h5 tag after the h5 tag of "Details"? The id and title of the following h5 tag vary and thus is unknown.

I've reviewed multiple similar questions – the answers often point to using preceding-sibling – however I can't seem to figure out how to use it, as I have no way of knowing what the following h5 is.

Body:
You can use the following XPath expression :

//p[preceding::*[1][contains(.,"Details")]]

This will select all p elements which are preceded by a heading element which contains the word "Details".

Output : 3 nodes

If you need to keep the headings, you can use :

//*[preceding::*[1][contains(.,"Details")] or contains(text(),"Details")]

Output : 6 nodes


问:
Shell Scripts hangs when running through ProcessBuilder
I have a Java program where I am triggering a shell scripts.
Java Code Sample is :

```<code> ProcessBuilder pb = new ProcessBuilder(cmdList);
        p = pb.start();
        p.waitFor();
</code>```

Where cmdList contains all required necessary input argument to execute the shell. This shell script is having a for loop inside and executing some DB scripts in that loop and printing result info & error logs in a file.

Below is sample shell script code :

```<code>#!/bin/bash
</code>```

export PATH=/apps/PostgresPlus/as9.6/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

set -eE

#################################################### START

TIME_ELAPSED=""
TIME_ELAPSED_IN_HOURS=""
SCRIPT_START_TIME_FORMATTED=date '+%F %T'
SCRIPT_START_TIME_IN_SEC=date +%s

PROCESS_LOG_BASE_PATH="/data/logs/purge_log/"
PROCESS_LOG="$PROCESS_LOG_BASE_PATH/purge.log"

trap 'err=$?; logError 2>&1 "Error occurred during purging. Exiting with status $err at line $LINENO: ${BASH_COMMAND}. Please check logs for more info." >>$PROCESS_LOG' ERR
trap 'logError 2>&1 "Error occurred during purging. Exiting shell script execution as an external interrupt was received. Please check logs for more info." >>$PROCESS_LOG; trap ERR' INT

banner()
{
  echo "+------------------------------------------------------------------------------------------------+"
  printf "|tput bold[ %-40s tput sgr0|\n" "$1 ] tput setaf 2 $2"
  echo "+------------------------------------------------------------------------------------------------+"
}

logError()
{
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"] tput setaf 1 tput bold [ERROR] tput setaf 1 %-40s tput sgr0\n" "$@"
}

logInfo(){
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"]  tput setaf 6 bold [INFO] %-40s tput sgr0\n" "$@"
}
logWarn(){
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"]  tput setaf 3 tput bold [WARNING] %-40s tput sgr0\n" "$@"
}

logHint(){
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"]  tput setaf 5 tput sitm %-40s tput sgr0\n" "$@"
}

main()
{

    banner "$SCRIPT_START_TIME_FORMATTED"  "Started processing" | tee -a $PROCESS_LOG
    logInfo "Started execution at $SCRIPT_START_TIME_FORMATTED" | tee -a $PROCESS_LOG

```<code>set PGPASSWORD=$DB_PASSWORD
export PGPASSWORD=$DB_PASSWORD

# Call DB function for audit and category wise data purging, population of schema names
SCHEMA_NAMES_RESULT=$(psql -h $HOST_NAME -d $DB_NAME -U $DB_USER -p $DB_PORT -At -c "SELECT $COMMON_SCHEMA_NAME.purge_audit_and_populate_schema_names('$COMMON_SCHEMA_NAME', $PURGE_DATA_INTERVAL_IN_DAYS,'$SCHEMA_NAMES',$NUM_TOP_CONTRIBUTING_TENANTS)")

SCHEMA_NAMES_RESULT=$(echo "$SCHEMA_NAMES_RESULT" | sed 's/{//g; s/}//g; s/"//g' )

SCHEMA_NAMES=$(echo $SCHEMA_NAMES_RESULT | rev | cut -d"," -f2-  | rev)

#Convert comma separated string of tenants to array
SCHEMA_NAMES=($(echo "$SCHEMA_NAMES" | tr ',' '\n'))

# loop for multi schema
for element in "${SCHEMA_NAMES[@]}"
do
    logInfo "Effective tenant - $element, Script start time - $SCRIPT_START_TIME_FORMATTED" | tee -a $PROCESS_LOG

    # PGSQL call to DB function to execute purging

    logInfo "Time elapsed since script execution started - $TIME_ELAPSED" | tee -a $PROCESS_LOG
done

#logInfo "Purge completed!" | tee -a $PROCESS_LOG
logInfo "Purge execution completed successfully at `date '+%F %T'`" | tee -a $PROCESS_LOG
exit 0
</code>```

}

mkdir -p $PROCESS_LOG_BASE_PATH
main "$@"

#################################################### END

Following is my observation with this program.

When running shell script directly on putty it executes properly without any error.

When triggering shell script through above java program the following behavior I observed.

a. It hangs after a certain iteration in for loop.

b. As I reduce the number of logs entries from shell scripts, iteration (for loop) numbers keeps on increasing.

c. When I removed all info logs and keeps on printing only error log then it completed successfully.

Can someone please help in identifying the reason behind this behavior.

For now, I put check on the number of iteration in for loop but that problem can occur any time when I will start receiving multiple error log.

Regards

Kushagra

答:
You have to consume the process streams or map err and out to file so the native buffers don't fill up.  It works better if you create threads to consume each stream.  The hacky single thread version is something like this:

```<code>ProcessBuilder pb = new ProcessBuilder(cmdList);
p = pb.start();
try (InputStream in = p.getInputStream();
            InputStream err = p.getErrorStream();
            OutputStream closeOnly = p.getOutputStream()) {
    while (p.isAlive()) {
        long skipped = 0L;
        try {
            skipped = in.skip(in.available())
                     + err.skip(err.available());
        } catch (IOException jdk8155808) {
           byte[] b = new byte[2048];
           int read = in.read(b, 0, Math.min(b.length, in.available());
           if (read > 0) {
               skipped += read;
           }

           read = err.read(b, 0, Math.min(b.length, err.available());
           if (read > 0) {
               skipped += read;
           }
        }

        if(skipped == 0L) {
           p.waitFor(5L, TimeUnit.MILLISECONDS);
        }
    }
} finally {
   p.destroy();
}
</code>```

The thread way works like this:

```<code>public void foo() {
    class DevNull implements Runnable {

        private final InputStream is;
        DevNull(final InputStream is) {
            is = Objects.requireNonNull(is);
        }

        public void run() {
            byte[] b = new byte[64];
            try {
                while (is.read(b) >= 0);
            } catch(IOException ignore) {
            }
        }
    }

    ExecutorService e = Executors.newCachedThreadPool();
    ProcessBuilder pb = new ProcessBuilder(cmdList);
    Process p = pb.start();
    try (InputStream in = p.getInputStream();
            InputStream err = p.getErrorStream();
            OutputStream closeOnly = p.getOutputStream()) {
        e.execute(new DevNull(in));
        e.execute(new DevNull(err));
        p.waitFor();
    } finally {
        p.destroy();
        e.shutdown();
    }
}
</code>```

Body:
I have a Java program where I am triggering a shell scripts.
Java Code Sample is :

 ProcessBuilder pb = new ProcessBuilder(cmdList);
        p = pb.start();
        p.waitFor();

Where cmdList contains all required necessary input argument to execute the shell. This shell script is having a for loop inside and executing some DB scripts in that loop and printing result info & error logs in a file.

Below is sample shell script code :

#!/bin/bash

export PATH=/apps/PostgresPlus/as9.6/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

set -eE

#################################################### START

TIME_ELAPSED=""
TIME_ELAPSED_IN_HOURS=""
SCRIPT_START_TIME_FORMATTED=date '+%F %T'
SCRIPT_START_TIME_IN_SEC=date +%s

PROCESS_LOG_BASE_PATH="/data/logs/purge_log/"
PROCESS_LOG="$PROCESS_LOG_BASE_PATH/purge.log"

trap 'err=$?; logError 2>&1 "Error occurred during purging. Exiting with status $err at line $LINENO: ${BASH_COMMAND}. Please check logs for more info." >>$PROCESS_LOG' ERR
trap 'logError 2>&1 "Error occurred during purging. Exiting shell script execution as an external interrupt was received. Please check logs for more info." >>$PROCESS_LOG; trap ERR' INT

banner()
{
  echo "+------------------------------------------------------------------------------------------------+"
  printf "|tput bold[ %-40s tput sgr0|\n" "$1 ] tput setaf 2 $2"
  echo "+------------------------------------------------------------------------------------------------+"
}

logError()
{
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"] tput setaf 1 tput bold [ERROR] tput setaf 1 %-40s tput sgr0\n" "$@"
}

logInfo(){
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"]  tput setaf 6 bold [INFO] %-40s tput sgr0\n" "$@"
}
logWarn(){
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"]  tput setaf 3 tput bold [WARNING] %-40s tput sgr0\n" "$@"
}

logHint(){
    printf "[ProcessId- $$] [date "+%Y-%m-%d %H:%M:%S"]  tput setaf 5 tput sitm %-40s tput sgr0\n" "$@"
}

main()
{

    banner "$SCRIPT_START_TIME_FORMATTED"  "Started processing" | tee -a $PROCESS_LOG
    logInfo "Started execution at $SCRIPT_START_TIME_FORMATTED" | tee -a $PROCESS_LOG

set PGPASSWORD=$DB_PASSWORD
export PGPASSWORD=$DB_PASSWORD

# Call DB function for audit and category wise data purging, population of schema names
SCHEMA_NAMES_RESULT=$(psql -h $HOST_NAME -d $DB_NAME -U $DB_USER -p $DB_PORT -At -c "SELECT $COMMON_SCHEMA_NAME.purge_audit_and_populate_schema_names('$COMMON_SCHEMA_NAME', $PURGE_DATA_INTERVAL_IN_DAYS,'$SCHEMA_NAMES',$NUM_TOP_CONTRIBUTING_TENANTS)")

SCHEMA_NAMES_RESULT=$(echo "$SCHEMA_NAMES_RESULT" | sed 's/{//g; s/}//g; s/"//g' )

SCHEMA_NAMES=$(echo $SCHEMA_NAMES_RESULT | rev | cut -d"," -f2-  | rev)

#Convert comma separated string of tenants to array
SCHEMA_NAMES=($(echo "$SCHEMA_NAMES" | tr ',' '\n'))

# loop for multi schema
for element in "${SCHEMA_NAMES[@]}"
do
    logInfo "Effective tenant - $element, Script start time - $SCRIPT_START_TIME_FORMATTED" | tee -a $PROCESS_LOG

    # PGSQL call to DB function to execute purging

    logInfo "Time elapsed since script execution started - $TIME_ELAPSED" | tee -a $PROCESS_LOG
done

#logInfo "Purge completed!" | tee -a $PROCESS_LOG
logInfo "Purge execution completed successfully at `date '+%F %T'`" | tee -a $PROCESS_LOG
exit 0

}

mkdir -p $PROCESS_LOG_BASE_PATH
main "$@"

#################################################### END

Following is my observation with this program.

When running shell script directly on putty it executes properly without any error.

When triggering shell script through above java program the following behavior I observed.

a. It hangs after a certain iteration in for loop.

b. As I reduce the number of logs entries from shell scripts, iteration (for loop) numbers keeps on increasing.

c. When I removed all info logs and keeps on printing only error log then it completed successfully.

Can someone please help in identifying the reason behind this behavior.

For now, I put check on the number of iteration in for loop but that problem can occur any time when I will start receiving multiple error log.

Regards

Kushagra

Body:
You have to consume the process streams or map err and out to file so the native buffers don't fill up.  It works better if you create threads to consume each stream.  The hacky single thread version is something like this:

ProcessBuilder pb = new ProcessBuilder(cmdList);
p = pb.start();
try (InputStream in = p.getInputStream();
            InputStream err = p.getErrorStream();
            OutputStream closeOnly = p.getOutputStream()) {
    while (p.isAlive()) {
        long skipped = 0L;
        try {
            skipped = in.skip(in.available())
                     + err.skip(err.available());
        } catch (IOException jdk8155808) {
           byte[] b = new byte[2048];
           int read = in.read(b, 0, Math.min(b.length, in.available());
           if (read > 0) {
               skipped += read;
           }

           read = err.read(b, 0, Math.min(b.length, err.available());
           if (read > 0) {
               skipped += read;
           }
        }

        if(skipped == 0L) {
           p.waitFor(5L, TimeUnit.MILLISECONDS);
        }
    }
} finally {
   p.destroy();
}

The thread way works like this:

public void foo() {
    class DevNull implements Runnable {

        private final InputStream is;
        DevNull(final InputStream is) {
            is = Objects.requireNonNull(is);
        }

        public void run() {
            byte[] b = new byte[64];
            try {
                while (is.read(b) >= 0);
            } catch(IOException ignore) {
            }
        }
    }

    ExecutorService e = Executors.newCachedThreadPool();
    ProcessBuilder pb = new ProcessBuilder(cmdList);
    Process p = pb.start();
    try (InputStream in = p.getInputStream();
            InputStream err = p.getErrorStream();
            OutputStream closeOnly = p.getOutputStream()) {
        e.execute(new DevNull(in));
        e.execute(new DevNull(err));
        p.waitFor();
    } finally {
        p.destroy();
        e.shutdown();
    }
}


问:
CloudFormation nested stacks outputs limit
Facts:

CloudFormation Outputs limit its 60 per template.

I have 90 resources to export so I created the following structure:

parent_stack.template (contains the below nested stacks)

stack01.template (contains 45 resources and its outputs)

stack02.template (contains 45 resources and its outputs)

My issue:

I need to export those 90 resources but I can't export them in parent_stack.template because of the limit.

I can export them in their respective stack01.template and stack02.template but since they are nested when CloudFormation creates them it adds a random alphanumeric string like Stack01-1B0HKOV4YRD6A so I can't actually use the logical name to import from the nested stacks anywhere but in the parent.

I would really appreciate any help here.

Thanks in advance!!!

答:
You can reference nested output variables. Look at this draft example, this would be like a main cloud formation script:

```<code>Description: >
    Some desc

AWSTemplateFormatVersion: 2010-09-09

Resources:

  MyStackA:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "mystackA.yml"
      Parameters:
        ProjectName: "myprojectA"

  MyStackB:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "mystackB.yml"
      Parameters:
        ProjectName: "myprojectB"

  MyStackC:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "mystackC.yml"
      Parameters:
        ProjectName: "myprojectC"
        OutputFromMyStackA: !GetAtt MyStackA.Outputs.myoutputA
        OutputFromMyStackB: !GetAtt MyStackB.Outputs.myoutputB
</code>```

MyStackC consumes params from MyStackA and MyStackB. MyStackC script will need a parameters section:

```<code>Parameters:

  OutputFromMyStackA:
    Description: param from stack a
    Type: String

  OutputFromMyStackB:
    Description: param from stack b
    Type: String
</code>```

StackA and StackB need to output their own stuff too

```<code>Outputs:

  myoutputA:
    Description: the myoutputA
    Value: !Ref SomeStackAResource   ====> this references something inside the script for StackA
</code>```

Body:
You can reference nested output variables. Look at this draft example, this would be like a main cloud formation script:

Description: >
    Some desc

AWSTemplateFormatVersion: 2010-09-09

Resources:

  MyStackA:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "mystackA.yml"
      Parameters:
        ProjectName: "myprojectA"

  MyStackB:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "mystackB.yml"
      Parameters:
        ProjectName: "myprojectB"

  MyStackC:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "mystackC.yml"
      Parameters:
        ProjectName: "myprojectC"
        OutputFromMyStackA: !GetAtt MyStackA.Outputs.myoutputA
        OutputFromMyStackB: !GetAtt MyStackB.Outputs.myoutputB

MyStackC consumes params from MyStackA and MyStackB. MyStackC script will need a parameters section:

Parameters:

  OutputFromMyStackA:
    Description: param from stack a
    Type: String

  OutputFromMyStackB:
    Description: param from stack b
    Type: String

StackA and StackB need to output their own stuff too

Outputs:

  myoutputA:
    Description: the myoutputA
    Value: !Ref SomeStackAResource   ====> this references something inside the script for StackA


问:
Button HorizontalFieldManager, change background image on focus?
I want a horizontal field manager to act as a button, changing the background image on focus:

set background image for HorizontalFieldManager and it should change onfocus(select) and it should act as a button to push some other screen...

Under that HorizontalFieldManager I want to add an image and labels to display some information...

I want it exactly like in the screen shot, there are no edit fields..

答:
Call something like:

```<code>getMainManager().setBackground(BackgroundFactory.createLinearGradientBackground(Color.WHITE, Color.GRAY, Color.DIMGRAY, Color.DIMGRAY));
</code>```

to change the background of your screen.

Body:
Call something like:

getMainManager().setBackground(BackgroundFactory.createLinearGradientBackground(Color.WHITE, Color.GRAY, Color.DIMGRAY, Color.DIMGRAY));

to change the background of your screen.


问:
Is there any other proper way to have same control on two different tabs in C# form?
Here is what I have tried and is working. But I want to whether this is proper or is there a better option or way to do the same  </p>

```<code>private void tabs_SelectedIndexChanged(object sender, EventArgs e)
{
    TabControl control = (TabControl)sender;
    if(control.SelectedIndex == 3  || control.SelectedIndex == 0)
    {
        button1.Parent = control.SelectedTab;
        zonalarealabel.Parent = control.SelectedTab;
        pictureBox3.Parent = control.SelectedTab;

    }
}
</code>```

答: If you don't mind coupling your code to your user interface then your approach is valid. However, I think the better option is to create a user control that raises events handled by the selected tab. The user control would appear on tabs 0 and 3 at all times. The advantage of this is that you don't need to modify your SelectedIndexChanged event handler should you want these buttons to appear on a future tab. There are many ways to approach this problem, but given the very narrow functional requirements you shared, it's a better design to relegate these buttons to a user control rather than re-parent them at runtime.

Body:
Here is what I have tried and is working. But I want to whether this is proper or is there a better option or way to do the same

private void tabs_SelectedIndexChanged(object sender, EventArgs e)
{
    TabControl control = (TabControl)sender;
    if(control.SelectedIndex == 3  || control.SelectedIndex == 0)
    {
        button1.Parent = control.SelectedTab;
        zonalarealabel.Parent = control.SelectedTab;
        pictureBox3.Parent = control.SelectedTab;

    }
}


问:
How to calculate redo log size?
I am trying to figure out if the current redo log size I have right now is optimal. Here is what I have done:

I used the Oracle documentation to find most of this information:
http://www.oracle.com/technetwork/database/availability/async-2587521.pdf

Using SQL I used the below query

```<code> select thread#,sequence#,blocks*block_size/1024/1024 "MB",(next_time-first_time)*86400 "sec",
 (blocks*block_size/1024/1024)/((next_time-first_time)*86400) "MB/s"
 from V$ARCHIVED_LOG
 where ((next_time-first_time)*86400<>0) and
first_time between to_date('2020/03/28 08:00:00','YYYY/MM/DD HH24:MI:SS')
and to_date('2020/05/28 11:00:00','YYYY/MM/DD HH24:MI:SS')
and dest_id=3
order by first_time
</code>```

From the results, I calculate the average MB/S which is 7.67 and the maximum MB/S which is 245 MB/S

According to the Oracle documentation
See table on recommended redo log group size

Using this query

```<code>         select * from V$LOGFILE a, V$LOG b where a.GROUP# = b.GROUP#
</code>```

I discovered that I have 15 groups of 2 GB, so the redo log group size is 30 GB.

Oracle says that "In general we
recommend adding an additional 30% on top of the peak rate", so that would mean I am expected to have 245mb/s*1.3 = 318.5 MB/S. Then here is where I get a little lost. Do I use the table in the picture I attached? If so, I would be expected to have a redo log group size of 64GB? Or am I making a connection where there should not be one?

Finally, I did also

```<code>  select optimal_logfile_size from v$instance_recovery
</code>```

and that returns 14 GB.

I am having trouble making all the connections and trying to confirm, my redo log size is adequate.

答:
If you have 15 groups of 2GB each, then your group size is 2GB, not 30GB.

The idea is not to switch logs too often -  no more than every 20 minutes. So look at how often your log switches are happening. If you are still more than 20 minutes between switches then you are probably fine. If you are ever having more frequent switches than that, then you might need bigger logs.

Based on the calculations you performed, a max rate of ~319MB/s would indicate that individual redo log files should be 64GB, and you want a minimum (per best practice) of three redo log groups. That said - how much of your time is spent at peak load? If only a small amount of time per day (your average transaction rate is much lower) then this may be overkill. You don't want log switches to happen too far apart, either, or your ability to do point-in-time recovery after a redo log failure could be compromised.

It may make more sense for you to have log files that are 16GB and maintain a steady switch rate on average and accept a higher switch rate during peak load. You might need more individual log files that way to handle the same total transactions per minute without waiting for incomplete log switches: say three groups of 64GB each vs. 12 groups of 16GB each. The same total log capacity but in smaller chunks for switches and archive logging. That's probably why you have 15 groups of 2GB each configured now...

Title: How to calculate redo log size?

Body:
I am trying to figure out if the current redo log size I have right now is optimal. Here is what I have done:

I used the Oracle documentation to find most of this information:
http://www.oracle.com/technetwork/database/availability/async-2587521.pdf

Using SQL I used the below query

 select thread#,sequence#,blocks*block_size/1024/1024 "MB",(next_time-first_time)*86400 "sec",
 (blocks*block_size/1024/1024)/((next_time-first_time)*86400) "MB/s"
 from V$ARCHIVED_LOG
 where ((next_time-first_time)*86400<>0) and
first_time between to_date('2020/03/28 08:00:00','YYYY/MM/DD HH24:MI:SS')
and to_date('2020/05/28 11:00:00','YYYY/MM/DD HH24:MI:SS')
and dest_id=3
order by first_time

From the results, I calculate the average MB/S which is 7.67 and the maximum MB/S which is 245 MB/S

According to the Oracle documentation
See table on recommended redo log group size

Using this query

         select * from V$LOGFILE a, V$LOG b where a.GROUP# = b.GROUP#

I discovered that I have 15 groups of 2 GB, so the redo log group size is 30 GB.

Oracle says that "In general we
recommend adding an additional 30% on top of the peak rate", so that would mean I am expected to have 245mb/s*1.3 = 318.5 MB/S. Then here is where I get a little lost. Do I use the table in the picture I attached? If so, I would be expected to have a redo log group size of 64GB? Or am I making a connection where there should not be one?

Finally, I did also

  select optimal_logfile_size from v$instance_recovery

and that returns 14 GB.

I am having trouble making all the connections and trying to confirm, my redo log size is adequate.


问:
Should I use numpy's Random Generator?
I have a large Python code that I've been maintaining/updating/expanding since ~2014. Recently I came across numpy's Random Number Generator Policy (2018-05) and now I'm a bit confused.

I'm not sure what changed, and if I should upgrade my code accordingly to use the new Random Generator. For example, the Random sampling docs say:

```<code># Do this
from numpy.random import default_rng
rng = default_rng()
vals = rng.standard_normal(10)
more_vals = rng.standard_normal(10)

# instead of this
from numpy import random
vals = random.standard_normal(10)
more_vals = random.standard_normal(10)
</code>```

All my code depends on the (old?) syntax shown in the second block (i.e., I don't use default_rng but simple calls to np.random.seed(), np.random.uniform(), np.random.normal(), etc), and I don't know why I should use the first block instead of the second block.

Could someone shed some light over this please?

答:
1.In python2(old code) default_rng is not available.

2.In python3(new code) both first and second blocks you mentioned will runs without an error and executed.

3.In future they may drop the random.standard_normal from coming versions of python,that's why they mentioned to use of default_rng instead of random.standard_normal

Title: Should I use numpy's Random Generator?

Body:
I have a large Python code that I've been maintaining/updating/expanding since ~2014. Recently I came across numpy's Random Number Generator Policy (2018-05) and now I'm a bit confused.

I'm not sure what changed, and if I should upgrade my code accordingly to use the new Random Generator. For example, the Random sampling docs say:

# Do this
from numpy.random import default_rng
rng = default_rng()
vals = rng.standard_normal(10)
more_vals = rng.standard_normal(10)

# instead of this
from numpy import random
vals = random.standard_normal(10)
more_vals = random.standard_normal(10)

All my code depends on the (old?) syntax shown in the second block (i.e., I don't use default_rng but simple calls to np.random.seed(), np.random.uniform(), np.random.normal(), etc), and I don't know why I should use the first block instead of the second block.

Could someone shed some light over this please?


问:
putting linq to objects query result into a typed dictionary
Still kinda new to LINQ.  Seems like there should be a more elegant way to do this using ToDictionary, but can't figure it out.  Here's my code I want to clean up:</p>

```<code> var EventOccurrencesMappedToPatientMeds = from pm in allPtMeds
      from e in thisUsersEventOccurrencesPlusEventData
      where e.EventContainer.Event.PatientMedId == pm.MedicationId
      select new ScheduleEventOccurrenceMedPair{
           PatientMedication = pm,
           ScheduledEventOccurrence = e.EventOccurrence
      };

 int evtOccCount = 1;
 foreach (var evtOcc in EventOccurrencesMappedToPatientMeds)
 {
      // EventOccurrenceChoices is a Dictionary of type <int, IScheduledEventOccurrenceMedPair>
      message.EventOccurrenceChoices.Add(evtOccCount,(ScheduleEventOccurrenceMedPair)evtOcc);
 }
</code>```

答:
You can use the overloaded Enumerable.Select method to include the index, then use ToDictionary:

```<code>var dict = EventOccurrencesMappedToPatientMeds
               .Select((e, i) => new { Event = e, Index = i + 1 })
               .ToDictionary(o => o.Index,
                             o => (ScheduleEventOccurrenceMedPair)o.Event);
</code>```

Body:
Still kinda new to LINQ.  Seems like there should be a more elegant way to do this using ToDictionary, but can't figure it out.  Here's my code I want to clean up:

 var EventOccurrencesMappedToPatientMeds = from pm in allPtMeds
      from e in thisUsersEventOccurrencesPlusEventData
      where e.EventContainer.Event.PatientMedId == pm.MedicationId
      select new ScheduleEventOccurrenceMedPair{
           PatientMedication = pm,
           ScheduledEventOccurrence = e.EventOccurrence
      };

 int evtOccCount = 1;
 foreach (var evtOcc in EventOccurrencesMappedToPatientMeds)
 {
      // EventOccurrenceChoices is a Dictionary of type <int, IScheduledEventOccurrenceMedPair>
      message.EventOccurrenceChoices.Add(evtOccCount,(ScheduleEventOccurrenceMedPair)evtOcc);
 }

Body:
You can use the overloaded Enumerable.Select method to include the index, then use ToDictionary:

var dict = EventOccurrencesMappedToPatientMeds
               .Select((e, i) => new { Event = e, Index = i + 1 })
               .ToDictionary(o => o.Index,
                             o => (ScheduleEventOccurrenceMedPair)o.Event);


问:
Stop Google Maps reloading
When we drag Google Maps to show another location, it loads map images. When I go back to the first location, I would expect that those images were somehow cached, so no reload is needed. But that's not the case.

Anyone ever managed to somehow cache the same images, so no reload is needed?

EDIT (adding code sample)

```<code>var _map = new google.maps.Map(document.getElementById("vehicles-map"), {
    center: new google.maps.LatLng(Settings.default_map_lat, Settings.default_map_lng),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
</code>```

答:
So this won't be the case for all users, but I accidentally had "Disable cache" checked in my Chrome dev tools:

This is a sticky setting so it's easy to forget you had it enabled from a prior session.

Title: Stop Google Maps reloading

Body:
When we drag Google Maps to show another location, it loads map images. When I go back to the first location, I would expect that those images were somehow cached, so no reload is needed. But that's not the case.

Anyone ever managed to somehow cache the same images, so no reload is needed?

EDIT (adding code sample)

var _map = new google.maps.Map(document.getElementById("vehicles-map"), {
    center: new google.maps.LatLng(Settings.default_map_lat, Settings.default_map_lng),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});


问:
How to drop rows by condition on string value in pandas dataframe?
Consider a Pandas Dataframe like:

```<code>>>> import pandas as pd
>>> df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com', 'http://www.url2.com','http://www.url3.com','http://www.url1.com']))
>>> df
</code>```

Giving:

```<code>                   url
0      http://url1.com
1  http://www.url1.com
2  http://www.url2.com
3  http://www.url3.com
4  http://www.url1.com
</code>```

I want to remove all rows containing url1.com and url2.com to obtain dataframe result like:

```<code>                   url
0   http://ww.url3.com
</code>```

I do this

```<code>domainToCheck = ('url1.com', 'url2.com')
goodUrl = df['url'].apply(lambda x : any(domain in x for domain in domainToCheck))
</code>```

But this give me no result.

Any idea how to solve the above problem?

Edit: Solution

```<code>import pandas as pd
import tldextract

df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com','http://www.url2.com','http://www.url3.com','http://www.url1.com']))
domainToCheck = ['url1', 'url2']
s = df.url.map(lambda x : tldextract.extract(x).domain).isin(domainToCheck)
df = df[~s].reset_index(drop=True)
</code>```

答:
Use, Series.str.contains to create a boolean mask m and then you can filter the dataframe df using this boolean mask:

```<code>m = df['url'].str.contains('|'.join(domainToCheck))
df = df[~m].reset_index(drop=True)
</code>```

Result:

```<code>                   url
0  http://www.url3.com
</code>```

Body:
Consider a Pandas Dataframe like:

>>> import pandas as pd
>>> df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com', 'http://www.url2.com','http://www.url3.com','http://www.url1.com']))
>>> df

Giving:

                   url
0      http://url1.com
1  http://www.url1.com
2  http://www.url2.com
3  http://www.url3.com
4  http://www.url1.com

I want to remove all rows containing url1.com and url2.com to obtain dataframe result like:

                   url
0   http://ww.url3.com

I do this

domainToCheck = ('url1.com', 'url2.com')
goodUrl = df['url'].apply(lambda x : any(domain in x for domain in domainToCheck))

But this give me no result.

Any idea how to solve the above problem?

Edit: Solution

import pandas as pd
import tldextract

df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com','http://www.url2.com','http://www.url3.com','http://www.url1.com']))
domainToCheck = ['url1', 'url2']
s = df.url.map(lambda x : tldextract.extract(x).domain).isin(domainToCheck)
df = df[~s].reset_index(drop=True)

Body:
Use, Series.str.contains to create a boolean mask m and then you can filter the dataframe df using this boolean mask:

m = df['url'].str.contains('|'.join(domainToCheck))
df = df[~m].reset_index(drop=True)

Result:

                   url
0  http://www.url3.com


问:
How to get these rows from many to many table, which contains 0 in exact column?
```<code>a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 11
6| 15 | 0
7| 15 | 234
8| 14 | 0
</code>```

So I want to return only these a_id which all rows in b_id are 0. In this case it would be a_id = 14.

```<code>a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 0
6| 15 | 0
7| 15 | 0
8| 14 | 0
</code>```

In second case it would be 14 and 15

What I tried:

```<code>select a_id
from id_table
group by a_id
having max(b_id) > 0
</code>```

答:
If you want full rows then you can use not exists :

```<code>select t.*
from table t
where not exists (select 1 from table t1 where t1.a_id = t.a_id and t1.b_id <> 0);
</code>```

Body:
a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 11
6| 15 | 0
7| 15 | 234
8| 14 | 0

So I want to return only these a_id which all rows in b_id are 0. In this case it would be a_id = 14.

a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 0
6| 15 | 0
7| 15 | 0
8| 14 | 0

In second case it would be 14 and 15

What I tried:

select a_id
from id_table
group by a_id
having max(b_id) > 0

Body:
If you want full rows then you can use not exists :

select t.*
from table t
where not exists (select 1 from table t1 where t1.a_id = t.a_id and t1.b_id <> 0);


问:
How to remove last line in a text file in R?
Im reading a text file containing data with "problematic" line. The last line that starts with *NOTE has to be removed (number of rows in the text file is not always the same):

```<code>ColumnA ColumnB ColumnC
A2  17  14
B2  20  -1
C2  21  36

*NOTE: -1 = data do not exist
</code>```

This is my line to read the text file (i have to select text file since its location not constant:

```<code>my_data <- read.delim(file.choose(), header = TRUE, sep = "", quote = "",
                      dec = ".", fill = TRUE, comment.char = "")
</code>```

I have tried :

```<code>my_data[- grep("*NOTE:", my_data$ColumnA),]
</code>```

But it does not seem to work.
Any simple solutions to this?

答:
You could call read.delim with comment.char = "*":

```<code>my_data <- read.delim(file.choose(), header = TRUE, sep = "", quote = "",
                      dec = ".", fill = TRUE, comment.char = "*")
</code>```

This will remove the final line when you are reading it in because it starts with *.

Another option is fread from data.table. fread has a fancy autostart feature which automagically drops lines without the expected number of columns:

```<code>library(data.table)
fread(file.choose())
</code>```

Body:
Im reading a text file containing data with "problematic" line. The last line that starts with *NOTE has to be removed (number of rows in the text file is not always the same):

ColumnA ColumnB ColumnC
A2  17  14
B2  20  -1
C2  21  36

*NOTE: -1 = data do not exist

This is my line to read the text file (i have to select text file since its location not constant:

my_data <- read.delim(file.choose(), header = TRUE, sep = "", quote = "",
                      dec = ".", fill = TRUE, comment.char = "")

I have tried :

my_data[- grep("*NOTE:", my_data$ColumnA),]

But it does not seem to work.
Any simple solutions to this?

Body:
You could call read.delim with comment.char = "*":

my_data <- read.delim(file.choose(), header = TRUE, sep = "", quote = "",
                      dec = ".", fill = TRUE, comment.char = "*")

This will remove the final line when you are reading it in because it starts with *.

Another option is fread from data.table. fread has a fancy autostart feature which automagically drops lines without the expected number of columns:

library(data.table)
fread(file.choose())


问:
How can I get print except statement printed instead of an error below in try/except syntax in Python
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)
```

<p>This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?</p>

```Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
```

答:
For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.</p>

```<code>while True:
    try:
        hours_string = input("Enter Hours: ")
        hours_float = float(hours_string)
    except ValueError:
        print("Invalid input. Enter a number please.")
    else:
        break
while True:
    try:
        rate_string = input("Enter Rate: ")
        rate_float = float(rate_string)
    except ValueError:
        print("Invalid input. Enter a number please.")
    else:
        break

result = hours_float * rate_float
print("Pay",result)
</code>```

Body:
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)

This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?

Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined

Body:
For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.

while True:
    try:
        hours_string = input("Enter Hours: ")
        hours_float = float(hours_string)
    except ValueError:
        print("Invalid input. Enter a number please.")
    else:
        break
while True:
    try:
        rate_string = input("Enter Rate: ")
        rate_float = float(rate_string)
    except ValueError:
        print("Invalid input. Enter a number please.")
    else:
        break

result = hours_float * rate_float
print("Pay",result)


问:
Why does Pandas Dataframe first function(DataFrame.first("2D")), with appropriate offset value, return empty?
Say I have DataFrame with a date column and I decide to set that column as the index to perform time series operation. Calling DataFrame.first("1M") returns empty dataframe and DataFrame.last("1M") returns all the data even after sorting the index with DataFrame.sort_index(). In fact calling DataFrame.sort_index() causes this behavior as it worked as expected if I don't call the sort_index().
For example:</p>

```<code>    import pandas as pd
    df = pd.DataFrame({"1":[1,2,3], "2":[2,3,4], "date":["2020-05-29", "2020-05-24", "2020-05-27"]})
    df["date"] = pd.to_datetime(df["date"])
    print(df)
    df = df.set_index("date").sort_index(ascending=False)
    print(df.first("2D"))

</code>```

答:
Since sort_index() on dataframe causes the behavior,

we can sort the dataframe before resetting the index.

import pandas as pd

df = pd.DataFrame({"1": [1, 2, 3], "2": [2, 3, 4], "date": ["2020-05-29", "2020-05-24", "2020-05-27"]})

df["date"] = pd.to_datetime(df["date"])

df = df.sort_values(by='date').set_index("date")

print(df.first("2D"))
```

<pre class="lang-py prettyprint-override"><code>date
2020-05-24  2  3
</code>```

Body:
Say I have DataFrame with a date column and I decide to set that column as the index to perform time series operation. Calling DataFrame.first("1M") returns empty dataframe and DataFrame.last("1M") returns all the data even after sorting the index with DataFrame.sort_index(). In fact calling DataFrame.sort_index() causes this behavior as it worked as expected if I don't call the sort_index().
For example:

    import pandas as pd
    df = pd.DataFrame({"1":[1,2,3], "2":[2,3,4], "date":["2020-05-29", "2020-05-24", "2020-05-27"]})
    df["date"] = pd.to_datetime(df["date"])
    print(df)
    df = df.set_index("date").sort_index(ascending=False)
    print(df.first("2D"))

Body:
Since sort_index() on dataframe causes the behavior,

we can sort the dataframe before resetting the index.

import pandas as pd

df = pd.DataFrame({"1": [1, 2, 3], "2": [2, 3, 4], "date": ["2020-05-29", "2020-05-24", "2020-05-27"]})

df["date"] = pd.to_datetime(df["date"])

df = df.sort_values(by='date').set_index("date")

print(df.first("2D"))

date
2020-05-24  2  3