问:
Just recieve one Dataobject from JSON
i try to get Map Markers from JSON into a MapActivity.
i just get the first one from the JSON the others arent shown in my map.
how can i solve my problem.
Here is my Map Activity:

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private ProgressDialog pDialog;
private GoogleMap mMap;
private static String url="http://partypeople.bplaced.net/markers.json";
ArrayList<HashMap<String, String>> contactList;
private String TAG = MainActivity.class.getSimpleName();
double latitude;
double longitude;
String namec;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    contactList = new ArrayList<>();
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map3);
    mapFragment.getMapAsync(this);

}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray contacts = jsonObj.getJSONArray("markers");

                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString("id");
                    String name = c.getString("name");
                    String address = c.getString("address");
                    String lat = c.getString("lat");
                    String lng = c.getString("lng");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("id", id);
                    contact.put("name", name);
                    contact.put("address",address);
                    contact.put("lat", lat);
                    contact.put("lng", lng);

                    latitude = Double.parseDouble(lat); longitude = Double.parseDouble(lng);
                    contactList.add(contact);
                    namec = name;

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

            LatLng P1 = new LatLng(latitude, longitude);

            mMap.addMarker(new MarkerOptions().position(P1).title(namec));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(P1));

    }

}
@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;
    new GetContacts().execute();
    mMap.setMyLocationEnabled(true);

}
</code>```

}

and here is my JSON:

```<code>{
"markers": [

    {
            "id": "c201",
            "name": "Munic",
            "address": "try",
            "lat": "48.142281",
            "lng" : "11.550613"

    },
   {
            "id": "c205",
            "name": "Berlin",
            "address": "test",
            "lat": "43.142281",
            "lng" : "11.550613"

    }
</code>```

]
}

and here is my httpHandler:

public class HttpHandler {

```<code>private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
</code>```

}

答:
Your problem is in onPostExecute, you add only one marker to map.
You should use your contactList there:</p>

```<code>for (HashMap<String, String> contact: contactList) {
    LatLng P1 = new LatLng(
                    Double.parseDouble(contact.get("lat")),
                    Double.parseDouble(contact.get("lng")));

    mMap.addMarker(new MarkerOptions().position(P1).title(contact.get("name")));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(P1));
}
</code>```

Title: Just recieve one Dataobject from JSON

Body:
i try to get Map Markers from JSON into a MapActivity.
i just get the first one from the JSON the others arent shown in my map.
how can i solve my problem.
Here is my Map Activity:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private ProgressDialog pDialog;
private GoogleMap mMap;
private static String url="http://partypeople.bplaced.net/markers.json";
ArrayList<HashMap<String, String>> contactList;
private String TAG = MainActivity.class.getSimpleName();
double latitude;
double longitude;
String namec;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    contactList = new ArrayList<>();
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map3);
    mapFragment.getMapAsync(this);

}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray contacts = jsonObj.getJSONArray("markers");

                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString("id");
                    String name = c.getString("name");
                    String address = c.getString("address");
                    String lat = c.getString("lat");
                    String lng = c.getString("lng");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("id", id);
                    contact.put("name", name);
                    contact.put("address",address);
                    contact.put("lat", lat);
                    contact.put("lng", lng);

                    latitude = Double.parseDouble(lat); longitude = Double.parseDouble(lng);
                    contactList.add(contact);
                    namec = name;

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

            LatLng P1 = new LatLng(latitude, longitude);

            mMap.addMarker(new MarkerOptions().position(P1).title(namec));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(P1));

    }

}
@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;
    new GetContacts().execute();
    mMap.setMyLocationEnabled(true);

}

}

and here is my JSON:

{
"markers": [

    {
            "id": "c201",
            "name": "Munic",
            "address": "try",
            "lat": "48.142281",
            "lng" : "11.550613"

    },
   {
            "id": "c205",
            "name": "Berlin",
            "address": "test",
            "lat": "43.142281",
            "lng" : "11.550613"

    }

]
}

and here is my httpHandler:

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

Body:
Your problem is in onPostExecute, you add only one marker to map.
You should use your contactList there:

for (HashMap<String, String> contact: contactList) {
    LatLng P1 = new LatLng(
                    Double.parseDouble(contact.get("lat")),
                    Double.parseDouble(contact.get("lng")));

    mMap.addMarker(new MarkerOptions().position(P1).title(contact.get("name")));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(P1));
}


来源: stackexchange

问:
How to read this php code: $input = JFactory::getApplication()->input;
I get confuse reading this php line of code:

```<code>$input = JFactory::getApplication()->input;
</code>```

As I understand this is a declaration for $input variable.
Can anyone help to explain the right part of the declaration?

答:
The line of code you are referring to is Joomla's way of reading GET/POST/COOKIE parameters.

```<code>$input = JFactory::getApplication()->input;
</code>```

Let's say you want to get all data received in $_POST. You would do something like:

```<code>$input = JFactory::getApplication()->input;
$post_array = $input->getArray($_POST);
</code>```

If you var_dump($post_array), you should see the data.

If you want to get specific keys from $_GET, $_POST etc, you would do something like this:

```<code>// GET specific dataset
JFactory::getApplication()->input->get->get('username');

// POST specific dataset
JFactory::getApplication()->input->post->get('username');

// COOKIE specific dataset
JFactory::getApplication()->input->cookie->get('usermane');
</code>```

Now let's get into the meaning of the right hand side:

```<code>$input = JFactory::getApplication()->input;
</code>```

Jfactory is actually the class name. It is called factory because the code architecture for this class is using the Factory design pattern.

In fact, JFactory is the Joomla Platform class, it gives you access to the most important parts in Joomla like the application one or the Joomla global configuration.

getApplicationis the method name within the class Jfactory. The fact that it is reference with :: this means that this method is static.

The input is an attribute of the class Jfactory.

You can find more information about the Jfactory class from Joomla documentation.

ContentLicense: CC BY-SA 3.0

Body:
I get confuse reading this php line of code:

$input = JFactory::getApplication()->input;

As I understand this is a declaration for $input variable.
Can anyone help to explain the right part of the declaration?

Body:
The line of code you are referring to is Joomla's way of reading GET/POST/COOKIE parameters.

$input = JFactory::getApplication()->input;

Let's say you want to get all data received in $_POST. You would do something like:

$input = JFactory::getApplication()->input;
$post_array = $input->getArray($_POST);

If you var_dump($post_array), you should see the data.

If you want to get specific keys from $_GET, $_POST etc, you would do something like this:

// GET specific dataset
JFactory::getApplication()->input->get->get('username');

// POST specific dataset
JFactory::getApplication()->input->post->get('username');

// COOKIE specific dataset
JFactory::getApplication()->input->cookie->get('usermane');

Now let's get into the meaning of the right hand side:

$input = JFactory::getApplication()->input;

Jfactory is actually the class name. It is called factory because the code architecture for this class is using the Factory design pattern.

In fact, JFactory is the Joomla Platform class, it gives you access to the most important parts in Joomla like the application one or the Joomla global configuration.

getApplicationis the method name within the class Jfactory. The fact that it is reference with :: this means that this method is static.

The input is an attribute of the class Jfactory.

You can find more information about the Jfactory class from Joomla documentation.


问:
Does multipart/x-mixed-replace wait for client requests?
I'm trying to figure out if it's possible to slow down the server when it's sending multipart/xmixed-replace responses.  I want my client to try to rate limit a motion jpeg stream.  I've found a lot of documentation about what the server sends in an HTTP response but nothing about what the client sends.

What does the client send, if anything, after each part in a multipart/x-mixed-replace response?  If it doesn't send anything, does the server just keep piling on the parts?

答:
At the HTTP level I dont think the client sends anything. The server assumes that as long as the connection is open it can keep sending the response.

I dont think there is an easy HTTP-level solution to the problem because there is no "ack" concept in the client-server exchange.

There are obviously TCP-/IP level solutions to this problem.

I am wondering if the client can do something differently when it actually receives the server's response headers and recognizes that the response is multipart - whether it can then abort the connect and open a new non-keep alive one and just get the parts one by one...

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Anshu


问:
Best way to disable entire form on PHP condition?
I have a site (like many). I want to show but disable a particular form based on whether they are logged in or not. The way I show if the user is logged in is via a cookie set by PHP. What I'm wondering is the best way to disable all the elements in the form when the user is not logged in.

The solution I have at the moment is to get PHP to echo some JavaScript (jQuery to be precise) to the page:

```
$("#form_name").children("input, textarea").attr("disabled", "disabled");
```

Is this the right way to go, or is there a better way to be doing things?

答: If you have the cookie set when PHP generates your page, just set the disabled attribute on the HTML element without Javascript. Then, if you have an ajaxy login form, you can parse the login response and enable the form based on that. If the login isn't ajaxy, PHP should set the cookie for you and build the page appropriately.</p>

Body:
I have a site (like many). I want to show but disable a particular form based on whether they are logged in or not. The way I show if the user is logged in is via a cookie set by PHP. What I'm wondering is the best way to disable all the elements in the form when the user is not logged in.

The solution I have at the moment is to get PHP to echo some JavaScript (jQuery to be precise) to the page:

$("#form_name").children("input, textarea").attr("disabled", "disabled");

Is this the right way to go, or is there a better way to be doing things?


问:
Crontab won't execute my script which executes manually
I have a bash script that needs to be executed everyday at 9:30pm. its called fetchIND.sh and I've made the entry for that in my tab with specifying the shell and path parameters as follows. It is supposed to fetch files off another server with sftp and works just fine manually. However, with crontab is doesn't execute.

My crontab entry :

06 21 * * * root /usr/bin/bash /root/IND/fetchIND.sh

results after 'ps aux | grep bash' command:

root      5815  0.0  0.0   8984   808 pts/0    S+   21:06   0:00 grep --color=auto bash

However, my script doesn't actually execute. Any help regarding this would be great. Thanks!!

答:
(Edited out a suggestion to check syntax -- this seems to be valid for CentOS. Leaving other suggestions, added details. -- sorry I have not enough karma to comment, hehe)

Your script might depend on things that are different when invoked by cron daemon: environment variables that you might have altered in your shell, access to a tty, etc.

You can debug it by appending a redirection:

```<code>06 21 * * * root /usr/bin/bash /root/IND/fetchIND.sh 2>&1 >> /tmp/trace_when_running_from_crontab.log
</code>```

Body:
(Edited out a suggestion to check syntax -- this seems to be valid for CentOS. Leaving other suggestions, added details. -- sorry I have not enough karma to comment, hehe)

Your script might depend on things that are different when invoked by cron daemon: environment variables that you might have altered in your shell, access to a tty, etc.

You can debug it by appending a redirection:

06 21 * * * root /usr/bin/bash /root/IND/fetchIND.sh 2>&1 >> /tmp/trace_when_running_from_crontab.log


问:
for loop with setTimeout prints number to console
I read about closures and find this code.

```<code>for(i=0;i<5;i++){
    setTimeout(function(){
        console.log(i);
    },2000)
}
</code>```

This outputs 5 number 5 times after 2 second. I understand this but before five appears there is number above him. And when I execute again this code it changes it adds 5 to his old value. What is it? Write code on console, see what it outputs then explain me what is it?

答:
It's the "result" value of the evaluated statement, which for a loop is the result value of the last statement in the loop body, which is the return value of the setTimeout call. And that returns a timer id (which allows you to cancel the timeout).

You also can see this behaviour with more simple statements:

```<code>> 0;
< 0
> console.log(1);
  1  // the output of the log()
< undefined
> var i=2;
< undefined // a declaration has no result
> var i=3; i;
< 3
> for (;i<3;i++) 4;
< undefined // the body was not evaluated
> for (;i<4;i++) 5;
< 5
</code>```

Notice how the leading arrow represents input and result output.

Body:
I read about closures and find this code.

for(i=0;i<5;i++){
    setTimeout(function(){
        console.log(i);
    },2000)
}

This outputs 5 number 5 times after 2 second. I understand this but before five appears there is number above him. And when I execute again this code it changes it adds 5 to his old value. What is it? Write code on console, see what it outputs then explain me what is it?

Body:
It's the "result" value of the evaluated statement, which for a loop is the result value of the last statement in the loop body, which is the return value of the setTimeout call. And that returns a timer id (which allows you to cancel the timeout).

You also can see this behaviour with more simple statements:

> 0;
< 0
> console.log(1);
  1  // the output of the log()
< undefined
> var i=2;
< undefined // a declaration has no result
> var i=3; i;
< 3
> for (;i<3;i++) 4;
< undefined // the body was not evaluated
> for (;i<4;i++) 5;
< 5

Notice how the leading arrow represents input and result output.


问:
Flask mysql query = query % self._escape_args(args, conn) TypeError: not all arguments converted during string formatting
I tried almost everything to make my first flask task work on cloud9 but still gives me this error

```<code>cursor.execute('''INSERT INTO studentmaster
                       (Student_Id,Student_FirstName,Student_LastName,
                        Course_Id,Gender,Residential_Address,
                        PhoneNo,Email,Password)
                  VALUES (%s,%s,%s,%s,%s,%s,%s)''',
               (stid,firstname, lastname, coursename, gender, address,
                phone, email,password))
</code>```

here is the link to my app
https://ide.c9.io/hunteelar/studentregistration#openfile-README.md

答:
you have 9 column in table name 9 var in values but only 7 %s in values ( %s......%s)</p>

```<code>cursor.execute('INSERT INTO studentmaster
  (Student_Id,Student_FirstName,Student_LastName,Course_Id,Gender,Residential_Address,PhoneNo,Email,Password)
  VALUES (%s,%s,%s,%s,%s,%s,%s)',
  (stid,firstname, lastname, coursename, gender, address,phone, email,password))
</code>```

Body:
I tried almost everything to make my first flask task work on cloud9 but still gives me this error

cursor.execute('''INSERT INTO studentmaster
                       (Student_Id,Student_FirstName,Student_LastName,
                        Course_Id,Gender,Residential_Address,
                        PhoneNo,Email,Password)
                  VALUES (%s,%s,%s,%s,%s,%s,%s)''',
               (stid,firstname, lastname, coursename, gender, address,
                phone, email,password))

here is the link to my app
https://ide.c9.io/hunteelar/studentregistration#openfile-README.md

Body:
you have 9 column in table name 9 var in values but only 7 %s in values ( %s......%s)

cursor.execute('INSERT INTO studentmaster
  (Student_Id,Student_FirstName,Student_LastName,Course_Id,Gender,Residential_Address,PhoneNo,Email,Password)
  VALUES (%s,%s,%s,%s,%s,%s,%s)',
  (stid,firstname, lastname, coursename, gender, address,phone, email,password))


问:
Angular: change form dynamically as per the selection
I am quite new to Angular. I would like to change form dynamically as per the selection from select box.

```<code><form name="register" method="post" id="register" role="form" ng-submit="registerForm()">
<div class="form-group" ng-class="{ 'has-error' : erroractype }">
        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
<span class="help-block" ng-show="errorName" class="ng-cloak">{{ erroractype }}</span>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorFname }">

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">
<div class = "alert alert-danger" ng-show="errorFname" class="ng-cloak">{{errorFname}}</div>

</div>

<div class="form-group" ng-class="{ 'has-error' : errorLname }">
<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">
<div class = "alert alert-danger" ng-show="errorLname" class="ng-cloak">{{ errorLname }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorEmail1 }">
<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">
<div class = "alert alert-danger" ng-show="errorEmail1" class="ng-cloak">{{ errorEmail1 }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorPassword1 }">
<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">
<div class = "alert alert-danger" ng-show="errorPassword1" class="ng-cloak">{{ errorPassword1 }}</div>
{{ errorPassword1 }}
</div>

<div class="form-group" ng-class="{ 'has-error' : errormobile }">
    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">
    <div class = "alert alert-danger" ng-show="errormobile" class="ng-cloak">{{ errormobile }}</div>
 </div>

<div class="form-group">
<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>
</div>
</form>
</code>```

As you can see three types of registration can be done as per the selection in select box. Student, Teacher and School.

For Student and Teacher form is looking fine. They would have first name & last name. But when people select school that time first name last name looks ugly. It should be only school with single textbox.

So, basically I want whenever school get selected lastname text box get hidden and First Name textbox become Name of School. How can I achieve that?

答:
Okay I came up with something like this. When You'll select the option One you'll see the changes you require. Here is a link to the working example: http://codepen.io/ayushgp/pen/BWMjgG

HTML code:

```<code><body ng-app="example">
  <div ng-controller="test">
    <select name="number" ng-model="type">
      <option value="0" selected>--Select an option--</option>
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>
    <div>
      {{type == 1 ? 'Name of school' : 'First Name'}}:   <input type="text" />
    </div>
    <div ng-style="{'display':type==1?'none':'block'}">
      Last name: <input type="text" />
    </div>
  </div>
</body>
</code>```

Body:
I am quite new to Angular. I would like to change form dynamically as per the selection from select box.

<form name="register" method="post" id="register" role="form" ng-submit="registerForm()">

        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
{{ erroractype }}

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">

{{errorFname}}

<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">

{{ errorLname }}

<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">

{{ errorEmail1 }}

<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">

{{ errorPassword1 }}

{{ errorPassword1 }}

    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">

{{ errormobile }}

<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>

</form>

As you can see three types of registration can be done as per the selection in select box. Student, Teacher and School.

For Student and Teacher form is looking fine. They would have first name & last name. But when people select school that time first name last name looks ugly. It should be only school with single textbox.

So, basically I want whenever school get selected lastname text box get hidden and First Name textbox become Name of School. How can I achieve that?

Body:
Okay I came up with something like this. When You'll select the option One you'll see the changes you require. Here is a link to the working example: http://codepen.io/ayushgp/pen/BWMjgG

HTML code:

<body ng-app="example">
  <div ng-controller="test">
    <select name="number" ng-model="type">
      <option value="0" selected>--Select an option--</option>
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>
    <div>
      {{type == 1 ? 'Name of school' : 'First Name'}}:   <input type="text" />
    </div>
    <div ng-style="{'display':type==1?'none':'block'}">
      Last name: <input type="text" />
    </div>
  </div>
</body>


问:
How to make a public variable in a method
I can't really find a way to do this. If I try to make a public variable it says that its an illegal modifier and that only final is allowed.</p>

答:
You cannot use public modifiers or any modifiers in the methods. The variables defined in the method are always local to that method.

For example:

```<code>public class MyClass{
    private String myVar1; //available within this class definition.

    public void myMehtod(){
      String myVar2; //local to myMethod()
    }
}
</code>```

Body:
You cannot use public modifiers or any modifiers in the methods. The variables defined in the method are always local to that method.

For example:

public class MyClass{
    private String myVar1; //available within this class definition.

    public void myMehtod(){
      String myVar2; //local to myMethod()
    }
}


问:
How to allow all file to accessible from uploads folder through .htaccess setting
I have root directory with files

```<code> - api.php
 - .htaccess
 - uploads/
 - uploads/abc.jpg
 - uploads/xyz.jpg
</code>```

I'm writing rest API for the mobile developer ,so I have successfully created number of API listed below

api.php

```<code>function register(){
    //POST Method
    //I can access this API with URL http://example.com/register
}

function login(){
    //POST Method
    //I can access this API with URL http://example.com/login
}

function user(){
    //GET Method
    //I can access this API with URL http://example.com/user
}
</code>```

Now the problem is what user profile image is store in the upload directory i.e (ab.jpg,xyz.jpg) and I can not access it using http://example.com/uploads/abc.jpg

I figure out it is due to .htaccess file which I have placed in the root level directory and code inside this file is :

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ api.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>
</code>```

I don't know how I can allow uploads folder to access it publicly using .htaccess

答:
Hope this will work. Just add this line to each redirection.

RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$

Check .htaccess here

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ api.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$
    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>
</code>```

Body:
I have root directory with files

 - api.php
 - .htaccess
 - uploads/
 - uploads/abc.jpg
 - uploads/xyz.jpg

I'm writing rest API for the mobile developer ,so I have successfully created number of API listed below

api.php

function register(){
    //POST Method
    //I can access this API with URL http://example.com/register
}

function login(){
    //POST Method
    //I can access this API with URL http://example.com/login
}

function user(){
    //GET Method
    //I can access this API with URL http://example.com/user
}

Now the problem is what user profile image is store in the upload directory i.e (ab.jpg,xyz.jpg) and I can not access it using http://example.com/uploads/abc.jpg

I figure out it is due to .htaccess file which I have placed in the root level directory and code inside this file is :

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ api.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

I don't know how I can allow uploads folder to access it publicly using .htaccess

Body:
Hope this will work. Just add this line to each redirection.

RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$

Check .htaccess here

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ api.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} !\.(jpg|png)$
    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>


问:
Bootstrap nav-tabs active color Change to a Different Colour For Each Bootstrap Active Tab
I can successfully change the color of the active tab and non active tabs as a group, but is it possible remain same when i go next tab.

here i tried  : http://jsfiddle.net/pThn6/2031/

When 2nd tab active the 1st color will be red. same way when 3rd active 1st and 2nd color will be red.

is it possible?

Thanks in advance.

答:
You can achieve this with three lines of jquery.

update fiddle

Working Example

function activaTab(tab) {
  $('.nav-tabs a[href="#' + tab + '"]').tab('show');

};
$("#n_tab li a").click(function() {
  $(this).parent().prevAll().addClass('redcol');
  $(this).parent().nextAll().removeClass('redcol');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.redcol>a {
  color: red;
}</code>```

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

1st

2nd

3rd

4th

...Content...

...Content...

...Content...

```

Hope this helps!

Body:
You can achieve this with three lines of jquery.

update fiddle

Working Example

function activaTab(tab) {
  $('.nav-tabs a[href="#' + tab + '"]').tab('show');

};
$("#n_tab li a").click(function() {
  $(this).parent().prevAll().addClass('redcol');
  $(this).parent().nextAll().removeClass('redcol');

});

.redcol>a {
  color: red;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>
  <ul id="n_tab" class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab">1st</a></li>
    <li><a href="#bbb" data-toggle="tab">2nd</a></li>
    <li><a href="#ccc" data-toggle="tab">3rd</a></li>
    <li><a href="#ccc" data-toggle="tab">4th</a></li>
  </ul>
  <div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
  </div>
</body>

</html>

Hope this helps!


问:
How to prevent saving child object with JPA?
I got OneToMany relationship between school and student entities. What I want to do is when I save a school object don't save or update students object.(and of course don't delete them)

When I try to save school object like below it also updates my student objects but I don't want them to be updated but only jointable. Is there any way?

I removed Cascade but its still not working.

```<code>School school = new School();
school.setStudents(studentList);
repository.save(school);
</code>```

My Entity;

```<code>@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "school_student", joinColumns = {@JoinColumn(name = "school_id")},
        inverseJoinColumns = {@JoinColumn(name = "student_id")})
private List<Student> students;
</code>```

EDIT:

When I try to save/update/remove a School object DON'T save/update/remove Student object. Think that I don't have any insert/update/delete authority on Student table.

答:
i suggest to remove the school.setStudents(studentList) because you telling hibernate to edit the many2one field of this students. try to session.clear()  if it did not work than remove the satement and make sure you do this from the student side.
i mean define a scool for student not the opposite.

```<code>package main;

import org.hibernate.Session;

import hibernate.ConnectionFactory;
import hibernate.models.Car;
import hibernate.models.Client;

public class MainClass {

    public static void main(String[] args) {
        try {
            /*
             * if you remove cascading configuration from both side
             * hibernate will not save unsaved transient instance
             */
            if(ConnectionFactory.buildSessionFactory()){
                Session session = ConnectionFactory.getSessionFactory().openSession();
                session.beginTransaction();
                // save a client instance
                Client client = new Client();
                client.setName("client");
                session.save(client);
                session.getTransaction().commit();
                session.close();

                session = ConnectionFactory.getSessionFactory().openSession();
                session.beginTransaction();
                Car car = new Car();
                car.setName("Audi");
                client = (Client) session.get(Client.class, 1);
                client.setName("client1");
                car.setClient_id(client);
                /* inset statement
                 * to prevent hibernate from updating client instance just clear
                 * the session and save only the wanted instance
                 */
                session.clear();
                session.save(car);
                session.getTransaction().commit();
                session.close();

                session = ConnectionFactory.getSessionFactory().openSession();
                session.beginTransaction();
                car = (Car) session.get(Car.class, 1);
                car.setName("Audi1");
                client = (Client) session.get(Client.class, 1);
                client.setName("Charif1");
                car.setClient_id(client);
                /* update statement
                 * to prevent hibernate from saving other instance just clear
                 * the session and update only the wanted instance
                 */
                session.clear();
                session.saveOrUpdate(car);
                session.getTransaction().commit();
                session.close();

                /**
                 * but you you are doing from the wrong side
                 * you are trying to tell that this client have
                 * this cars but Hibernate will try to link this
                 * car by editing the many2one field ??!!
                 * so remove the statement
                 * school.setStudents(studentList);
                 *
                 *
                 */
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        try {
            ConnectionFactory.getSessionFactory().close();
        } catch (Exception e) {e.printStackTrace();}

    }

}
</code>```

Body:
I got OneToMany relationship between school and student entities. What I want to do is when I save a school object don't save or update students object.(and of course don't delete them)

When I try to save school object like below it also updates my student objects but I don't want them to be updated but only jointable. Is there any way?

I removed Cascade but its still not working.

School school = new School();
school.setStudents(studentList);
repository.save(school);

My Entity;

@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "school_student", joinColumns = {@JoinColumn(name = "school_id")},
        inverseJoinColumns = {@JoinColumn(name = "student_id")})
private List<Student> students;

EDIT:

When I try to save/update/remove a School object DON'T save/update/remove Student object. Think that I don't have any insert/update/delete authority on Student table.

Body:
i suggest to remove the school.setStudents(studentList) because you telling hibernate to edit the many2one field of this students. try to session.clear()  if it did not work than remove the satement and make sure you do this from the student side.
i mean define a scool for student not the opposite.

package main;

import org.hibernate.Session;

import hibernate.ConnectionFactory;
import hibernate.models.Car;
import hibernate.models.Client;

public class MainClass {

    public static void main(String[] args) {
        try {
            /*
             * if you remove cascading configuration from both side
             * hibernate will not save unsaved transient instance
             */
            if(ConnectionFactory.buildSessionFactory()){
                Session session = ConnectionFactory.getSessionFactory().openSession();
                session.beginTransaction();
                // save a client instance
                Client client = new Client();
                client.setName("client");
                session.save(client);
                session.getTransaction().commit();
                session.close();

                session = ConnectionFactory.getSessionFactory().openSession();
                session.beginTransaction();
                Car car = new Car();
                car.setName("Audi");
                client = (Client) session.get(Client.class, 1);
                client.setName("client1");
                car.setClient_id(client);
                /* inset statement
                 * to prevent hibernate from updating client instance just clear
                 * the session and save only the wanted instance
                 */
                session.clear();
                session.save(car);
                session.getTransaction().commit();
                session.close();

                session = ConnectionFactory.getSessionFactory().openSession();
                session.beginTransaction();
                car = (Car) session.get(Car.class, 1);
                car.setName("Audi1");
                client = (Client) session.get(Client.class, 1);
                client.setName("Charif1");
                car.setClient_id(client);
                /* update statement
                 * to prevent hibernate from saving other instance just clear
                 * the session and update only the wanted instance
                 */
                session.clear();
                session.saveOrUpdate(car);
                session.getTransaction().commit();
                session.close();

                /**
                 * but you you are doing from the wrong side
                 * you are trying to tell that this client have
                 * this cars but Hibernate will try to link this
                 * car by editing the many2one field ??!!
                 * so remove the statement
                 * school.setStudents(studentList);
                 *
                 *
                 */
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        try {
            ConnectionFactory.getSessionFactory().close();
        } catch (Exception e) {e.printStackTrace();}

    }

}


问:
How the $scope.$watch works
I wrote an application to understand the Angular $scope.$watch(). But while doing so faced an issue I couldn't understand.

With the following code, I am expecting that when the value in the input box is changing the statement "Data is changing!!" will be logged to the console.

```<code>   <!DOCTYPE html>
     <html lang='en' ng-app="app">
       <head>
         <meta charset="utf-8">
         <title>My $Scope.$watch demo</title>
       </head>
       <body>
         <div ng-controller="MainController">
           <input ng-model='myData.val'>
           <h1>{{myData.val}}</h1>
         </div>
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
         <script type="text/javascript">
           angular.module('app', [])
           .controller('MainController', ['$scope', function($scope){
             $scope.myData = {};
             console.log($scope.myData);
             $scope.myData = { val:"Bablo"};
             console.log($scope.myData.val);
             $scope.$watch('$scope.myData.val', function(){
               console.log("Data is changing!!");
             });
           }]);
         </script>
       </body>
     </html>
</code>```

But I didn't observe what I was expecting, but when I changed the $scope.$watch() parameter to myData.val (earlier it was $scope.myData.val), it started working fine. Why so?

What's the issue here if I pass the whole $scope.myData.val instead of just mydata.val?

答:
While writing $scope.$watch('model_name', function(){}) you are already refering to model_name under $scope, so when you prepend it with $scope, it will look for $scope.$scope.model_name i.e $scope.$scope.myData.val in your case.
This is the reason why myData.val worked and why $scope.myData.val didn't.

Title: How the $scope.$watch works

Body:
I wrote an application to understand the Angular $scope.$watch(). But while doing so faced an issue I couldn't understand.

With the following code, I am expecting that when the value in the input box is changing the statement "Data is changing!!" will be logged to the console.

   <!DOCTYPE html>

         <meta charset="utf-8">
         <title>My $Scope.$watch demo</title>

           <input ng-model='myData.val'>

{{myData.val}}

But I didn't observe what I was expecting, but when I changed the $scope.$watch() parameter to myData.val (earlier it was $scope.myData.val), it started working fine. Why so?

What's the issue here if I pass the whole $scope.myData.val instead of just mydata.val?


问:
Removing text from NSString between "@" and ":" while keeping the text after it
So I'm reading the most recent tweet from a twitter bot and assigning it to a string, but sometimes it tweets directly to users. Here's an example of what that might look like.

```<code>NSString tweet = @("@user hey heres my message: BLah blah with symbols!");
//part I want to keep is: " BLah blah with symbols!"
//or it could end up being

NSString tweet = @("@otheruser my msg is: Wow heres some more blah: and a second colon");
//part I want to keep is: " Wow heres some more blah: and a second colon"
</code>```

I want to always remove the first part that talks to the user, while keeping the message on the end. There are too many different messages to use "stringByReplacingOccurrencesOfString"

I don't want to use "exlude-replies" from the twitter API because this bot is very popular and that would require fetching up to 100 since "count" applies before

any idea how I could do this? I think it has something to do with regular expressions, but I haven't ever used them before or been able to get one working how I want. I would really appreciate the help from anyone whos comfortable with regex

edit: also if a regex won't work for this case, id accept an explanation of the limitation preventing that :)

答:
You can also use this.</p>

```<code>  NSString *myString = @"@username is me: by using this as sample text";
  NSRange range = [myString rangeOfString:@":"];
  NSString *newString= [myString substringFromIndex:range.location];
  NSLog(@"New String is : %@", newString);
</code>```

Body:
So I'm reading the most recent tweet from a twitter bot and assigning it to a string, but sometimes it tweets directly to users. Here's an example of what that might look like.

NSString tweet = @("@user hey heres my message: BLah blah with symbols!");
//part I want to keep is: " BLah blah with symbols!"
//or it could end up being

NSString tweet = @("@otheruser my msg is: Wow heres some more blah: and a second colon");
//part I want to keep is: " Wow heres some more blah: and a second colon"

I want to always remove the first part that talks to the user, while keeping the message on the end. There are too many different messages to use "stringByReplacingOccurrencesOfString"

I don't want to use "exlude-replies" from the twitter API because this bot is very popular and that would require fetching up to 100 since "count" applies before

any idea how I could do this? I think it has something to do with regular expressions, but I haven't ever used them before or been able to get one working how I want. I would really appreciate the help from anyone whos comfortable with regex

edit: also if a regex won't work for this case, id accept an explanation of the limitation preventing that :)

Body:
You can also use this.

  NSString *myString = @"@username is me: by using this as sample text";
  NSRange range = [myString rangeOfString:@":"];
  NSString *newString= [myString substringFromIndex:range.location];
  NSLog(@"New String is : %@", newString);


问:
MySQL query becomes extremely slow when using Order By
I have a messages table with 15 million rows.

Below query returns about 5 million(But limited in 15 rows) records in less than 1 second :

```<code>SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' LIMIT 15;
</code>```

But when I adding an Order ByidDESC to the end of it, it becomes extremely slow about ~40 seconds :

```<code>SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' ORDER BY messages.id DESC LIMIT 15;
</code>```

Any help would be great appreciated.

答:
The pattern SELECT lots_of_stuff  ORDER BY something LIMIT small_integer is notorious for causing performance trouble. Leaving out ORDER BY something makes the performance trouble go away. Why?  Because the pattern with ORDER BY causes the MySQL server to sort a very large number of fairly large rows (5 million in your case), only to discard all but a small number of them.  That uses a lot of RAM, CPU, and IO in your server, just to discard most of the work.

Your best bet is to use a deferred join type of pattern here, where you sort nothing but the message.id values.  Use this subquery to do that.

```<code>                   SELECT messages.id
                     FROM messages
               INNER JOIN gateways ON messages.gateway_id=gateways.id
               INNER JOIN orders   ON gateways.order_id=orders.id
                    WHERE orders.user_id=6500
                      AND messages.deleted=0
                      AND messages.type='Out'
                 ORDER BY messages.id DESC
                   LIMIT 15
</code>```

This will give you a nice little collection of 15 message.id values.

Your next step is to work on optimizing this subquery.  I suggest you try a compound covering index on your messages table, containing the columns (deleted, type, id, gateway_id). This shoud help accelerate it.

You may need indexes on the other tables as well. You should consider using the EXPLAIN function in MySQL to analyze your performance.

Finally, use that little collection of messages.id values to get the messages rows you need, like this.  (This is the deferred join; you're deferring fetching the whole row until you know which rows you'll need. That way you don't have to ORDER the whole mess.)

Edit Add a compound index on gateways (order_id, id) to avoid the full table scan of that table. It's not enormous, but this might help a bit.

```<code>SELECT a.*
  FROM messages a
  JOIN (
                   SELECT messages.id
                     FROM messages
               INNER JOIN gateways ON messages.gateway_id=gateways.id
               INNER JOIN orders   ON gateways.order_id=orders.id
                    WHERE orders.user_id=6500
                      AND messages.deleted=0
                      AND messages.type='Out'
                 ORDER BY messages.id DESC
                   LIMIT 15
       ) b ON a.id = b.id
 ORDER BY a.id DESC
</code>```

Body:
I have a messages table with 15 million rows.

Below query returns about 5 million(But limited in 15 rows) records in less than 1 second :

SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' LIMIT 15;

But when I adding an Order ByidDESC to the end of it, it becomes extremely slow about ~40 seconds :

SELECT messages.* FROM messages
INNER JOIN gateways ON
messages.gateway_id=gateways.id
INNER JOIN orders ON
gateways.order_id=orders.id
WHERE orders.user_id=6500 AND messages.deleted=0
AND messages.type='Out' ORDER BY messages.id DESC LIMIT 15;

Any help would be great appreciated.

Body:
The pattern SELECT lots_of_stuff  ORDER BY something LIMIT small_integer is notorious for causing performance trouble. Leaving out ORDER BY something makes the performance trouble go away. Why?  Because the pattern with ORDER BY causes the MySQL server to sort a very large number of fairly large rows (5 million in your case), only to discard all but a small number of them.  That uses a lot of RAM, CPU, and IO in your server, just to discard most of the work.

Your best bet is to use a deferred join type of pattern here, where you sort nothing but the message.id values.  Use this subquery to do that.

                   SELECT messages.id
                     FROM messages
               INNER JOIN gateways ON messages.gateway_id=gateways.id
               INNER JOIN orders   ON gateways.order_id=orders.id
                    WHERE orders.user_id=6500
                      AND messages.deleted=0
                      AND messages.type='Out'
                 ORDER BY messages.id DESC
                   LIMIT 15

This will give you a nice little collection of 15 message.id values.

Your next step is to work on optimizing this subquery.  I suggest you try a compound covering index on your messages table, containing the columns (deleted, type, id, gateway_id). This shoud help accelerate it.

You may need indexes on the other tables as well. You should consider using the EXPLAIN function in MySQL to analyze your performance.

Finally, use that little collection of messages.id values to get the messages rows you need, like this.  (This is the deferred join; you're deferring fetching the whole row until you know which rows you'll need. That way you don't have to ORDER the whole mess.)

Edit Add a compound index on gateways (order_id, id) to avoid the full table scan of that table. It's not enormous, but this might help a bit.

SELECT a.*
  FROM messages a
  JOIN (
                   SELECT messages.id
                     FROM messages
               INNER JOIN gateways ON messages.gateway_id=gateways.id
               INNER JOIN orders   ON gateways.order_id=orders.id
                    WHERE orders.user_id=6500
                      AND messages.deleted=0
                      AND messages.type='Out'
                 ORDER BY messages.id DESC
                   LIMIT 15
       ) b ON a.id = b.id
 ORDER BY a.id DESC


问:
How to get the IP address of a Samsung Smart TV
I am creating an application for a Samsung Smart TV. In my app, I need to get the Smart TV's IP address. Does anyone know how to get it?</p>

答:
For Tizen TV, you can get IP address from webapis, i.e.,

```<code>webapis.network.getIp()
</code>```

will return you the IP address of the device.

Include webapi's in your index.html as :

```<code><script type="text/javascript" src="$WEBAPIS/webapis/webapis.js"></script>
</code>```

You can find more details related to Network of Tizen TV on the below mentioned Link:

http://developer.samsung.com/tv/develop/api-references/samsung-product-api-references/network-api

Body:
For Tizen TV, you can get IP address from webapis, i.e.,

webapis.network.getIp()

will return you the IP address of the device.

Include webapi's in your index.html as :

<script type="text/javascript" src="$WEBAPIS/webapis/webapis.js"></script>

You can find more details related to Network of Tizen TV on the below mentioned Link:

http://developer.samsung.com/tv/develop/api-references/samsung-product-api-references/network-api


问:
Python 3.5 multiprocessing pool and queue don't work
I encounter a multiprocessing problem. The code is included below. The code can execute as expected, but when uncommenting self.queue = multiprocessing.Queue(), this program will exit immediately and it seems that the subprocess can't be started successfully.

I don't know what happened. Could someone help me out? Many Thanks!

```<code>import multiprocessing
import time

class Test:
    def __init__(self):
        self.pool = multiprocessing.Pool(1)
        #self.queue = multiprocessing.Queue()

    def subprocess(self):
        for i in range(10):
            print("Running")
            time.sleep(1)
        print("Subprocess Completed")

    def start(self):
        self.pool.apply_async(func=self.subprocess)
        print("Subprocess has been started")
        self.pool.close()
        self.pool.join()

    def __getstate__(self):
        self_dict = self.__dict__.copy()
        del self_dict['pool']
        return self_dict

    def __setstate__(self, state):
        self.__dict__.update(state)

if __name__ == '__main__':
    test = Test()
    test.start()
</code>```

答:
I can reproduce your Issue and also no Traceback raised up.

This should raise the following error, don't know why not:

RuntimeError: Queue objects should only be shared between processes through inheritance

Replace your line of code with:

```<code>    m = multiprocessing.Manager()
    self.queue = m.Queue()
</code>```

Why does this happens?

multiprocessing.Queue is for use with one Process, you are using multiprocessing.Pool, which uses multiple Process, you have to use
multiprocessing.Manager().Queue().

Tested with Python: 3.4.2

Body:
I encounter a multiprocessing problem. The code is included below. The code can execute as expected, but when uncommenting self.queue = multiprocessing.Queue(), this program will exit immediately and it seems that the subprocess can't be started successfully.

I don't know what happened. Could someone help me out? Many Thanks!

import multiprocessing
import time

class Test:
    def __init__(self):
        self.pool = multiprocessing.Pool(1)
        #self.queue = multiprocessing.Queue()

    def subprocess(self):
        for i in range(10):
            print("Running")
            time.sleep(1)
        print("Subprocess Completed")

    def start(self):
        self.pool.apply_async(func=self.subprocess)
        print("Subprocess has been started")
        self.pool.close()
        self.pool.join()

    def __getstate__(self):
        self_dict = self.__dict__.copy()
        del self_dict['pool']
        return self_dict

    def __setstate__(self, state):
        self.__dict__.update(state)

if __name__ == '__main__':
    test = Test()
    test.start()

Body:
I can reproduce your Issue and also no Traceback raised up.

This should raise the following error, don't know why not:

RuntimeError: Queue objects should only be shared between processes through inheritance

Replace your line of code with:

    m = multiprocessing.Manager()
    self.queue = m.Queue()

Why does this happens?

multiprocessing.Queue is for use with one Process, you are using multiprocessing.Pool, which uses multiple Process, you have to use
multiprocessing.Manager().Queue().

Tested with Python: 3.4.2


问:
Go - operator overloading
I have started to study Go and I am trying to understand what happens below:

time.Sleep(1000 * time.Millisecond) // Works
time.Sleep("1000ms") // Doesn't work
```

If you print to the console time.Milliseconds you can see 1ms. So I think that I can simply call that method with the value "1000ms", but I get an error. Next I searched for operator overloading in Go, but it doesn't support it. I understand that time.Sleep gets the time.Milliseconds data type, but how does Go allow it if it doesn't support overloading operators like *?

答:
Sleep() accept a Duration type which is int64. So you can't pass string type object as an argument without typecasting it.

You got the output 1ms because of this method

```<code>(time.Duration) String() string
</code>```

Title: Go - operator overloading

Body:
I have started to study Go and I am trying to understand what happens below:

time.Sleep(1000 * time.Millisecond) // Works
time.Sleep("1000ms") // Doesn't work

If you print to the console time.Milliseconds you can see 1ms. So I think that I can simply call that method with the value "1000ms", but I get an error. Next I searched for operator overloading in Go, but it doesn't support it. I understand that time.Sleep gets the time.Milliseconds data type, but how does Go allow it if it doesn't support overloading operators like *?

Body:
Sleep() accept a Duration type which is int64. So you can't pass string type object as an argument without typecasting it.

You got the output 1ms because of this method

(time.Duration) String() string


问:
How to search array of dates to determine if one or more fit within a defined range
The problem I'm trying to solve is to determine if a user has created a "tip" last month. This check will be done after the user creates a new tip.

I have an array of strings of past tip dates for the user called "tip_dates". My current solution using rails steps through each value in that array, converts it to a date, and checks to see if it is within the month.

Is this the most efficient solution? I'm concerned that as the date array gets larger this check may take a lot of time.

```<code>def tip_last_month
    start_date = Date.today.beginning_of_month - 1.month
    end_date = start_date.end_of_month
    for tip_date in self.tip_dates do
        if tip_date.to_date.between?(start_date, end_date)
            return true
        end
    end
    return false
end
</code>```

答:
Ruby people dont really use for and explicit return-s at the end of the functions. The value of the last expression will get returned by default.

What i do here is that i create an array by mapping the string to date objects and then passing them to an any? block which will return true for the first match or return false if there is none.

```<code>def tip_last_month
  start_date = Date.today.beginning_of_month - 1.month
  end_date = start_date.end_of_month

  tip_dates.map(&:to_date).any? do |date|
    date.between?(start_date, end_date)
  end
end
</code>```

It is true that as the array gets larger, this function will slow down. You should consider storing the tips in the database in a separate table, by having one record for each tip and query them by date. It will be much faster that way.

You can read more about associations here:

http://guides.rubyonrails.org/association_basics.html

Body:
The problem I'm trying to solve is to determine if a user has created a "tip" last month. This check will be done after the user creates a new tip.

I have an array of strings of past tip dates for the user called "tip_dates". My current solution using rails steps through each value in that array, converts it to a date, and checks to see if it is within the month.

Is this the most efficient solution? I'm concerned that as the date array gets larger this check may take a lot of time.

def tip_last_month
    start_date = Date.today.beginning_of_month - 1.month
    end_date = start_date.end_of_month
    for tip_date in self.tip_dates do
        if tip_date.to_date.between?(start_date, end_date)
            return true
        end
    end
    return false
end

Body:
Ruby people dont really use for and explicit return-s at the end of the functions. The value of the last expression will get returned by default.

What i do here is that i create an array by mapping the string to date objects and then passing them to an any? block which will return true for the first match or return false if there is none.

def tip_last_month
  start_date = Date.today.beginning_of_month - 1.month
  end_date = start_date.end_of_month

  tip_dates.map(&:to_date).any? do |date|
    date.between?(start_date, end_date)
  end
end

It is true that as the array gets larger, this function will slow down. You should consider storing the tips in the database in a separate table, by having one record for each tip and query them by date. It will be much faster that way.

You can read more about associations here:

http://guides.rubyonrails.org/association_basics.html


问:
Find and modify a pattern within the start and end patterns and update file
I want to find and modify a pattern within the start and end pattern to update multiple files.
I am breaking down the steps if this can achieved with awk / sed.

Find an occurrence of a string within a 'startpat' and 'endpat' (capture the lines between start and end)

Modify the strings in the instance, for instance:
update 'sss: ccc' to 'sss: ddd'
update 'brr: mmm' to 'brr: rel/ccc'

Now create a new set of lines from 'startpat' to 'endpat' with the update strings from step 2.

Append to the start of the file after '---'.

Delete the last occurrence set of lines from 'startpat' and 'endpat' if it matches the string 'sss: aaa' and 'brr: rel/aaa'

Note: most importantly would like preserve the indents since I am working with json/yaml files.

Input file format (PS ignore comments lines // while parsing the file):

```<code>---
 - startpat:        // Startpat - make this line inclusive
    ...
    sss: ccc        // pattern to be modified
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'      // pattern to be modified
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
    ...

 - startpat:        // Endpat - make this line exclusive
</code>```

expected output after processing:

```<code>---
 - startpat:
    sss: ddd
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'

 - startpat:        // Startpat
    ....
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
    ...

 - startpat:        // Endpat
</code>```

答:
I think the simplest way is to save every line in an array. To get you started:

```<code>$ cat f.awk
BEGIN {
    # build regualr expressions to match "start pattern" and
    # "end pattern" (in the question they are the same)

    ws = "[\\t ]*"            # white-spaces
    sp = "^" ws "- startpat:" # [s]tart [p]attern
    ep = sp                   # [e]nd   [p]attern

    # a regular expression to match "---"
    # possibly suraunded by white-spaces
    op = "^" ws "---" ws "$" # where to start appending
}

{ f[NR] = $0 } # save every line to an array

END {
    n = NR # number of line in the file

    find_blocks() # set `nb` (number of blocks), `ss` `ee`

    for (ib = 1; ib <= nb; ib++)
        process_block(ss[ib], ee[ib]) # pass start and end of each block
                                      # set `nex' (number of extra lines) and `eex'
    write()
}

function find_blocks(   i, l, is, ie) {
    for (i = 1; i <= n; i++) {
        l = f[i]
        if (is > ie && l ~ ep) ee[++ie] = i # end
        if (           l ~ sp) ss[++is] = i # start
    }
    nb = ie
}

function process_block(is, ie,   i, l) {
    for (i = is + 1; i <= ie - 1; i++) {
        l = f[i]
        # modify a line (an example)
        if (l ~ /brr:/) sub(/'mmm'/, "'rel/cc'", l)

        eex[++nex] = l # push the line to another array
    }
}

function write(   i, j, l) {
    i = 1
    while (i <= n) { # print everything before "---"
        print l = f[i++]
        if (l ~ op) break
    }

    for (j = 1; j <= nex; j++) # add an extra part
        print eex[j]

    while (i <= n)            # print the part after "---"
        print f[i++]
}
</code>```

Input file

```<code>$ cat input
---
 - startpat:
    XXXXX
    brr: 'mmm'
 - startpat:
    YYYYY
    brr: 'mmm'
 - startpat:
</code>```

Usage:

```<code>awk -f f.awk input
</code>```

Output:

```<code>---
    XXXXX
    brr: 'rel/cc'
    YYYYY
    brr: 'rel/cc'
 - startpat:
    XXXXX
    brr: 'mmm'
 - startpat:
    YYYYY
    brr: 'mmm'
 - startpat:
</code>```

Body:
I want to find and modify a pattern within the start and end pattern to update multiple files.
I am breaking down the steps if this can achieved with awk / sed.

Find an occurrence of a string within a 'startpat' and 'endpat' (capture the lines between start and end)

Modify the strings in the instance, for instance:
update 'sss: ccc' to 'sss: ddd'
update 'brr: mmm' to 'brr: rel/ccc'

Now create a new set of lines from 'startpat' to 'endpat' with the update strings from step 2.

Append to the start of the file after '---'.

Delete the last occurrence set of lines from 'startpat' and 'endpat' if it matches the string 'sss: aaa' and 'brr: rel/aaa'

Note: most importantly would like preserve the indents since I am working with json/yaml files.

Input file format (PS ignore comments lines // while parsing the file):

---
 - startpat:        // Startpat - make this line inclusive
    ...
    sss: ccc        // pattern to be modified
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'      // pattern to be modified
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
    ...

 - startpat:        // Endpat - make this line exclusive

expected output after processing:

---
 - startpat:
    sss: ddd
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'

 - startpat:        // Startpat
    ....
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
    ...

 - startpat:        // Endpat

Body:
I think the simplest way is to save every line in an array. To get you started:

$ cat f.awk
BEGIN {
    # build regualr expressions to match "start pattern" and
    # "end pattern" (in the question they are the same)

    ws = "[\\t ]*"            # white-spaces
    sp = "^" ws "- startpat:" # [s]tart [p]attern
    ep = sp                   # [e]nd   [p]attern

    # a regular expression to match "---"
    # possibly suraunded by white-spaces
    op = "^" ws "---" ws "$" # where to start appending
}

{ f[NR] = $0 } # save every line to an array

END {
    n = NR # number of line in the file

    find_blocks() # set `nb` (number of blocks), `ss` `ee`

    for (ib = 1; ib <= nb; ib++)
        process_block(ss[ib], ee[ib]) # pass start and end of each block
                                      # set `nex' (number of extra lines) and `eex'
    write()
}

function find_blocks(   i, l, is, ie) {
    for (i = 1; i <= n; i++) {
        l = f[i]
        if (is > ie && l ~ ep) ee[++ie] = i # end
        if (           l ~ sp) ss[++is] = i # start
    }
    nb = ie
}

function process_block(is, ie,   i, l) {
    for (i = is + 1; i <= ie - 1; i++) {
        l = f[i]
        # modify a line (an example)
        if (l ~ /brr:/) sub(/'mmm'/, "'rel/cc'", l)

        eex[++nex] = l # push the line to another array
    }
}

function write(   i, j, l) {
    i = 1
    while (i <= n) { # print everything before "---"
        print l = f[i++]
        if (l ~ op) break
    }

    for (j = 1; j <= nex; j++) # add an extra part
        print eex[j]

    while (i <= n)            # print the part after "---"
        print f[i++]
}

Input file

$ cat input
---
 - startpat:
    XXXXX
    brr: 'mmm'
 - startpat:
    YYYYY
    brr: 'mmm'
 - startpat:

Usage:

awk -f f.awk input

Output:

---
    XXXXX
    brr: 'rel/cc'
    YYYYY
    brr: 'rel/cc'
 - startpat:
    XXXXX
    brr: 'mmm'
 - startpat:
    YYYYY
    brr: 'mmm'
 - startpat:


问:
If I include 2 files in a main file, can I make functions from 1st incuded file available in 2nd
I have a main .py file.

In this I import 2 other files.
The first is a module containing a series of debug functions called debug.py.
The second just contains a class definition.

I want my debug functions to be available to be called from within the class.

I do not want to import debug.py in my class file, as it has configurable options which I do not want to have to set multiple times across the program.

Is this possible, and how would I do it?

I include below a very simplified example of my code.

main.py:

```<code>import debug
from class import CLASS

debug.debug_messages_enabled = True

my_object = CLASS()
</code>```

debug.py:

```<code>debug_messages_enabled = False

def log (message):
    if debug_messages_enabled:
        output = ""
        output += "[LOG]: "
        output += message
        print output
</code>```

class.py:

```<code>class CLASS (object):
    def __init__ ():
        #I want to be able to access debug.log here
</code>```

答:
You need to import the debug.py in your class file.

The fact that main.py makes a change to one setting in the debug module is not relevant. Your class files is going to contain the debug statements, make the debug calls, etc.

The decision to print/not print will be made based on that setting. The setting (debug_messages_enabled) will be changed by main.py, but that doesn't matter to class.py.

class.py:

```<code>from debug import log

class CLASS (object):
    def __init__ (self):
        log("A long thick section of trimmed, unhewn timber.")
        self.foo = 1
</code>```

Body:
I have a main .py file.

In this I import 2 other files.
The first is a module containing a series of debug functions called debug.py.
The second just contains a class definition.

I want my debug functions to be available to be called from within the class.

I do not want to import debug.py in my class file, as it has configurable options which I do not want to have to set multiple times across the program.

Is this possible, and how would I do it?

I include below a very simplified example of my code.

main.py:

import debug
from class import CLASS

debug.debug_messages_enabled = True

my_object = CLASS()

debug.py:

debug_messages_enabled = False

def log (message):
    if debug_messages_enabled:
        output = ""
        output += "[LOG]: "
        output += message
        print output

class.py:

class CLASS (object):
    def __init__ ():
        #I want to be able to access debug.log here

Body:
You need to import the debug.py in your class file.

The fact that main.py makes a change to one setting in the debug module is not relevant. Your class files is going to contain the debug statements, make the debug calls, etc.

The decision to print/not print will be made based on that setting. The setting (debug_messages_enabled) will be changed by main.py, but that doesn't matter to class.py.

class.py:

from debug import log

class CLASS (object):
    def __init__ (self):
        log("A long thick section of trimmed, unhewn timber.")
        self.foo = 1


问:
Error: [MC] Reading from private effective user settings
I have set OS_ACTIVITY_MODE to disabled, yet I am still getting this error whenever I try typing in a text field. Any help would be much appreciated!

答: This message is not an error, this is simply a (somewhat buggy) log message in the debug console stating that the app is reading from user settings. You can safely ignore it.</p>


问:
Get internal byte array from ByteArrayInputStream
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?

Thanks,

答:
The internal field is protected, so extending would be easy. If you really don't want to, reflection may be another way. This is not a great solution since it relies on internal workings of ByteArrayInputStream (such as knowing the field is called buf). You have been warned.

```<code>ByteArrayInputStream bis = ...
Field f = ByteArrayInputStream.class.getDeclaredField("buf");
f.setAccessible(true);
byte[] buf = (byte[])f.get(bis);
</code>```

Body:
The internal field is protected, so extending would be easy. If you really don't want to, reflection may be another way. This is not a great solution since it relies on internal workings of ByteArrayInputStream (such as knowing the field is called buf). You have been warned.

ByteArrayInputStream bis = ...
Field f = ByteArrayInputStream.class.getDeclaredField("buf");
f.setAccessible(true);
byte[] buf = (byte[])f.get(bis);


问:
Something's wrong with mouseOver() and multiples elements
I am currently working on a some sort of small html game.
Below is my code :

```<code><div id="BS">
        <img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" onmouseover="mouseOver()" src="Pictures/BS1.png"/>
    </div>
    <script type="text/javascript">
            function mouseOver() {
                document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS2.png" onmouseout="mouseOut()"/>';
                }
            function mouseOut() {
                document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS1.png" onmouseover="mouseOver()"/>';
            }
    </script>

  <div id="Radio">
        <img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" onmouseover="mouseOver()" src="Pictures/radio1.png"/>
    </div>
    <script type="text/javascript">
            function mouseOver() {
                document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio2.png" onmouseout="mouseOut()"/>';
                }
            function mouseOut() {
                document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio1.png" onmouseover="mouseOver()"/>';
            }
    </script>
</code>```

The issue is, only the last item coded ( here, the Radio ) is working when I'm putting my cursor onto it. So i was wondering, is there a way to fix this ? Cause I did plan to put at least 2 more elements ...
Thanks,
Paul

答:
You Have both function names mouseOver and mouseOut, so the second time you are creating it, you are overwriting the first one. If you name them mouseBsOver and mouseRadioOver, then assign them that way, it will work.

```<code><div id="BS">
    <img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" onmouseover="mouseBsOver()" src="Pictures/BS1.png"/>
</div>
<script type="text/javascript">
        function mouseBsOver() {
            document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS2.png" onmouseout="mouseOut()"/>';
            }
        function mouseBsOut() {
            document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS1.png" onmouseover="mouseOver()"/>';
        }
</script>

<div id="Radio">
    <img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" onmouseover="mouseRadioOver()" src="Pictures/radio1.png"/>
</div>
<script type="text/javascript">
        function mouseRadioOver() {
            document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio2.png" onmouseout="mouseOut()"/>';
            }
        function mouseRadioOut() {
            document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio1.png" onmouseover="mouseOver()"/>';
        }
</script>
</code>```

Body:
I am currently working on a some sort of small html game.
Below is my code :

The issue is, only the last item coded ( here, the Radio ) is working when I'm putting my cursor onto it. So i was wondering, is there a way to fix this ? Cause I did plan to put at least 2 more elements ...
Thanks,
Paul

Body:
You Have both function names mouseOver and mouseOut, so the second time you are creating it, you are overwriting the first one. If you name them mouseBsOver and mouseRadioOver, then assign them that way, it will work.

<div id="BS">
    <img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" onmouseover="mouseBsOver()" src="Pictures/BS1.png"/>
</div>
<script type="text/javascript">
        function mouseBsOver() {
            document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS2.png" onmouseout="mouseOut()"/>';
            }
        function mouseBsOut() {
            document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS1.png" onmouseover="mouseOver()"/>';
        }
</script>

<div id="Radio">
    <img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" onmouseover="mouseRadioOver()" src="Pictures/radio1.png"/>
</div>
<script type="text/javascript">
        function mouseRadioOver() {
            document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio2.png" onmouseout="mouseOut()"/>';
            }
        function mouseRadioOut() {
            document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio1.png" onmouseover="mouseOver()"/>';
        }
</script>


问:
Program consuming too much RAM
I am trying to run a simple code that will create a 2D array. At first I declared the array normally, but it got an abnormal termination.

In the task manager the program typically grew to a size of 0.4 MB and was terminated. So, after some research, I discovered the heap and consequently tried to store there. This time it took almost 3 GB and my OS restarted due to low memory.

```<code>int main()
{
    for(int i=0;i<1000;i++)            // outer loop to create 1000 instances
    {
        int** c = new int*[3000];         // creating 2D array of size 3000*3000
        int** b = new int*[3000];

        for(int z=0;z<3000;z++)
        {
            c[z] = new int[3000];
            b[z] = new int[3000];
        }

    }
    return 0;
}
</code>```

So, as far as I can tell, the maximum size of c is [3000][3000] = 36*10^6 B = 36 MB

Now I have 4GB of RAM, so this seems quite unfair.

Anyway I understand that C++ does not have auto garbage collection; that's why the remains are left out. However, I need this array structure for computation. How can I get it to use more of the available memory?

答:
You have 2 * sum{ 0 ~ 2999 } = 2 * 2999 * 3000 / 2 = 8,997,000 int*s, and each int* points int[3000].

If assuming sizeof(int*) == 8 and sizeof(int) == 4, The size of the memory your program needs is 8997000 * (8 + 3000 * 4) = 108,035,976,000 bytes.

108,035,976,000 byte > 105,503,882 KiB > 103,031 MiB > 100 GiB. I think your machine don't support 100 GiB size of memory space.

Title: Program consuming too much RAM

Body:
I am trying to run a simple code that will create a 2D array. At first I declared the array normally, but it got an abnormal termination.

In the task manager the program typically grew to a size of 0.4 MB and was terminated. So, after some research, I discovered the heap and consequently tried to store there. This time it took almost 3 GB and my OS restarted due to low memory.

int main()
{
    for(int i=0;i<1000;i++)            // outer loop to create 1000 instances
    {
        int** c = new int*[3000];         // creating 2D array of size 3000*3000
        int** b = new int*[3000];

        for(int z=0;z<3000;z++)
        {
            c[z] = new int[3000];
            b[z] = new int[3000];
        }

    }
    return 0;
}

So, as far as I can tell, the maximum size of c is [3000][3000] = 36*10^6 B = 36 MB

Now I have 4GB of RAM, so this seems quite unfair.

Anyway I understand that C++ does not have auto garbage collection; that's why the remains are left out. However, I need this array structure for computation. How can I get it to use more of the available memory?


问:
Multithreading requests in Rails
I'm pretty new to Ruby On Rails webdevelopment, and I've got the following question:

In my Javascript I launch multiple calls to my controller at once with the use of AJAX, however I'm under the impression these requests get handled one by one, which results in a very slow experience (as some of the requests are quite intense and can take a while to process). I'd expect the server to spawn a separate thread for each request. As far as I'm aware I'm using WEBrick as the server on which my application is running. Online I found some posts indicating that WEBrick is by definition single threaded, so I'm out of luck, however some other posts claim it supports multithreading, but it is prohibited by a mutex in Rails. Most posts seem to refer rails 4.1-4.2, I'm currently running 5.0.1.

答: Use puma instead of webrick in development and unicorn in production and you will be alright.</p>

Title: Multithreading requests in Rails


问:
cPanel api2 for MysqlFE authorizehost
I am trying to use cPanel xml api to add ip addresses to the mysql remote access host list.

If I use this...

```<code>$newdomain = "12.345.45.678";
$myemails = $xmlapi->api2_query($account, "MysqlFE", "authorizehost", array('host'=>$newdomain) );
</code>```

I can in fact add the ip to the remote host access list. I verified by logging into cPanel and checking.
When I try to access the database remotely, I am blocked. ???? like I have not whitelisted my ip ??

If I log into cPanel and remove the ip address and add it manually(the exact same ip)...then test my remote connection, and it works.

Am I missing something here?
The xmlapi adds the ip successfully, but I still can't get a remote connection.

If it helps at all, my whitelist already has some ip addresses that were added manually. So, it is not an empty record.

答:
```<code><?php
require_once("xmlapi.php");
$ip = 'website ip address here';
$account = 'cpanel username here';
$domain = 'mysite.com';
$passwd = 'cpanel password here';

$xmlapi = new xmlapi($ip);
$xmlapi->password_auth($account, $passwd);
$xmlapi->set_port(2083);
$xmlapi->set_output("simplexml");

$newAuthIP = "123.45.67.890";  <----- sanitized value from a form post
$myemails = $xmlapi->api2_query($account, "MysqlFE", "authorizehost", array('host'=>$newAuthIP) );
?>
</code>```

Title: cPanel api2 for MysqlFE authorizehost

Body:
I am trying to use cPanel xml api to add ip addresses to the mysql remote access host list.

If I use this...

$newdomain = "12.345.45.678";
$myemails = $xmlapi->api2_query($account, "MysqlFE", "authorizehost", array('host'=>$newdomain) );

I can in fact add the ip to the remote host access list. I verified by logging into cPanel and checking.
When I try to access the database remotely, I am blocked. ???? like I have not whitelisted my ip ??

If I log into cPanel and remove the ip address and add it manually(the exact same ip)...then test my remote connection, and it works.

Am I missing something here?
The xmlapi adds the ip successfully, but I still can't get a remote connection.

If it helps at all, my whitelist already has some ip addresses that were added manually. So, it is not an empty record.