问:
How to show maximum same adjacent elements in an array in Java
Im new to Java and i'm doing array sorting problems and i'm having difficulties with this problem. Searched for simmular or duplicate posts, but didn't seem to find any.

The problem is "Find the most same, adjacent elements in an array and write them in to a new array".

My question is.
How can i store most occurued adjacent elements in an array from another array ?

This is what I have comed up so far.

```<code>int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array

int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];

for (i=1; i<length; i++)

    {
   if (arr[i-1]==arr[i])
    {
     counter++;      // Counter to represent maximal adjacent occurred elem.
     resultArr[i] = arr[i]  //Writing elements in result array
    }

}
 System.out.println(counter);
 System.out.println(resultArr);
</code>```

```<code> Input: It is the test array "arr"

 Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
 Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )
</code>```

My output is (directly from console)

1

[I@6d06d69c

答:
Break the problem down, first a method to determine when runs of adjacent values stop;

```<code>private static int runsTo(int[] vals, int index) {
    for (int i = index; i < vals.length - 1; i++) {
        if (vals[i] != vals[i + 1]) {
            return i;
        }
    }
    return vals.length;
}
</code>```

Then we can use that with Arrays.toString(int[])1 as well as Arrays.copyOfRange(int[], int, int) like

```<code>int[] arr = { 2, 1, 1, 3, 3, 2, 2, 2, 2, 1, 1 };
int index = 0, count = 0;
for (int i = 0; i < arr.length; i++) {
    int r = runsTo(arr, i);
    int c = r - i + 1;
    if (c > count) {
        index = i;
        count = c;
        i += count - 1;
    }
}
System.out.println(Arrays.toString(arr));
System.out.printf("Starting from %d get %d%n", index, count);
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, index, index + count)));
</code>```

Which outputs

```<code>[2, 1, 1, 3, 3, 2, 2, 2, 2, 1, 1]
Starting from 5 get 4
[2, 2, 2, 2]
</code>```

1 Java arrays do not override toString(), so you are getting the arrays' hashcode.

Body:
Im new to Java and i'm doing array sorting problems and i'm having difficulties with this problem. Searched for simmular or duplicate posts, but didn't seem to find any.

The problem is "Find the most same, adjacent elements in an array and write them in to a new array".

My question is.
How can i store most occurued adjacent elements in an array from another array ?

This is what I have comed up so far.

int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array

int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];

for (i=1; i<length; i++)

    {
   if (arr[i-1]==arr[i])
    {
     counter++;      // Counter to represent maximal adjacent occurred elem.
     resultArr[i] = arr[i]  //Writing elements in result array
    }

}
 System.out.println(counter);
 System.out.println(resultArr);

 Input: It is the test array "arr"

 Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
 Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )

My output is (directly from console)

1

[I@6d06d69c

Body:
Break the problem down, first a method to determine when runs of adjacent values stop;

private static int runsTo(int[] vals, int index) {
    for (int i = index; i < vals.length - 1; i++) {
        if (vals[i] != vals[i + 1]) {
            return i;
        }
    }
    return vals.length;
}

Then we can use that with Arrays.toString(int[])1 as well as Arrays.copyOfRange(int[], int, int) like

int[] arr = { 2, 1, 1, 3, 3, 2, 2, 2, 2, 1, 1 };
int index = 0, count = 0;
for (int i = 0; i < arr.length; i++) {
    int r = runsTo(arr, i);
    int c = r - i + 1;
    if (c > count) {
        index = i;
        count = c;
        i += count - 1;
    }
}
System.out.println(Arrays.toString(arr));
System.out.printf("Starting from %d get %d%n", index, count);
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, index, index + count)));

Which outputs

[2, 1, 1, 3, 3, 2, 2, 2, 2, 1, 1]
Starting from 5 get 4
[2, 2, 2, 2]

1 Java arrays do not override toString(), so you are getting the arrays' hashcode.


来源: stackexchange

问:
C++ virtual functions implementation outside the class
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.

Following code gives error:

```<code>class B
{
public:
    virtual void f();
};

void B::f() {
    std::cout<<"B::f";
}

class D : public B
{
public:
    void f2() {int b;}
};

// error: no "void D::f()" member function declared in class "D"
void D::f() {
    std::cout<<"D::F";
}
</code>```

It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?

Thanks in advance..

答:
You can't add members to a class outside of the class definition. If you want D to have an override for B::f then you have to declare it inside the class definition. Those are the rules.

Declaring a member in a base class doesn't automatically give derived classes an identical member. Inheriting from the base gives the derived class all the members of the base class so you can choose whether to override, hide or add to the base classes members but you have to indicate a choice to override in the class definition by declaring the overriding function.

ContentLicense: CC BY-SA 2.5

Body:
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.

Following code gives error:

class B
{
public:
    virtual void f();
};

void B::f() {
    std::cout<<"B::f";
}

class D : public B
{
public:
    void f2() {int b;}
};

// error: no "void D::f()" member function declared in class "D"
void D::f() {
    std::cout<<"D::F";
}

It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?

Thanks in advance..


问:
How to drop first row using pandas?
I've searched at other questions related to dropping rows but could not find one that worked:

I have a CSV file exported from the tool screaming frog that looks like this:

Internal - HTML |               |             |
--------------- | --------------|-------------|
   Address      |   Content     | Status Code |
----------------|---------------|-------------|
www.example.com |   text/html   |   200       |
```

<p>I want to remove the first row that contains 'Internal - HTML'. When analyzing it with <code>df.keys()</code> I get this information" <code>Index(['Internal - HTML'], dtype='object')</code>.</p>

<p>I want to use the second row as the Index, which contains the correct column labels.</p>

<p>When I use the code:</p>

```a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.drop('Internal - HTML')
a.head(3)
```

<p>I get this error: <code>KeyError: 'Internal - HTML'</code></p>

<p>I also tried what was suggested here Remove index name in pandas and also tried resetting the index:</p>

```a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.reset_index(level=0, drop=True)
a.head(3)
```

None of the options above worked.

答:
Not exactly sure about how data is in csv, but I think you can use skiprows=1 while reading the csv:

```<code>a = pd.read_csv("internal_html.csv", encoding="utf-8")
a.keys()
</code>```

Output:

```<code>Index(['Internal - HTML'], dtype='object')
</code>```

Looking at df (Assuming data is in following format):

```<code>print(a)
</code>```

Output:

```<code>                            Internal - HTML
Address            Content   Status Code
www.example.com   text/html     200
</code>```

Now, using skiprows to read the .csv file:

```<code>a = pd.read_csv("internal_html.csv", encoding="utf-8", skiprows=1)
print(a.keys())
</code>```

Output:

```<code>Index(['Address', '   Content', 'Status Code'], dtype='object')
</code>```

Observing dataframe a:

```<code>print(a)
</code>```

Output:

```<code>           Address      Content       Status Code
  0  www.example.com    text/html     200
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to drop first row using pandas?

Body:
I've searched at other questions related to dropping rows but could not find one that worked:

I have a CSV file exported from the tool screaming frog that looks like this:

Internal - HTML |               |             |
--------------- | --------------|-------------|
   Address      |   Content     | Status Code |
----------------|---------------|-------------|
www.example.com |   text/html   |   200       |

I want to remove the first row that contains 'Internal - HTML'. When analyzing it with df.keys() I get this information" Index(['Internal - HTML'], dtype='object').

I want to use the second row as the Index, which contains the correct column labels.

When I use the code:

a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.drop('Internal - HTML')
a.head(3)

I get this error: KeyError: 'Internal - HTML'

I also tried what was suggested here Remove index name in pandas and also tried resetting the index:

a = pandas.read_csv("internal_html.csv", encoding="utf-8")
a.reset_index(level=0, drop=True)
a.head(3)

None of the options above worked.

Body:
Not exactly sure about how data is in csv, but I think you can use skiprows=1 while reading the csv:

a = pd.read_csv("internal_html.csv", encoding="utf-8")
a.keys()

Output:

Index(['Internal - HTML'], dtype='object')

Looking at df (Assuming data is in following format):

print(a)

Output:

                            Internal - HTML
Address            Content   Status Code
www.example.com   text/html     200

Now, using skiprows to read the .csv file:

a = pd.read_csv("internal_html.csv", encoding="utf-8", skiprows=1)
print(a.keys())

Output:

Index(['Address', '   Content', 'Status Code'], dtype='object')

Observing dataframe a:

print(a)

Output:

           Address      Content       Status Code
  0  www.example.com    text/html     200


问:
Paypal sandbox account could not be created
When I try to create a business sandbox account it first has a status of processing but then always results in an error status code. It says the sandbox account could not be created, please delete it and create another one.

I saw that the paypal forms have some validation issues so I have already tried the following:

Password more than 8 characters containing uppercase,lowercase,numbers and symbol characters.

Positive balance < $1000

Valid fictional email address that is not the same as my address.

Tried different countries including the US.

Filled in the optional fields of first name and last name

But still the same error.

答:
I solved this by using a different browser. So I guess this was cache related in some way. I entered the following data:

Country: United States

Didn't fill in optional fields

Bank verified

Visa

$100 in account

I used Microsoft Edge instead of Chrome.


问:
What is wrong in my code if saving an info in Firebase database brings "App keeps stopping"
When clicking on button(bSave) and trying to save Name, Age and Id in realtime firebase database, app keeps stopping. Maybe the problem is with the connection between app and firebase ?

RegisterAcitivity

```<code>package com.example.mher.loginregister;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.security.cert.CertPathBuilderSpi;

public class RegisterActivity extends AppCompatActivity {

private EditText etAge;
private EditText etName;
private EditText etEmail;
private EditText etPassword;
private Button bRegister;
private Button bSave;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
DatabaseReference databaseDrivers;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    firebaseAuth=FirebaseAuth.getInstance();

    progressDialog=new ProgressDialog(this);

    etAge=(EditText) findViewById(R.id.etAge);
    etName=(EditText) findViewById(R.id.etName);
    etEmail=(EditText) findViewById(R.id.etEmail);
    etPassword=(EditText) findViewById(R.id.etPassword);
    bRegister=(Button) findViewById(R.id.bRegister);
    bSave=(Button) findViewById(R.id.bSave);
    databaseDrivers= FirebaseDatabase.getInstance().getReference();

    bSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adddriver();
        }
    });

    bRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            registeruser();

        }
    });

}
private void adddriver()
{
    String name=etName.getText().toString().trim();
    String age=etAge.getText().toString().trim();
    if(!TextUtils.isEmpty(name))
    {
        String id=databaseDrivers.push().getKey();
        Driver driver=new Driver(id,name,age);
        databaseDrivers.child(id).setValue(driver);

    }
    else
    {
        Toast.makeText(this,"Please enter a name",Toast.LENGTH_SHORT);
    }
}
private void registeruser()
{
    String email=etEmail.getText().toString().trim();
    String password=etPassword.getText().toString().trim();
    if(TextUtils.isEmpty(email))
    {
        Toast.makeText(this,"Please Enter Your Email",Toast.LENGTH_SHORT).show();
        return;

    }
    if(TextUtils.isEmpty(password))
    {
        Toast.makeText(this,"Please Enter Your Password",Toast.LENGTH_SHORT).show();
        return;

    }
    progressDialog.setMessage("Registering User");
    progressDialog.show();
    firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful())
            {
                Toast.makeText(RegisterActivity.this,"Registered Successfully",Toast.LENGTH_SHORT).show();
                progressDialog.hide();
            }
            else
            {
                Toast.makeText(RegisterActivity.this,"Could Not Register Successfully",Toast.LENGTH_SHORT).show();
                progressDialog.hide();
            }

        }
    });

}
</code>```

}

Driver Class

```<code>package com.example.mher.loginregister;

public class Driver {
String DriverId;
String DriverName;
String DriverAge;
public Driver()
{

}

public Driver(String driverId, String driverName, String driverAge) {
    DriverId = driverId;
    DriverName = driverName;
    DriverAge = driverAge;
}

public String getDriverId() {
    return DriverId;
}

public String getDriverName() {
    return DriverName;
}

public String getDriverAge() {
    return DriverAge;
}
}
</code>```

答:
I think it is because this:

```<code>String id=databaseDrivers.push().getKey();
Driver driver=new Driver(id,name,age);
databaseDrivers.child(id).setValue(driver);
</code>```

getKey() retrieves value from server, so databaseDrivers.child(id).setValue(driver); must wait before it is done and it causes a freeze.

Try this:

```<code>DatabaseReference newPostRef = databaseDrivers.push();
newPostRef.setValue(driver);
</code>```

or simplier:

```<code>databaseDrivers.push().setValue(driver);
</code>```

This way you can't add an id to your driver object, but you don't need it because it is stored as a key to your value (driver).

Body:
When clicking on button(bSave) and trying to save Name, Age and Id in realtime firebase database, app keeps stopping. Maybe the problem is with the connection between app and firebase ?

RegisterAcitivity

package com.example.mher.loginregister;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.security.cert.CertPathBuilderSpi;

public class RegisterActivity extends AppCompatActivity {

private EditText etAge;
private EditText etName;
private EditText etEmail;
private EditText etPassword;
private Button bRegister;
private Button bSave;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
DatabaseReference databaseDrivers;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    firebaseAuth=FirebaseAuth.getInstance();

    progressDialog=new ProgressDialog(this);

    etAge=(EditText) findViewById(R.id.etAge);
    etName=(EditText) findViewById(R.id.etName);
    etEmail=(EditText) findViewById(R.id.etEmail);
    etPassword=(EditText) findViewById(R.id.etPassword);
    bRegister=(Button) findViewById(R.id.bRegister);
    bSave=(Button) findViewById(R.id.bSave);
    databaseDrivers= FirebaseDatabase.getInstance().getReference();

    bSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adddriver();
        }
    });

    bRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            registeruser();

        }
    });

}
private void adddriver()
{
    String name=etName.getText().toString().trim();
    String age=etAge.getText().toString().trim();
    if(!TextUtils.isEmpty(name))
    {
        String id=databaseDrivers.push().getKey();
        Driver driver=new Driver(id,name,age);
        databaseDrivers.child(id).setValue(driver);

    }
    else
    {
        Toast.makeText(this,"Please enter a name",Toast.LENGTH_SHORT);
    }
}
private void registeruser()
{
    String email=etEmail.getText().toString().trim();
    String password=etPassword.getText().toString().trim();
    if(TextUtils.isEmpty(email))
    {
        Toast.makeText(this,"Please Enter Your Email",Toast.LENGTH_SHORT).show();
        return;

    }
    if(TextUtils.isEmpty(password))
    {
        Toast.makeText(this,"Please Enter Your Password",Toast.LENGTH_SHORT).show();
        return;

    }
    progressDialog.setMessage("Registering User");
    progressDialog.show();
    firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful())
            {
                Toast.makeText(RegisterActivity.this,"Registered Successfully",Toast.LENGTH_SHORT).show();
                progressDialog.hide();
            }
            else
            {
                Toast.makeText(RegisterActivity.this,"Could Not Register Successfully",Toast.LENGTH_SHORT).show();
                progressDialog.hide();
            }

        }
    });

}

}

Driver Class

package com.example.mher.loginregister;

public class Driver {
String DriverId;
String DriverName;
String DriverAge;
public Driver()
{

}

public Driver(String driverId, String driverName, String driverAge) {
    DriverId = driverId;
    DriverName = driverName;
    DriverAge = driverAge;
}

public String getDriverId() {
    return DriverId;
}

public String getDriverName() {
    return DriverName;
}

public String getDriverAge() {
    return DriverAge;
}
}

Body:
I think it is because this:

String id=databaseDrivers.push().getKey();
Driver driver=new Driver(id,name,age);
databaseDrivers.child(id).setValue(driver);

getKey() retrieves value from server, so databaseDrivers.child(id).setValue(driver); must wait before it is done and it causes a freeze.

Try this:

DatabaseReference newPostRef = databaseDrivers.push();
newPostRef.setValue(driver);

or simplier:

databaseDrivers.push().setValue(driver);

This way you can't add an id to your driver object, but you don't need it because it is stored as a key to your value (driver).


问:
Python, Flask client ip address
I need to log the IP address of every user of my webapp, that I've created with Python and Flask.

I'm using

```<code>request.remote_addr
</code>```

But that's return the IP address of the server the app is deployed to. Any fixes to this?

答:
The easiest way to get the user's(also known as client) IP is to set this as a variable or use it directly.

request.environ['REMOTE_ADDR']

To get your server's IP:

request.remote_addr

Title: Python, Flask client ip address

Body:
I need to log the IP address of every user of my webapp, that I've created with Python and Flask.

I'm using

request.remote_addr

But that's return the IP address of the server the app is deployed to. Any fixes to this?


问:
Sending props to parent on second render using conponentDidMount
I have Parent component which calls the child component

```<code>class Parent extends Component {
  constructor(props){
    super(props);
    this.data = this.getData();
  }
  getData(val){
  // this is where the problems come when setting
  // val on the second render
   if(typeof val != "undefined"){
    return val;
   }

  }

  render() {
    return (
      <div className="App">
      <Child sendData={this.getLineOffset} onDataLoaded={this.forceUpdate}/>

      </div>
    );

  }
}

export default Home;
</code>```

In the child component I run componentDidMount function because I need to get an offset of a div which is being rendered on the first render. And on the second render it gets the refs value

```<code>export default class Child extends Component {
    constructor(props) {
        super(props);
        }

    componentDidMount() {
        // sending props to the parent
        this.props.sendData(this.refs.el.offsetLeft);
    }
  render() {
    return (
      <div ref="el" > </div>
    );
  }
}
</code>```

The problem I am facing is that in the parent I only get value from the first render in the parent, because constructor is saving only the first value i return in the getData funcion.

I understand it is not the best practice, but I couldn't find any other ways to get the offset of the rendered content.

I have tried using forceUpdate when the data is loaded but the value is still undefined.

Of course if console log in the getData function It will display but still  not saved in the constructor.

How could i solve this problem ?

Thanks in advance.

答: You can get new values by adding a componentWillReceiveProps(nextProps) in the child component. You then compare the oldProps and the newProps on the second render and update the props to the new one.

Body:
I have Parent component which calls the child component

class Parent extends Component {
  constructor(props){
    super(props);
    this.data = this.getData();
  }
  getData(val){
  // this is where the problems come when setting
  // val on the second render
   if(typeof val != "undefined"){
    return val;
   }

  }

  render() {
    return (

      <Child sendData={this.getLineOffset} onDataLoaded={this.forceUpdate}/>

    );

  }
}

export default Home;

In the child component I run componentDidMount function because I need to get an offset of a div which is being rendered on the first render. And on the second render it gets the refs value

export default class Child extends Component {
    constructor(props) {
        super(props);
        }

    componentDidMount() {
        // sending props to the parent
        this.props.sendData(this.refs.el.offsetLeft);
    }
  render() {
    return (

    );
  }
}

The problem I am facing is that in the parent I only get value from the first render in the parent, because constructor is saving only the first value i return in the getData funcion.

I understand it is not the best practice, but I couldn't find any other ways to get the offset of the rendered content.

I have tried using forceUpdate when the data is loaded but the value is still undefined.

Of course if console log in the getData function It will display but still  not saved in the constructor.

How could i solve this problem ?

Thanks in advance.


问:
500 Internal Server Error when updating htaccess
I'm using a quiz plugin for WP which caused a 504 Gateway Timeout after adding too many questions.

The developer told me to update my .htaccess file with the following code:

```<code>php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000
</code>```

This is the .htaccess code before I added the 3 lines of code:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

And this is after I've added the code:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000
</IfModule>

# END WordPress
</code>```

I also tried doing it like this:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000

# END WordPress
</code>```

However, both cause a 500 Internal Server Error.
I'm not really sure what I'm doing wrong and was hoping to get your insight on it.

Here's a link to the FAQ / Article the developer of the plugin told me to use.
https://www.ohmyquiz.io/knowledgebase/get-fatal-error-save-big-quiz/

答:
Have you tried this? Before # BEGIN Wordpress, This must work.</p>

```<code>php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Body:
I'm using a quiz plugin for WP which caused a 504 Gateway Timeout after adding too many questions.

The developer told me to update my .htaccess file with the following code:

php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000

This is the .htaccess code before I added the 3 lines of code:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

And this is after I've added the code:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000
</IfModule>

# END WordPress

I also tried doing it like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000

# END WordPress

However, both cause a 500 Internal Server Error.
I'm not really sure what I'm doing wrong and was hoping to get your insight on it.

Here's a link to the FAQ / Article the developer of the plugin told me to use.
https://www.ohmyquiz.io/knowledgebase/get-fatal-error-save-big-quiz/

Body:
Have you tried this? Before # BEGIN Wordpress, This must work.

php_value max_input_vars 5000
php_value suhosin.post.max_vars 5000
php_value suhosin.request.max_vars 5000

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


问:
How can flex-shrink win against padding?
I have a flex-box tag cloud that is being sized from the outside. I want tags inside it to be collapsible all the way down to zero if needed (an edge case). Right now, they will go only as far as 2x their padding.

Basically, I need a way to make flex-shrink "win" against padding.

If possible, I'd like to achieve that without using overflow: hidden, as that will interfere with other stuff that is inside this enclosure.

Runnable snippet:

$('button').on('click', (e) => {
  $('.tags').css({
    width: $(e.target).text()
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tags {
  display: flex;
  margin-bottom: 20px;
  background: red;
  overflow: visible;
  padding: 20px 5px;
}
.tag {
  position: relative;
  padding: 5px 10px;
  background: #ccc;
  border: 1px solid #aaa;
  border-radius: 20px;
  white-space: nowrap;
  text-overflow: ellipsis;
  flex-shrink: 1;
  overflow: hidden;
}
.tag + .tag {
  margin-left: 3px;
}</code>```

Tags will not collapse beyond 2 x padding

Tag 1

Tag 2

Tag 3

  <button>200px</button>
  <button>100px</button>
  <button>50px</button>
  <button>10px</button>

```

Anyone has an idea?

答:
flex-shrink can't win against padding, neither can a normal block element: fiddle demo

One way to make that work is to add an extra wrapper for the text and set padding/borders on it instead of the flex item.

$('button').on('click', (e) => {
  $('.tags').css({
    width: $(e.target).text()
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tags {
  display: flex;
  margin-bottom: 20px;
  background: red;
  overflow: visible;
  padding: 20px 5px;
}
.tag {
  flex-shrink: 1;
  overflow: hidden;
}
.tag div {
  padding: 5px 10px;
  background: #ccc;
  border: 1px solid #aaa;
  border-radius: 20px;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.tag + .tag {
  margin-left: 3px;
}</code>```

Tags will not collapse beyond 2 x padding

Tag 1

Tag 2

Tag 3

  <button>200px</button>
  <button>100px</button>
  <button>50px</button>
  <button>10px</button>

```

Body:
I have a flex-box tag cloud that is being sized from the outside. I want tags inside it to be collapsible all the way down to zero if needed (an edge case). Right now, they will go only as far as 2x their padding.

Basically, I need a way to make flex-shrink "win" against padding.

If possible, I'd like to achieve that without using overflow: hidden, as that will interfere with other stuff that is inside this enclosure.

Runnable snippet:

$('button').on('click', (e) => {
  $('.tags').css({
    width: $(e.target).text()
  });
});

.tags {
  display: flex;
  margin-bottom: 20px;
  background: red;
  overflow: visible;
  padding: 20px 5px;
}
.tag {
  position: relative;
  padding: 5px 10px;
  background: #ccc;
  border: 1px solid #aaa;
  border-radius: 20px;
  white-space: nowrap;
  text-overflow: ellipsis;
  flex-shrink: 1;
  overflow: hidden;
}
.tag + .tag {
  margin-left: 3px;
}

Tags will not collapse beyond 2 x padding

Tag 1

Tag 2

Tag 3

  <button>200px</button>
  <button>100px</button>
  <button>50px</button>
  <button>10px</button>

Anyone has an idea?

Body:
flex-shrink can't win against padding, neither can a normal block element: fiddle demo

One way to make that work is to add an extra wrapper for the text and set padding/borders on it instead of the flex item.

$('button').on('click', (e) => {
  $('.tags').css({
    width: $(e.target).text()
  });
});

.tags {
  display: flex;
  margin-bottom: 20px;
  background: red;
  overflow: visible;
  padding: 20px 5px;
}
.tag {
  flex-shrink: 1;
  overflow: hidden;
}
.tag div {
  padding: 5px 10px;
  background: #ccc;
  border: 1px solid #aaa;
  border-radius: 20px;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.tag + .tag {
  margin-left: 3px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Tags will not collapse beyond 2 x padding</h3>
<div class="tags" style="width: 200px">
  <div class="tag"><div>Tag 1</div></div>
  <div class="tag"><div>Tag 2</div></div>
  <div class="tag"><div>Tag 3</div></div>
</div>
<br />
<div>
  <button>200px</button>
  <button>100px</button>
  <button>50px</button>
  <button>10px</button>
</div>


问:
coloring buttons
i want to color the text inside the button
how can i do that?
i made that code:

```<code>for(int i=0; i<10 ;i++)
    {
        arr[i]=new Button(""+i);
        arr[i].
        arr[i].setBackground(Color.LIGHT_GRAY);
        p1.add(arr[i]);
        this.arr[i].addActionListener(this);
    }
</code>```

the buttons text color is black.
if i want to color the text in the button from black to blue what i need to write?

答: arr[ i ].setForeground( Color.BLUE );</p>

Title: coloring buttons

Body:
i want to color the text inside the button
how can i do that?
i made that code:

for(int i=0; i<10 ;i++)
    {
        arr[i]=new Button(""+i);
        arr[i].
        arr[i].setBackground(Color.LIGHT_GRAY);
        p1.add(arr[i]);
        this.arr[i].addActionListener(this);
    }

the buttons text color is black.
if i want to color the text in the button from black to blue what i need to write?

Body: arr[ i ].setForeground( Color.BLUE );


问:
DropDown List selections in asp mvc
I am using a loop to create multi DropDownList in the same view. As a result of the loop, two lists are created. However the problem is when user select an item from one list, the other list will change its selection to be the same selection from the other one.

So, how do I avoid that, and make selection process separated from a list to another?

Here is the code generate the list

```<code>@Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })
</code>```

EDIT:

The ListItem Code is this

```<code>List<SelectListItem> listItems = new List<SelectListItem>();

listItems.Add(new SelectListItem
{

    Text = "1 day",
    Value = "1"
});
listItems.Add(new SelectListItem
{

    Text = "3 days",
    Value = "3"
});
listItems.Add(new SelectListItem
{
    Selected = true,
    Text = "7 days",
    Value = "7"
});
listItems.Add(new SelectListItem
{

    Text = "15 days",
    Value = "15"
});
listItems.Add(new SelectListItem
{

    Text = "30 days",
    Value = "30"
});
</code>```

and This is the loop

```<code>@{
foreach (var item in companyList)
{
<div class="panel-body">

                                            <form class="form-horizontal" role="form" action="/Admin/Telecom" method="post">
                                                <div class="form-group">
                                                    <label class="col-sm-2 control-label">Payment View</label>
                                                    <div class="col-sm-6">

                                                        @Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })
                                                    </div>

                                                    <div class="col-sm-3">
                                                        <button type="submit" name="btnView" value="@item.TelecomCompanyName" class="btn btn-primary btn-rounded w-md waves-effect waves-light m-b-5">change</button>
                                                    </div>
                                                </div>
                                            </form>

                                    </div>
}
</code>```

答:
You are dynamically generating more dropdownlists with the same id.

They should have different ids to behave correctly.

```<code>@Html.DropDownList("selectedDays" + item.id, listItems, new { @class = "form-control", id="Day"+item.id })
</code>```

Title: DropDown List selections in asp mvc

Body:
I am using a loop to create multi DropDownList in the same view. As a result of the loop, two lists are created. However the problem is when user select an item from one list, the other list will change its selection to be the same selection from the other one.

So, how do I avoid that, and make selection process separated from a list to another?

Here is the code generate the list

@Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })

EDIT:

The ListItem Code is this

List<SelectListItem> listItems = new List<SelectListItem>();

listItems.Add(new SelectListItem
{

    Text = "1 day",
    Value = "1"
});
listItems.Add(new SelectListItem
{

    Text = "3 days",
    Value = "3"
});
listItems.Add(new SelectListItem
{
    Selected = true,
    Text = "7 days",
    Value = "7"
});
listItems.Add(new SelectListItem
{

    Text = "15 days",
    Value = "15"
});
listItems.Add(new SelectListItem
{

    Text = "30 days",
    Value = "30"
});

and This is the loop

@{
foreach (var item in companyList)
{

                                            <form class="form-horizontal" role="form" action="/Admin/Telecom" method="post">

                                                    Payment View

                                                        @Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })

                                                        <button type="submit" name="btnView" value="@item.TelecomCompanyName" class="btn btn-primary btn-rounded w-md waves-effect waves-light m-b-5">change</button>

                                            </form>

}

Body:
You are dynamically generating more dropdownlists with the same id.

They should have different ids to behave correctly.

@Html.DropDownList("selectedDays" + item.id, listItems, new { @class = "form-control", id="Day"+item.id })


问:
inserting relationships go-pg PostgreSQL
I've got 2 structs to represent a ManyToMany relationship. User and Note

```<code>type User struct {
    ID int
    Name string
    Notes []*Note
}

type Note struct {
    TableName struct{} `sql:"user_notes"`
    ID int
    Text string
}
</code>```

Now let's say I want to insert a new user and also at the same time add a few notes.

I would expect this to insert a user and its note(s):

```<code>note := Note{
    Text: "alohaa dude",
}

user := User{
    Name:  "peter",
    Notes: []Note{no},
}

s.DB.Insert(&user)
</code>```

However this only saves the user and not the user and the note. In go-pg do I have to do this manually or is there an automated way through the ORM?

答:
Rodrigo, same problem statement is being discussed here: https://github.com/go-pg/pg/issues/478

This functionality is not supported in go-pg at this time and you might want to try a db prepare approach to insert with relationships.

Body:
I've got 2 structs to represent a ManyToMany relationship. User and Note

type User struct {
    ID int
    Name string
    Notes []*Note
}

type Note struct {
    TableName struct{} `sql:"user_notes"`
    ID int
    Text string
}

Now let's say I want to insert a new user and also at the same time add a few notes.

I would expect this to insert a user and its note(s):

note := Note{
    Text: "alohaa dude",
}

user := User{
    Name:  "peter",
    Notes: []Note{no},
}

s.DB.Insert(&user)

However this only saves the user and not the user and the note. In go-pg do I have to do this manually or is there an automated way through the ORM?


问:
how to chain the START command in cmd?
My goal is to be able to chain START commands in a single cmd line.

Lets say I have a cmd window (lets call it starter). With a single line I want to start a new cmd window (lets call it cmd1) that will echo 1 and start another cmd window (lets call it cmd2) that will echo 2 and wait (with pause), after cmd1 called cmd2 (without waiting for it to finish) it will wait as well (with pause), after starter called cmd1 (without waiting for it to finish) it will close (or do nothing)

In the end I should end up with 2 cmd windows (cmd1 with "1" printed, cmd2 with 2 printed) and both are waiting for ENTER.

Running scheme:

```<code>--- Starter
    +--- Start cmd1 (Non-blocking)
    |    +--- Start cmd2 (Non-blocking)
    |    |    +--- Echo 2
    |    |    \--- Pause (Blocking cmd2)
    |    +--- Echo 1
    |    \--- Pause (Blocking cmd1)
    \---Do nothing (Starter, Incase running from bat file starter will exit)
</code>```

I wrote this cmd line in a bat file:

```<code>title starter
start cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause
                       \----------cmd2-----------/
      \---------------------------cmd1----------------------------/
</code>```

(the "title starter" is just for understanding which window is opened and should not be included in the final line)

with that cmd line, starter is the one that prints 2 and waits, and cmd1 just exits after calling cmd2.

The running scheme of that line:

```<code>--- Starter
    +--- Start cmd1 (Non-blocking)
    |    \--- Start cmd2 (Non-blocking)
    |         +--- Echo 2
    |         \--- Pause (Blocking cmd2)
    +--- Echo 1
    +--- Pause (Blocking Starter)
    \---Do nothing (Starter, Incase running from bat file starter will exit)
</code>```

I tried some other variations of this line with no success.

```<code>title starter
start "cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c ""echo 2 & pause"" & echo 1 & pause"
</code>```

(important to note that I can open the 2 cmds (cmd1, cmd2) from the first cmd (starter) and the result of this will be the final result of my wanted running scheme, but it is important that cmd1 will be the one that creates cmd2)

So, does anyone know how may I achieve the running scheme that I want?

答:
Here is a script that will recursively START any arbitrary number of windows. Simply pass the count as the first and only argument to the script. If you don't provide the count, then it will only open 1 window.

The technique relies on the definition of a variable named cmd that serves as a "macro". It contains the string of commands to be executed by cmd.exe /v:on /c. It is important that the macro not be expanded until within the child process. Within the parent batch I delay expansion of the macro by using %%cmd%%. All subsequent processes have a command line context instead of batch context, so the delay is achieved by %^cmd% instead. When defining the macro, the percents must be doubled as %%^cmd%% to achieve the desired string of %^cmd%.

RecursiveStart.bat

```<code>@echo off
setlocal disableDelayedExpansion
set /a N=1, END=%~1+0
set "cmd=set /a N+=1,N-1&echo(&(if not !N! gtr !END! start "!N!" cmd /v:on /c %%^cmd%%)&pause"
start "%N%" cmd /v:on /c %%cmd%%
</code>```

For example, to start 5 windows, simply use:

```<code>RecursiveStart 5
</code>```

However, if all you want to do is open N number of windows and execute some commands in each, and each window is entirely independent of the other (don't care who started it), then it is much simpler to iterate the START command N times in your parent script.

```<code>@echo off
for /l %%N in (1 1 5) do start "%%N" cmd /c "echo %%N&pause"
</code>```

Title: how to chain the START command in cmd?

Body:
My goal is to be able to chain START commands in a single cmd line.

Lets say I have a cmd window (lets call it starter). With a single line I want to start a new cmd window (lets call it cmd1) that will echo 1 and start another cmd window (lets call it cmd2) that will echo 2 and wait (with pause), after cmd1 called cmd2 (without waiting for it to finish) it will wait as well (with pause), after starter called cmd1 (without waiting for it to finish) it will close (or do nothing)

In the end I should end up with 2 cmd windows (cmd1 with "1" printed, cmd2 with 2 printed) and both are waiting for ENTER.

Running scheme:

--- Starter
    +--- Start cmd1 (Non-blocking)
    |    +--- Start cmd2 (Non-blocking)
    |    |    +--- Echo 2
    |    |    \--- Pause (Blocking cmd2)
    |    +--- Echo 1
    |    \--- Pause (Blocking cmd1)
    \---Do nothing (Starter, Incase running from bat file starter will exit)

I wrote this cmd line in a bat file:

title starter
start cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause
                       \----------cmd2-----------/
      \---------------------------cmd1----------------------------/

(the "title starter" is just for understanding which window is opened and should not be included in the final line)

with that cmd line, starter is the one that prints 2 and waits, and cmd1 just exits after calling cmd2.

The running scheme of that line:

--- Starter
    +--- Start cmd1 (Non-blocking)
    |    \--- Start cmd2 (Non-blocking)
    |         +--- Echo 2
    |         \--- Pause (Blocking cmd2)
    +--- Echo 1
    +--- Pause (Blocking Starter)
    \---Do nothing (Starter, Incase running from bat file starter will exit)

I tried some other variations of this line with no success.

title starter
start "cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c ""echo 2 & pause"" & echo 1 & pause"

(important to note that I can open the 2 cmds (cmd1, cmd2) from the first cmd (starter) and the result of this will be the final result of my wanted running scheme, but it is important that cmd1 will be the one that creates cmd2)

So, does anyone know how may I achieve the running scheme that I want?

Body:
Here is a script that will recursively START any arbitrary number of windows. Simply pass the count as the first and only argument to the script. If you don't provide the count, then it will only open 1 window.

The technique relies on the definition of a variable named cmd that serves as a "macro". It contains the string of commands to be executed by cmd.exe /v:on /c. It is important that the macro not be expanded until within the child process. Within the parent batch I delay expansion of the macro by using %%cmd%%. All subsequent processes have a command line context instead of batch context, so the delay is achieved by %^cmd% instead. When defining the macro, the percents must be doubled as %%^cmd%% to achieve the desired string of %^cmd%.

RecursiveStart.bat

@echo off
setlocal disableDelayedExpansion
set /a N=1, END=%~1+0
set "cmd=set /a N+=1,N-1&echo(&(if not !N! gtr !END! start "!N!" cmd /v:on /c %%^cmd%%)&pause"
start "%N%" cmd /v:on /c %%cmd%%

For example, to start 5 windows, simply use:

RecursiveStart 5

However, if all you want to do is open N number of windows and execute some commands in each, and each window is entirely independent of the other (don't care who started it), then it is much simpler to iterate the START command N times in your parent script.

@echo off
for /l %%N in (1 1 5) do start "%%N" cmd /c "echo %%N&pause"


问:
div animate not working jquery
HTML

```<code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>
</head>

<body>
  <div id="top1">
    <div class="inside1">
      <div class="nested_inside1"> MY HAPPY PLACES </div>
    </div>
    <div class="inside2">
      <div class="nested_inside2"> CLUMSSY BEACHES
      </div>
    </div>
    <div class="inside3">
      <div class="nested_inside3"> REGULAR APPLES </div>
    </div>
    <div class="inside4">
      <div class="nested_inside4"> LUSTY BRUSHES </div>
    </div>
    <div class="inside5">
      <div class="nested_inside5"> ECSTATIC DIMENSIONS </div>
    </div>
    <div class="inside6">
      <div class="nested_inside6"> CURLY HILLS </div>
    </div>
    <div class="inside7">
      <div class="nested_inside7"> SHINY WATER </div>
    </div>
    <div class="inside8">
      <div class="nested_inside8"> COOL BOATS </div>
    </div>
    <div class="inside9">
      <div class="nested_inside9"> CRUNCHY CLUSHTERS </div>
    </div>
    <script type="text/javascript" src="myscript2.js"></script>
</body>

</html>
</code>```

JavaScript

```<code>$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});
</code>```

答:
There are two inherent problems with this:

The CSS - Add position: relative to .nested_inside to make sure the top property works

The hover event has been removed from jQuery 1.8. You'll need to replace it with mouseenter and mouseleave and do the necessary animations if you're using the latest version of jQuery

I've added a fiddle based on my assumption of how it should work:
https://jsfiddle.net/fxmtz2yn/

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

 $("#top1").on("mouseover mouseleave", ".nested_inside",function(evt) {
    var $el = $(this),
        top = $el;
    switch(evt.type) {
        case "mouseover":
            $el.animate({
                "top": "-10px"
            });
            break;
        case "mouseleave":
           $el.animate({
               "top": "0"
           });
           break;
    }
  });
});
</code>```

Title: div animate not working jquery

Body:
HTML

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>

 MY HAPPY PLACES

 CLUMSSY BEACHES

 REGULAR APPLES

 LUSTY BRUSHES

 ECSTATIC DIMENSIONS

 CURLY HILLS

 SHINY WATER

 COOL BOATS

 CRUNCHY CLUSHTERS

JavaScript

$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});

Body:
There are two inherent problems with this:

The CSS - Add position: relative to .nested_inside to make sure the top property works

The hover event has been removed from jQuery 1.8. You'll need to replace it with mouseenter and mouseleave and do the necessary animations if you're using the latest version of jQuery

I've added a fiddle based on my assumption of how it should work:
https://jsfiddle.net/fxmtz2yn/

$(document).ready(function() {

 $("#top1").on("mouseover mouseleave", ".nested_inside",function(evt) {
    var $el = $(this),
        top = $el;
    switch(evt.type) {
        case "mouseover":
            $el.animate({
                "top": "-10px"
            });
            break;
        case "mouseleave":
           $el.animate({
               "top": "0"
           });
           break;
    }
  });
});


问:
NodeJS: load html with res.write()
I'm new to Node so I'm trying to learn it. I'm trying to load a simple HTML file in Node but that gives me an error as HTML is not defined when I use res.write(html) I saw some examples where are similar to me so I would like to understand what is wrong here.
I wrote this:

```<code>const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    }
});

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    res.write(html);
    res.end();
});

server.listen(port, hostname, () => {
    console.log('Server started on port ' + port);
});
</code>```

答:
As Soren pointed out, htmlis not defined when you call to res.write(). Asynchronous can be very convenient but it's a bit difficult to understand when you are a beginner. The best for you is to try to handle the concept of asynchronous tasks. Until then, a solution to your problem would be to use the synchronous version of fs.readFile, fs.readFileSync (docs here), and call it inside the createServer function.

Since readFileSync returns the read stuff synchronously, you could do:

```<code>const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    var html = fs.readFileSync('./index.html');
    res.write(html);
    res.end();
});
</code>```

Another option, as I guess you were trying to make, is to initialize the html variable in the callback of readFile.

```<code>var html_g; //global html variable
fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    } else {
        html_g = html; //html_g = content_of_index_file;
});
</code>```

But since this function is asynchrounous, the createServer function could be called before html_g was initialize, causing problems.

Title: NodeJS: load html with res.write()

Body:
I'm new to Node so I'm trying to learn it. I'm trying to load a simple HTML file in Node but that gives me an error as HTML is not defined when I use res.write(html) I saw some examples where are similar to me so I would like to understand what is wrong here.
I wrote this:

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    }
});

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    res.write(html);
    res.end();
});

server.listen(port, hostname, () => {
    console.log('Server started on port ' + port);
});

Body:
As Soren pointed out, htmlis not defined when you call to res.write(). Asynchronous can be very convenient but it's a bit difficult to understand when you are a beginner. The best for you is to try to handle the concept of asynchronous tasks. Until then, a solution to your problem would be to use the synchronous version of fs.readFile, fs.readFileSync (docs here), and call it inside the createServer function.

Since readFileSync returns the read stuff synchronously, you could do:

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    var html = fs.readFileSync('./index.html');
    res.write(html);
    res.end();
});

Another option, as I guess you were trying to make, is to initialize the html variable in the callback of readFile.

var html_g; //global html variable
fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    } else {
        html_g = html; //html_g = content_of_index_file;
});

But since this function is asynchrounous, the createServer function could be called before html_g was initialize, causing problems.


问:
PHP CodeIgniter translating special characters
Is there any Helper class available for codeigniter to translate german characters to pass thme in URL?

for example

ä = ae, ü = ue, ß=ss, ö=oe

Thanks in advance.

Body:
PyroCMS has some basic character conversion but it could be improved upon:

if ( ! function_exists('url_title'))
{
    function url_title($str, $separator = 'dash', $lowercase = FALSE)
    {
        $CI =& get_instance();

        $foreign_characters = array(
            '/ä|æ|ǽ/' => 'ae',
            '/ö|œ/' => 'oe',
            '/ü/' => 'ue',
            '/Ä/' => 'Ae',
            '/Ü/' => 'Ue',
            '/Ö/' => 'Oe',
            '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|А/' => 'A',
            '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|а/' => 'a',
            '/Б/' => 'B',
            '/б/' => 'b',
            '/Ç|Ć|Ĉ|Ċ|Č|Ц/' => 'C',
            '/ç|ć|ĉ|ċ|č|ц/' => 'c',
            '/Ð|Ď|Đ|Д/' => 'D',
            '/ð|ď|đ|д/' => 'd',
            '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Е|Ё|Э/' => 'E',
            '/è|é|ê|ë|ē|ĕ|ė|ę|ě|е|ё|э/' => 'e',
            '/Ф/' => 'F',
            '/ф/' => 'f',
            '/Ĝ|Ğ|Ġ|Ģ|Г/' => 'G',
            '/ĝ|ğ|ġ|ģ|г/' => 'g',
            '/Ĥ|Ħ|Х/' => 'H',
            '/ĥ|ħ|х/' => 'h',
            '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|И/' => 'I',
            '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|и/' => 'i',
            '/Ĵ|Й/' => 'J',
            '/ĵ|й/' => 'j',
            '/Ķ|К/' => 'K',
            '/ķ|к/' => 'k',
            '/Ĺ|Ļ|Ľ|Ŀ|Ł|Л/' => 'L',
            '/ĺ|ļ|ľ|ŀ|ł|л/' => 'l',
            '/М/' => 'M',
            '/м/' => 'm',
            '/Ñ|Ń|Ņ|Ň|Н/' => 'N',
            '/ñ|ń|ņ|ň|ŉ|н/' => 'n',
            '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|О/' => 'O',
            '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|о/' => 'o',
            '/П/' => 'P',
            '/п/' => 'p',
            '/Ŕ|Ŗ|Ř|Р/' => 'R',
            '/ŕ|ŗ|ř|р/' => 'r',
            '/Ś|Ŝ|Ş|Š|С/' => 'S',
            '/ś|ŝ|ş|š|ſ|с/' => 's',
            '/Ţ|Ť|Ŧ|Т/' => 'T',
            '/ţ|ť|ŧ|т/' => 't',
            '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|У/' => 'U',
            '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|у/' => 'u',
            '/В/' => 'V',
            '/в/' => 'v',
            '/Ý|Ÿ|Ŷ|Ы/' => 'Y',
            '/ý|ÿ|ŷ|ы/' => 'y',
            '/Ŵ/' => 'W',
            '/ŵ/' => 'w',
            '/Ź|Ż|Ž|З/' => 'Z',
            '/ź|ż|ž|з/' => 'z',
            '/Æ|Ǽ/' => 'AE',
            '/ß/'=> 'ss',
            '/Ĳ/' => 'IJ',
            '/ĳ/' => 'ij',
            '/Œ/' => 'OE',
            '/ƒ/' => 'f',
            '/Ч/' => 'Ch',
            '/ч/' => 'ch',
            '/Ю/' => 'Ju',
            '/ю/' => 'ju',
            '/Я/' => 'Ja',
            '/я/' => 'ja',
            '/Ш/' => 'Sh',
            '/ш/' => 'sh',
            '/Щ/' => 'Shch',
            '/щ/' => 'shch',
            '/Ж/' => 'Zh',
            '/ж/' => 'zh',
        );

        $str = preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str);

        $replace = ($separator == 'dash') ? '-' : '_';

        $trans = array(
            '&\#\d+?;' => '',
            '&\S+?;' => '',
            '\s+' => $replace,
            '[^a-z0-9\-\._]' => '',
            $replace.'+' => $replace,
            $replace.'$' => $replace,
            '^'.$replace => $replace,
            '\.+$' => ''
        );

        $str = strip_tags($str);

        foreach ($trans as $key => $val)
        {
            $str = preg_replace("#".$key."#i", $val, $str);
        }

        if ($lowercase === TRUE)
        {
            if( function_exists('mb_convert_case') )
            {
                $str = mb_convert_case($str, MB_CASE_LOWER, "UTF-8");
            }
            else
            {
                $str = strtolower($str);
            }
        }

        $str = preg_replace('#[^'.$CI->config->item('permitted_uri_chars').']#i', '', $str);

        return trim(stripslashes($str));
    }
}


问:
How to give space between two cells in tableview?
I want a space between two cell in table view,

I want cell like this,

How can i do that?

答:
Here is my method with Swift 3:

In ViewDidLoad(), add:

```<code>self.tableView.rowHeight = 500.0
</code>```

In tableview "CellForRowAt", add following:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    // Configure the cell...
    var actualContentView = UIView()
    actualContentView.frame = CGRect(x: 10, y: 10, width: cell.contentView.frame.width - 20, height: cell.contentView.frame.height - 20)
    actualContentView.backgroundColor = UIColor.blue
    cell.contentView.addSubview(actualContentView)

    return cell
}
</code>```

Body:
Here is my method with Swift 3:

In ViewDidLoad(), add:

self.tableView.rowHeight = 500.0

In tableview "CellForRowAt", add following:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    // Configure the cell...
    var actualContentView = UIView()
    actualContentView.frame = CGRect(x: 10, y: 10, width: cell.contentView.frame.width - 20, height: cell.contentView.frame.height - 20)
    actualContentView.backgroundColor = UIColor.blue
    cell.contentView.addSubview(actualContentView)

    return cell
}


问:
How to Html Input value echo in php
I have made some classes in css and i have a html form and i also have some html elements and i want to echo them by php but i want them to echo by the value of html form submition
For eg

```<code>    <form action="index.php"  method="post">
<select name="slideNumber">
 <option value="3" name="slideNumber">3 Image Slider</option>
<option value="right-3" name="slideNumber">3 Image Right Slider</option>
<option value="4" name="slideNumber">4 Image Slider</option>
<option value="right-4" name="slideNumber">4 Image Right Slider</option>
<!--And more just like this-->
</select>
<input type="submit" value="submit" />
</form>

<?php
 $i= trim($_POST['slideNumber']);
if(($i = '3') || ($i = 'right-3')){
     $x= '3';
}
else if(($i = '4') || ($i = 'right-4')){
     $x= '4';
}
echo "
         <div class=\"slider-".$x."\">
         </div>
";
?>
</code>```

It is showing only first $x
I mean it is showing slider-3 even if i had give the value 4 in form please help me to solve this

答:
Basically the problem is with equality check i.e your if condition </p>

<p>use: </p>

```<code>if ($i === '3' || $i === 'right-3'){
   $x = '3';
} elseif ($i === '4' || $i === 'right-4)) {
   $x = '4';
}
</code>```

Title: How to Html Input value echo in php

Body:
I have made some classes in css and i have a html form and i also have some html elements and i want to echo them by php but i want them to echo by the value of html form submition
For eg

    <form action="index.php"  method="post">
<select name="slideNumber">
 <option value="3" name="slideNumber">3 Image Slider</option>
<option value="right-3" name="slideNumber">3 Image Right Slider</option>
<option value="4" name="slideNumber">4 Image Slider</option>
<option value="right-4" name="slideNumber">4 Image Right Slider</option>

</select>
<input type="submit" value="submit" />
</form>

<?php
 $i= trim($_POST['slideNumber']);
if(($i = '3') || ($i = 'right-3')){
     $x= '3';
}
else if(($i = '4') || ($i = 'right-4')){
     $x= '4';
}
echo "

";
?>

It is showing only first $x
I mean it is showing slider-3 even if i had give the value 4 in form please help me to solve this

Body:
Basically the problem is with equality check i.e your if condition

use:

if ($i === '3' || $i === 'right-3'){
   $x = '3';
} elseif ($i === '4' || $i === 'right-4)) {
   $x = '4';
}


问:
fusioncharts and wkhtmltoimage
I'm trying to export fusionChart Images on the Server Without Rendering in a Browser.. i would like to use the image in tcpdf

i followed the example here
http://www.fusioncharts.com/blog/2013/03/how-to-save-charts-as-images-at-server-side/

```<code>    < ?php
    $webpageURLWithChart = "mychart.php";
    $outputImageFileName = "savedImage.png";
    $delay = 500;
    $shellout = shell_exec("wkhtmltoimage --javascript-delay $delay $webpageURLWithChart $outputImageFileName" );
    echo $shellout;
    ?>
</code>```

mychart.php is working fine but image is not generated

path is set C:\Program Files\wkhtmltopdf

any help is much apreciated

答:
Finally Got it..we have to set the full url for $webpageURLWithChart</p>

```<code>  < ?php
    $webpageURLWithChart = "http://localhost/test/mychart.php";
    $outputImageFileName = "savedImage.png";
    $delay = 500;
    $shellout = shell_exec("wkhtmltoimage --javascript-delay $delay $webpageURLWithChart $outputImageFileName" );
    echo $shellout;
    ?>
</code>```

Title: fusioncharts and wkhtmltoimage

Body:
I'm trying to export fusionChart Images on the Server Without Rendering in a Browser.. i would like to use the image in tcpdf

i followed the example here
http://www.fusioncharts.com/blog/2013/03/how-to-save-charts-as-images-at-server-side/

    < ?php
    $webpageURLWithChart = "mychart.php";
    $outputImageFileName = "savedImage.png";
    $delay = 500;
    $shellout = shell_exec("wkhtmltoimage --javascript-delay $delay $webpageURLWithChart $outputImageFileName" );
    echo $shellout;
    ?>

mychart.php is working fine but image is not generated

path is set C:\Program Files\wkhtmltopdf

any help is much apreciated

Body:
Finally Got it..we have to set the full url for $webpageURLWithChart

  < ?php
    $webpageURLWithChart = "http://localhost/test/mychart.php";
    $outputImageFileName = "savedImage.png";
    $delay = 500;
    $shellout = shell_exec("wkhtmltoimage --javascript-delay $delay $webpageURLWithChart $outputImageFileName" );
    echo $shellout;
    ?>


问:
Arrange % in google sheets
I am looking for some help with two small problems I have. I have made a small stock portfolio spreadsheet, which the link is: Link to spreadsheet
I am trying to show the gap difference in % of stocks in real time using google finance. Column’s 6 -10, are the correct %, but showing up as a -%. Is there any way to show the % without the -?

In addition, how can I sort the spreadsheet to show lowest % at the top, highest at the bottom?
For example, I would like the spreadsheet to show:

FL 49.98 50.33 short 0.70%

MDZL 43.22 42.50 long 1.67%

STX 38.20 37.44 long 1.99%

WR 53.13 54.47 short 2.52%

答: To sort, select columns A-F. Select Data from the menu. From the dropdown select Sort Range. Click Data has header row. In Sort by, select column F, A-Z. Click Sort. That should do it. I don't understand "Is there any way to show the % without the -?"</p>

Title: Arrange % in google sheets


问:
ReactJS: Uncaught ReferenceError: [function] not defined, July 2017
Attempting to turn a JSON file into an array, then randomly selecting 5 items from it.

I think the issue is my render/return statement at the bottom of ImageContainer.js, but I'm a ReactJS n00b, so it could be anything.

Any help or advice is greatly appreciated.

Console Error

```<code>compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)
</code>```

ImageContainer.js - pulls img info from a .JSON file, randomly selects 5 to render

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}
</code>```

Image.js - just the image HTML

```<code>import React from 'react';

export class Image extends React.Component {
    render() {
        const key = this.props.id;
        const name = this.props.name;
        const src = this.props.src;
        return (
            <picture>
                <img id="pic-template" className="pic" src="{src}" name="{name}" key="id" />
            </picture>
        );
    }
}
</code>```

[Main].js - most of the HTML is here, just including the import bits

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { ImageContainer } from './ImageContainer';

export default class NameGame extends React.Component {
  render () {
    return (
      ...
      <div id="images-wrap">
          <ImageContainer />
      </div>
      ...
    );
  }
}
</code>```

Dependencies

```<code>{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}
</code>```

答:
Here is the updated (mostly) working version of ImageContainer.js, which incorporates Danillo's changes and solves the array problem that followed. The issues were mainly related to missing "this." and "this.state."

ImageContainer.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);

        this.numImages = 5;

        this.state = {
          data: []
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    shuffleArray(array) {
      let i = array.length - 1;
      for (; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    }

    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data);
      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}
</code>```

Body:
Attempting to turn a JSON file into an array, then randomly selecting 5 items from it.

I think the issue is my render/return statement at the bottom of ImageContainer.js, but I'm a ReactJS n00b, so it could be anything.

Any help or advice is greatly appreciated.

Console Error

compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)

ImageContainer.js - pulls img info from a .JSON file, randomly selects 5 to render

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}

Image.js - just the image HTML

import React from 'react';

export class Image extends React.Component {
    render() {
        const key = this.props.id;
        const name = this.props.name;
        const src = this.props.src;
        return (
            <picture>

            </picture>
        );
    }
}

[Main].js - most of the HTML is here, just including the import bits

import React from 'react';
import ReactDOM from 'react-dom';
import { ImageContainer } from './ImageContainer';

export default class NameGame extends React.Component {
  render () {
    return (
      ...

          <ImageContainer />

      ...
    );
  }
}

Dependencies

{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}

Body:
Here is the updated (mostly) working version of ImageContainer.js, which incorporates Danillo's changes and solves the array problem that followed. The issues were mainly related to missing "this." and "this.state."

ImageContainer.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);

        this.numImages = 5;

        this.state = {
          data: []
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    shuffleArray(array) {
      let i = array.length - 1;
      for (; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    }

    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data);
      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}


问:
Qt Creator - Add keyboard shortcuts to Menu entries
I created the shortcut events, such as:

```<code>new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));
</code>```

But now I would like to show "Ctrl+Q" in the menu entry here:

How do I do that? I don't seem to find a way to do that in Qt Creator.

答:
You can set the shortcut keys in the QtDesigner in the 'Action Editor' (Tab at the bottom, the 'Signal/Slot Editor' tab is selected by default).

Here all defined QActions are listed. A double click on a field in the 'shortcut' column will open the wanted dialog.

This will add the shortcut to the QAction (create triggered events) and set it as visibile text, e.g. in the menu entry (only visible in the application, not in QtDesigner).

In the 'Property Editor' are more options for the 'shortcuts' (e.g. make them translatable).

Body:
I created the shortcut events, such as:

new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));

But now I would like to show "Ctrl+Q" in the menu entry here:

How do I do that? I don't seem to find a way to do that in Qt Creator.


问:
Formula in worksheet and VBA works differently
Cell A1 contains the number 25, which is right-aligned, implying it's a number, not text.

D1 contains the formula:

="" & A1

The 25 in D1 is left-aligned, implying it's text. That is confirmed by the following formula, which returns 1:

=IF(D1="25",1,0)

The following VBA code puts 25 in F1 but the 25 is right-aligned and the IF test returns 0:

```<code>Range("F1") = "" & Range("A1")
</code>```

Any explanation for the discrepancy?

E1 contains the following formula which gives a left-aligned 25 and the IF test returns 1:

TEXT(A1,"0")

However, the following code gives a right-aligned 25 and the IF test returns 0:

```<code>Range("F1") = Application.WorksheetFunction.Text(Range("A1"), "0")
</code>```

Not that I have to use the TEXT function. I just wonder why it works differently than when in a worksheet.

Any rule that tells when or what worksheet functions won't work in VBA code, or more precisely, will give different results than when in worksheet?

答:
When a data is written by vba into a cell, an internal type conversion function is called if required, that is if the data type is different from the cell's numberformat property.

You dont want that conversion function to be called.

To avoid this conversion function to be called, choose the proper Numberformat property for the cell before writing the data.

```<code>Range("b4").NumberFormat = "@"
Range("b4") = Application.WorksheetFunction.Text(Range("A1"), "0")
</code>```

Body:
Cell A1 contains the number 25, which is right-aligned, implying it's a number, not text.

D1 contains the formula:

="" & A1

The 25 in D1 is left-aligned, implying it's text. That is confirmed by the following formula, which returns 1:

=IF(D1="25",1,0)

The following VBA code puts 25 in F1 but the 25 is right-aligned and the IF test returns 0:

Range("F1") = "" & Range("A1")

Any explanation for the discrepancy?

E1 contains the following formula which gives a left-aligned 25 and the IF test returns 1:

TEXT(A1,"0")

However, the following code gives a right-aligned 25 and the IF test returns 0:

Range("F1") = Application.WorksheetFunction.Text(Range("A1"), "0")

Not that I have to use the TEXT function. I just wonder why it works differently than when in a worksheet.

Any rule that tells when or what worksheet functions won't work in VBA code, or more precisely, will give different results than when in worksheet?

Body:
When a data is written by vba into a cell, an internal type conversion function is called if required, that is if the data type is different from the cell's numberformat property.

You dont want that conversion function to be called.

To avoid this conversion function to be called, choose the proper Numberformat property for the cell before writing the data.

Range("b4").NumberFormat = "@"
Range("b4") = Application.WorksheetFunction.Text(Range("A1"), "0")


问:
How to write for .net 3.5 in Visual Studio 2010
I have an ASP MVC 2 project, originally written in VS 2008 but now upgraded to VS 2010.  I want, however, to remain with .net 3.5 since the production environment does not always have .net 4 installed yet.  I thought this was possible.  When I upgraded the project I answered no to the question about upgrading the .net framework version.  I have checked and .net 3.5 is set as the target framework in the advanced compile options for the project.

My problem is that I can write code which builds and runs fine in VS but which doesn't work in a .net 3.5 environment.  For example, I added a function with an optional paramater of type Integer? (nullable integer).  This appears to be allowed in 4 but not in 3.5?  Anyway, works fine in VS 2010.  However, when I try to build and deploy I run into one of two problems.  (We use custom build/deploy scripts - build uses msbuild on a separate build server.)

Porblem 1 is if i try to use the 3.5 version of msbuild.  Then the build fails with message "error BC31405: Optional parameters cannot have structure types.".

Problem 2 is if I try to use the .net 4 version of msbuild on the build server (remember that the target framework is still 3.5, the only change is which msbuild executable the build script uses).  In this case it builds, but when I try to run the site on a server which has 3.5 but not .net 4 installed I get the error "Could not load file or assembly 'ProjectName.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded."

According to MSDN (http://msdn.microsoft.com/en-us/library/bb398202.aspx) all I need to do is make sure the target framework is right (and the references, but there doesn't seem to be a problem there in that it builds fine against 3.5 as long as I avoid certain syntaxes, etc.)

The problem is that I get no error in VS to tell me there could be a problem if I use those structures which won't build.  Accoridng to the Visual Studio Multi-Targeting Overview article on MSDN (http://msdn.microsoft.com/en-us/library/bb398197.aspx) "when you work on a project that targets an earlier version of the .NET Framework, Visual Studio dynamically makes changes in the development environment, such as the following ... It compiles and builds with the appropriate version of the compiler and with the appropriate compiler options"  So why does it compile in VS but not with msbuild?

I wondered if it was the toolset property that was the problem (if I specify /tv:3.5 on the command line to msbuild 4 I get the same build errors as with msbuild 3.5).  According to the MSBuild Multitargeting article (http://msdn.microsoft.com/en-us/library/ee395432.aspx) "You designate the tool set by setting the ToolsVersion attribute of the Project element of a project file".  However, if I change the ToolsVersion="4.0" to ToolsVersion="3.5" in the .vbproj file then the Visual Studio Conversion Wizard pops up when i try to reload the proejct.

So, how can I either:

A - Get VS 2010 to accept that it's a .net 3.5 project and use the appropraite background compiler and therefore show me errors during development (before it gets to the build server)?

or

B - Build the project is such a way (with msbuild 4 for example) that it will build but still run in a .net 3.5 only environment?

答:
Seems like you are trying to use C# 4.0 Language Features in a .Net Framework 3.5 application.

Refrain from using new features introduced in C# 4.0 such as:

Optional parameters

Dynamic Programming

Covariance/Contravariance

And others listed here.

And you should be fine.


问:
Range Selection in Matlab
I defined a matrix 6 by 6 and want to make a change in values in some ranges.

```<code>c = floor(rand(6,6) * 100)
</code>```

the result:

```<code>22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40
</code>```

then I run:

```<code>c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40
</code>```

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

答:
Here is another approach that multiplies the matrix with a logical mask:</p>

```<code>c(1:3,:) = c(1:3,:) .* c(1:3,:) >= 17;
</code>```

Title: Range Selection in Matlab

Body:
I defined a matrix 6 by 6 and want to make a change in values in some ranges.

c = floor(rand(6,6) * 100)

the result:

22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40

then I run:

c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

Body:
Here is another approach that multiplies the matrix with a logical mask:

c(1:3,:) = c(1:3,:) .* c(1:3,:) >= 17;


问:
Android Studio: Gradle 'project_name' project refresh failed
I recently downloaded and installed the latest version of Android Studio Bundle 2.3.3. I get a Gradle 'project_name' project refresh failed error {Error:Could not download jsr305.jar (com.google.code.findbugs:jsr305:2.0.1): No cached version available for offline mode} every time I load up the IDE. I have a constant internet connection and I even have downloaded jsr305.jar and placed it in the gradle directory in the Android Studio program files, but the problem still persist. I have not yet started coding or developing the layout yet.Screenshot of the error</p>

答:
In your app's build.gradle file add the following:(use latest version)

```<code>android {
configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
    }
}
</code>```

Body:
In your app's build.gradle file add the following:(use latest version)

android {
configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
    }
}


问:
javascript alert TypeError
In the following javascript code,

```<code>        needSubIdCheck = $("#needSubIdCheck").text();
        liveSupplierCount = $("#liveSupplierCount").text();
        subIdCount = $("#subIdCount").text();

         if(needSubIdCheck == 'true')
         {
          if( liveSupplierCount > subIdCount  )
          {
              alert("subIDS Needs to be assigned");
            return false;
          }
        }
</code>```

The above code gives, "Uncaught TypeError: alert is not a function" in the console. If I change the alert with window.confirm or console.log everything is fine. Can anyone help me to come out of this problem?

答: Nothing is wrong in the given code. Can you check if you are using any pop-up-blockers, this could happen some times. Also check if you have override the alert (var alert = ...,window.alert) some were in the code. This could happen if you are using some external js files as well. For the time being comment out external js files and check if alert is working

Title: javascript alert TypeError

Body:
In the following javascript code,

        needSubIdCheck = $("#needSubIdCheck").text();
        liveSupplierCount = $("#liveSupplierCount").text();
        subIdCount = $("#subIdCount").text();

         if(needSubIdCheck == 'true')
         {
          if( liveSupplierCount > subIdCount  )
          {
              alert("subIDS Needs to be assigned");
            return false;
          }
        }

The above code gives, "Uncaught TypeError: alert is not a function" in the console. If I change the alert with window.confirm or console.log everything is fine. Can anyone help me to come out of this problem?


问:
my bundle.js doesn't seem to be created
I am building a simple app with the use of webpack to combine all my modules. My webpack seem to be running (although, I have battled its not-working).
Now it looks like a bundle.js necessary to see my app cannot be found. I get this error:

the error

So here are my files that might cause the issue

the config.webpack.js file

my packageJSON

```<code>{
 "name": "quiz",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "mocha specs"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "mocha": "^3.4.2",
   "webpack": "1.12.15"
 }
}
</code>```

and the html file that looks for the bundle.js file

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quiz game</title>
</head>
<body>
    <script src = "build.js "></script>
    <div>
    Quiz game
    </div>
</body>
</html>
</code>```

Any ideas on what might be wrong?

答:
Your problem is the build.js path to the file.

You're missing just a small part.

Try this:
Place a / in your src right before your "build.js"

Title: my bundle.js doesn't seem to be created

Body:
I am building a simple app with the use of webpack to combine all my modules. My webpack seem to be running (although, I have battled its not-working).
Now it looks like a bundle.js necessary to see my app cannot be found. I get this error:

the error

So here are my files that might cause the issue

the config.webpack.js file

my packageJSON

{
 "name": "quiz",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "mocha specs"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "mocha": "^3.4.2",
   "webpack": "1.12.15"
 }
}

and the html file that looks for the bundle.js file

<!DOCTYPE html>

    <title>Quiz game</title>

    Quiz game

Any ideas on what might be wrong?


问:
Googletest: How to run tests asynchronously?
Given a large project with thousands of tests, some of which take multiple minutes to complete. When executed sequentially, the whole set of test takes more than an hour to finish. The testing time could be reduced by executing tests in parallel.

As far as I know there are no means to do that directly from googletest/mock, like a --async option. Or am I wrong?

One solution is to determine the tests which can run in parallel and write a script that starts each in a separate job, i.e.

```<code>./test --gtest_filter=TestSet.test1 &
./test --gtest_filter=TestSet.test2 &
...
</code>```

But this would require additional maintenance effort and introduce another "layer" between the test code and its execution. I'd like a more convenient solution. For example, one could suffix the TEST and TEST_F macros and introduce TEST_ASYNC, TEST_F_ASYNC. Tests defined with TEST_ASYNC would then be executed by independent threads, starting at the same time.

How can this be achieved? Or is there another solution?

答:
Late response, but I'll put it here for anyone searching for a similar answer. Working on WebRTC I found a similar need to speed up our test execution. Executing all of our tests sequentially took more than 20 minutes, and a bunch of them spend at least some time waiting (so they don't even fully utilize a core).

Even for "proper unit tests" I'd argue this is still relevant, because there's a difference between your single-threaded tests taking 20 seconds and ~1 second to execute (if your workstation is massively parallel, this speedup is not uncommon).

To solve this for us, I developed a script that test executes tests in parallel. This is stable enough to run on our continuous integration, and released here: https://github.com/google/gtest-parallel/

This python script essentially takes --gtest_filter=Foo (which you can specify) of one or more gtest binary specified, splits them up on several workers and runs individual tests in parallel. This works fine so long as the tests are independent (don't write to shared files, etc). For tests that didn't work fine, we put them in a webrtc_nonparallel_tests binary and ran those separately, but the vast majority were already fine, and we fixed several of them because we wanted the speedup.

Body:
Given a large project with thousands of tests, some of which take multiple minutes to complete. When executed sequentially, the whole set of test takes more than an hour to finish. The testing time could be reduced by executing tests in parallel.

As far as I know there are no means to do that directly from googletest/mock, like a --async option. Or am I wrong?

One solution is to determine the tests which can run in parallel and write a script that starts each in a separate job, i.e.

./test --gtest_filter=TestSet.test1 &
./test --gtest_filter=TestSet.test2 &
...

But this would require additional maintenance effort and introduce another "layer" between the test code and its execution. I'd like a more convenient solution. For example, one could suffix the TEST and TEST_F macros and introduce TEST_ASYNC, TEST_F_ASYNC. Tests defined with TEST_ASYNC would then be executed by independent threads, starting at the same time.

How can this be achieved? Or is there another solution?