问:
Read JSON from Server (Java)
First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

```<code>[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]
</code>```

This is my code:

```<code>/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

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

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

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

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

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

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

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } 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);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}
</code>```

答:
First you can use Gson Which is a google powerd tool for serializing and de-serializing Json

Then add the gson dependency to your code,

```<code>    compile 'com.google.code.gson:gson:2.7'
</code>```

Next thing you want to do is to create some sample model classes to serialize your json data, use this link and paste your json data and create corresponding classes

Then is the java code, (Lets say your base model class name is UserLocation

Userlocation

```<code>    public class UserLocation{
        private Location location;

        private String name;

        public Location getLocation ()
        {
            return location;
        }

        public void setLocation (Location location)
        {
            this.location = location;
        }

        public String getName ()
        {
            return name;
        }

        public void setName (String name)
        {
            this.name = name;
        }
  }
</code>```

Location

```<code>    public class Location {
    private double longitude;

    private double latitude;

    public double getLongitude ()
    {
        return longitude;
    }

    public void setLongitude (double longitude)
    {
        this.longitude = longitude;
    }

    public double getLatitude ()
    {
        return latitude;
    }

    public void setLatitude (double latitude)
    {
        this.latitude = latitude;
    }
}
</code>```

in code

```<code>List<UserLocation> userLocationList = Arrays.asList(new Gson().fromJson(yourResponseString, UserLocation[].class));
</code>```

This is it, everything will be under this userLocationList

Happy coding.. :)

Title: Read JSON from Server (Java)

Body:
First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]

This is my code:

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

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

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

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

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

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

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

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } 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);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}

Body:
First you can use Gson Which is a google powerd tool for serializing and de-serializing Json

Then add the gson dependency to your code,

    compile 'com.google.code.gson:gson:2.7'

Next thing you want to do is to create some sample model classes to serialize your json data, use this link and paste your json data and create corresponding classes

Then is the java code, (Lets say your base model class name is UserLocation

Userlocation

    public class UserLocation{
        private Location location;

        private String name;

        public Location getLocation ()
        {
            return location;
        }

        public void setLocation (Location location)
        {
            this.location = location;
        }

        public String getName ()
        {
            return name;
        }

        public void setName (String name)
        {
            this.name = name;
        }
  }

Location

    public class Location {
    private double longitude;

    private double latitude;

    public double getLongitude ()
    {
        return longitude;
    }

    public void setLongitude (double longitude)
    {
        this.longitude = longitude;
    }

    public double getLatitude ()
    {
        return latitude;
    }

    public void setLatitude (double latitude)
    {
        this.latitude = latitude;
    }
}

in code

List<UserLocation> userLocationList = Arrays.asList(new Gson().fromJson(yourResponseString, UserLocation[].class));

This is it, everything will be under this userLocationList

Happy coding.. :)


来源: stackexchange

问:
Xcode, UISwipeGestureRecognizer, ViewController transitions the wrong way?
I use the latest Xcode. So I put the SwipeGestureRecognizer inside my ViewController and connected it to another ViewController via a SHOW(push) seque. According to Attributes Inspector I can choose left/right. But when I build/run project and swipe left/right to transition between view controllers, the transition is up/down instead of right/left.

How do I make a right/left swipe make the VC move right/left instead of up/down?

答:
For swift 3.0

```<code>let transition = CATransition()
transition.duration = 0.5
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
view.window!.layer.add(transition, forKey: kCATransition)
present(dashboardWorkout, animated: false, completion: nil)
</code>```

For objective c

```<code>CATransition *transition = [[CATransition alloc] init];
transition.duration = 0.5;
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[self.view.window.layer addAnimation:transition forKey:kCATransition];
[self presentViewController:dashboardWorkout animated:false completion:nil];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For swift 3.0

let transition = CATransition()
transition.duration = 0.5
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
view.window!.layer.add(transition, forKey: kCATransition)
present(dashboardWorkout, animated: false, completion: nil)

For objective c

CATransition *transition = [[CATransition alloc] init];
transition.duration = 0.5;
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[self.view.window.layer addAnimation:transition forKey:kCATransition];
[self presentViewController:dashboardWorkout animated:false completion:nil];


问:
What does smart merge do in Android Studio?
In Android studio there are options at the bottom right corner to handle branches. In Merge option when I merge another remote or local branch, it shows me options like Force merge and smart merge.

What exactly they do?

When merging with local/remote branches?

答:
Smart merge executes the following commands:

git stash save "Uncommitted changes before Update at <MM/DD/YY>, <HH:MM>"

git merge <remote>

git stash pop (if merge successful)

If the merge is unsuccessful and you abort or discard changes, you'll need to run git stash pop yourself to get back your changes.

You can see the exact commands being executed by examining the Version Control context in Android Studio, in the Console tab:


问:
Rows alternate in query
I have this query.

```<code>Select name from Table
</code>```

and this is the result.

Now, I need this risult.

This is the question. How can I modify the query for write 'OK' after every  single row ?

Thank you

答:
You can do like this:

```<code>Select [name], 1 As S, [name] As Ex
From Table;
Union All
Select [name], 2 As S, "OK" As Ex
From Table
Order By 1, 2
</code>```

The last column will hold your sequence.

Title: Rows alternate in query

Body:
I have this query.

Select name from Table

and this is the result.

Now, I need this risult.

This is the question. How can I modify the query for write 'OK' after every  single row ?

Thank you

Body:
You can do like this:

Select [name], 1 As S, [name] As Ex
From Table;
Union All
Select [name], 2 As S, "OK" As Ex
From Table
Order By 1, 2

The last column will hold your sequence.


问:
How to convert lowercase characters of a string to uppercase characters in C++?
I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

```<code> #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }
</code>```

I get the output as:

```<code>HELLO WORLDHello World
</code>```

But the required output is:

```<code>HELLO WORLD HELLO WORLD
</code>```

How do I make the

```<code> cout<<str;
</code>```

statement in main() to print the result computed in the function :

```<code> void stringToUpper(string &s)
</code>```

答:
cout << str;            //This line should not be changed

This means that you must change str.

void stringToUpper(string &s) //This line should not be changed

Good news, your method take s as a reference.

In your code you are doing c=s[i]; you should reassign the char in your string s[i] = c

Body:
I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

 #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }

I get the output as:

HELLO WORLDHello World

But the required output is:

HELLO WORLD HELLO WORLD

How do I make the

 cout<<str;

statement in main() to print the result computed in the function :

 void stringToUpper(string &s)


问:
"Marshall" or "Marshal"? "Marshalling" or "Marshaling"?
Which one is it in a programming context?  Is there a difference?  I've seen it both ways and I don't want to spell it wrong in my code.</p>

答:
Marshal (one l) is correct in English. However, both Marshalling or Marshaling are correct.

Marshalling (with two lls) "seems to make more sense" in my American-English mind as it softens the "a" explicitly.

Some Links

Free Dictionary - marshal

Merriam Webster - marshal & marshalling

Google Trends - marshalling vs marshaling

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Typescript Partial params in constructor and access in extended class
How can I achieve this:

```<code>export class Base
{
    constructor(public defaultValues: Partial<Base>)
    {
        if (defaultValues)
            for (const [key, value] of Object.entries(defaultValues))
                this[key] = value;
    }
}

export class Extended extends Base
{
    public prop1: boolean;

    public method1()
    {
        //prop1 does not exists, because defaultValues are Base not Extended
        this.defaultValues.prop1;     //!!!! ERROR Property 'prop1' does not exists on type 'Partial<Base>'.
    }
}
</code>```

I need to set some default values to class itself and store it in variable, so I can access defaultValues later.

Edited:

I also try:

```<code>class Base<T extends Base = any> {
    constructor(public defaultValues: Partial<T>) {

    }
}

class Extended extends Base<Extended> {
    public prop1: boolean;

    public method1() {
        this.defaultValues.prop1;
    }
}
</code>```

But got error:

and this, but now I get error that

T[keyof T] is not accessible to this[keyof t]

:

```<code>export class Base<T extends Base<T>>
{
    constructor(public defaultValues: T)
    {
        if (defaultValues)
            for (const [key, value] of Object.entries(defaultValues))
                this[key] = value;  //!!!!! ERROR
    }
}

export class Extended extends Base<Extended>
{
    public prop1: boolean;

    public method1()
    {
        this.defaultValues.prop1;
    }
}
</code>```

Error with default parameters:

Edited 3:

After installing VS 15.3 (VS 2017 update 2) and Typescript SDK 2.3 and after choosing Typescript 2.3 in Intellisense  for VS 2017 I made some progress.
Have just a little tiny problem:

答:
Base doesn't have a member called prop1, Extended does.

You can make Base generic:

```<code>class Base<T extends Base = any> {
    constructor(public defaultValues: Partial<T>) {
        ...
    }
}

class Extended extends Base<Extended> {
    public prop1: boolean;

    public method1() {
        this.defaultValues.prop1;
    }
}
</code>```

Edit

Before typescript 2.3 (because of Generic parameter defaults) you need to do:

```<code>class Base<T extends Base<any>> {
    constructor(public defaultValues: Partial<T>) {

    }
}
</code>```

2nd edit

If you're using the noImplicitAny flag then you need to do this:

```<code>class Base<T extends Base<any>> {
    constructor(public defaultValues: T) {
        if (defaultValues) {
            for (const [key, value] of Object.entries(defaultValues)) {
                this[key as keyof this] = value;
            }
        }
    }
}
</code>```

The difference being this[key as keyof this] = value;

Body:
How can I achieve this:

export class Base
{
    constructor(public defaultValues: Partial<Base>)
    {
        if (defaultValues)
            for (const [key, value] of Object.entries(defaultValues))
                this[key] = value;
    }
}

export class Extended extends Base
{
    public prop1: boolean;

    public method1()
    {
        //prop1 does not exists, because defaultValues are Base not Extended
        this.defaultValues.prop1;     //!!!! ERROR Property 'prop1' does not exists on type 'Partial<Base>'.
    }
}

I need to set some default values to class itself and store it in variable, so I can access defaultValues later.

Edited:

I also try:

class Base<T extends Base = any> {
    constructor(public defaultValues: Partial<T>) {

    }
}

class Extended extends Base<Extended> {
    public prop1: boolean;

    public method1() {
        this.defaultValues.prop1;
    }
}

But got error:

and this, but now I get error that

T[keyof T] is not accessible to this[keyof t]

:

export class Base<T extends Base<T>>
{
    constructor(public defaultValues: T)
    {
        if (defaultValues)
            for (const [key, value] of Object.entries(defaultValues))
                this[key] = value;  //!!!!! ERROR
    }
}

export class Extended extends Base<Extended>
{
    public prop1: boolean;

    public method1()
    {
        this.defaultValues.prop1;
    }
}

Error with default parameters:

Edited 3:

After installing VS 15.3 (VS 2017 update 2) and Typescript SDK 2.3 and after choosing Typescript 2.3 in Intellisense  for VS 2017 I made some progress.
Have just a little tiny problem:

Body:
Base doesn't have a member called prop1, Extended does.

You can make Base generic:

class Base<T extends Base = any> {
    constructor(public defaultValues: Partial<T>) {
        ...
    }
}

class Extended extends Base<Extended> {
    public prop1: boolean;

    public method1() {
        this.defaultValues.prop1;
    }
}

Edit

Before typescript 2.3 (because of Generic parameter defaults) you need to do:

class Base<T extends Base<any>> {
    constructor(public defaultValues: Partial<T>) {

    }
}

2nd edit

If you're using the noImplicitAny flag then you need to do this:

class Base<T extends Base<any>> {
    constructor(public defaultValues: T) {
        if (defaultValues) {
            for (const [key, value] of Object.entries(defaultValues)) {
                this[key as keyof this] = value;
            }
        }
    }
}

The difference being this[key as keyof this] = value;


问:
material 2 paletta contrast color
In the paletta, I can see contrast.
How can I choose a contrast color?

works:

```<code>scss
mat-color($button-primary);
</code>```

Not working

```<code>scss
mat-color($button-primary, contrast(900));
</code>```

See on the bottom it says contrast.

```<code>scss
$mat-red: (
  50: #ffebee,
  100: #ffcdd2,
  200: #ef9a9a,
  300: #e57373,
  400: #ef5350,
  500: #f44336,
  600: #e53935,
  700: #d32f2f,
  800: #c62828,
  900: #b71c1c,
  A100: #ff8a80,
  A200: #ff5252,
  A400: #ff1744,
  A700: #d50000,
  contrast: (
    50: $black-87-opacity,
    100: $black-87-opacity,
    200: $black-87-opacity,
    300: $black-87-opacity,
    400: $black-87-opacity,
    500: white,
    600: white,
    700: white,
    800: $white-87-opacity,
    900: $white-87-opacity,
    A100: $black-87-opacity,
    A200: white,
    A400: white,
    A700: white,
  )
);
</code>```

How can I use the contrast?

答:
The solution is:

.test {
  color: mat-color($button-primary, 900-contrast)
}
```

Title: material 2 paletta contrast color

Body:
In the paletta, I can see contrast.
How can I choose a contrast color?

works:

scss
mat-color($button-primary);

Not working

scss
mat-color($button-primary, contrast(900));

See on the bottom it says contrast.

scss
$mat-red: (
  50: #ffebee,
  100: #ffcdd2,
  200: #ef9a9a,
  300: #e57373,
  400: #ef5350,
  500: #f44336,
  600: #e53935,
  700: #d32f2f,
  800: #c62828,
  900: #b71c1c,
  A100: #ff8a80,
  A200: #ff5252,
  A400: #ff1744,
  A700: #d50000,
  contrast: (
    50: $black-87-opacity,
    100: $black-87-opacity,
    200: $black-87-opacity,
    300: $black-87-opacity,
    400: $black-87-opacity,
    500: white,
    600: white,
    700: white,
    800: $white-87-opacity,
    900: $white-87-opacity,
    A100: $black-87-opacity,
    A200: white,
    A400: white,
    A700: white,
  )
);

How can I use the contrast?


问:
GitHub Pages Failed to load resource
I am trying to host an Angular application with Bootstrap 4 on GitHub Pages with angular-cli-ghpages at https://ewoutg.github.io/ePortfolio/ but I run into several of these errors:

```<code>Failed to load resource: styles.05418b2b9d65514cb185.bundle.css the server responded with a status of 404 (Not Found)`
</code>```

I do have a Dist folder with that resource in:

What am I doing wrong? How can I fix this?

答:
Seems your problem is related with case sensitivity. Try the following base href

```<code><base href="https://ewoutg.github.io/ePortfolio/">
</code>```

Here is used capital P

Title: GitHub Pages Failed to load resource

Body:
I am trying to host an Angular application with Bootstrap 4 on GitHub Pages with angular-cli-ghpages at https://ewoutg.github.io/ePortfolio/ but I run into several of these errors:

Failed to load resource: styles.05418b2b9d65514cb185.bundle.css the server responded with a status of 404 (Not Found)`

I do have a Dist folder with that resource in:

What am I doing wrong? How can I fix this?

Body:
Seems your problem is related with case sensitivity. Try the following base href

<base href="https://ewoutg.github.io/ePortfolio/">

Here is used capital P


问:
jQuery Ajax function does not work?
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

```<code><script>
 function submitForLogin()
 {
    $.ajax({
            type: "POST",
            url: "php/login.php",
            data: { email: "example@abc.com",password:"123" }}).done(function(data){alert(data);});

 }

</script>
</code>```

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

```<code><?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>
</code>```

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

答:
Try this code working for me on my machine. Don't forgot to place Jquery File.
 PHP (ajax.php) :

```<code><html>
<head>
    <script src="jquery.min.js"></script>
    <script>
        function submitForLogin()
 {
        alert("23");
        var email = document.getElementById("txtUserName").value;
        var password = document.getElementById("txtPassword").value;
    $.ajax({
            type: "POST",
            url: "login1.php",
            data: { email: email,password:password },
            success : function(response){
                alert(response);
            }
   });

 }

    </script>
</head>
<body>
    <input type="text" placeholder = "Enter user name" id="txtUserName"/>
    <input type="password" placeholder = "Enter password" id="txtPassword"/><br>
    <input type="button" onclick="submitForLogin();" value="Login"/>
</body>
</html>
</code>```

Server Side (login1.php) :

```<code>    <?php
var_dump($_POST);
?>
</code>```

Title: jQuery Ajax function does not work?

Body:
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

Body:
Try this code working for me on my machine. Don't forgot to place Jquery File.
 PHP (ajax.php) :

<html>
<head>
    <script src="jquery.min.js"></script>
    <script>
        function submitForLogin()
 {
        alert("23");
        var email = document.getElementById("txtUserName").value;
        var password = document.getElementById("txtPassword").value;
    $.ajax({
            type: "POST",
            url: "login1.php",
            data: { email: email,password:password },
            success : function(response){
                alert(response);
            }
   });

 }

    </script>
</head>
<body>
    <input type="text" placeholder = "Enter user name" id="txtUserName"/>
    <input type="password" placeholder = "Enter password" id="txtPassword"/><br>
    <input type="button" onclick="submitForLogin();" value="Login"/>
</body>
</html>

Server Side (login1.php) :

    <?php
var_dump($_POST);
?>


问:
Cannot Get Django Template to Print Formatted JSON
I'm struggling with printing a formatted JSON response from Watson's NLU API. I'm using Python 2.7 and Django 1.11. My views.py looks like this:

```<code>def nlu_analysis(request):
    if request.method == 'POST':
        text2send = request.POST.get('text2send')
        natural_language_understanding = NLUV1(
            version='2017-02-27',
            username='####',
            password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ... features.SemanticRoles()])

        parsedData = json.dumps(response, indent=2)
    return render(request, 'analysis.html', {'data': parsedData})
</code>```

My analysis.html looks like this:

```<code>  <div class="container text-left">
      <p>{{ data }}</p>
  </div>
</code>```

The result of all of this is the data, with JSON brackets being printed on one line like this:

{ "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized": "be" }, "sentence": "Batman and Superman are fighting the bad guys", ... "keywords": [ { "relevance": 0.931284, "text": "bad guys" }, { "relevance": 0.790756, "text": "Superman" }, { "relevance": 0.752557, "text": "Batman" } ] }

If I run this within a for loop

```<code><div class="container text-left">
    {% for d in data %}
        <p>{{ d }}</p>
    {% endfor %}
</div>
</code>```

it simply prints on character on each line

{

"

s

e

m

...

suggesting that {{ data }} is a string, nothing more.

Clearly I am fundamentally misunderstanding something. Either it is something with respect to how json.dumps (including 'indent=2') works or how to deal with it properly in my template. I suspect the later as the information being passed via 'data' clearly contains all of the JSON syntax. If I place the one line result above result in a JSON validator it reformats and validates perfectly.

Any help for a complete rookie out there? Thanks.

答:
If you want to access the value for a key in the dict object, you just need to do like this (for your example data),

```<code>{{ response.semantic_roles }}
</code>```

Here semantic_roles will be interpreted as a literal string and not using the value of the variable “semantics”, if one exists in the template context. And response is the name of the context variable.

Or, If you want to get value of each key in he dict object using a loop, you may need to create a custom filter for your template,

```<code>from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)
</code>```

And in your template,

```<code>{% for key in response %}
{{ response|get_item:key }}
{% endfor %}
</code>```

Of course, make sure to call load on your template tags so they're visible to the renderer.

Here are some helpful links,

https://docs.djangoproject.com/en/1.11/ref/templates/api/#variables-and-lookups

Accessing dictionary by key in Django template,

https://code.djangoproject.com/ticket/3371

http://stackoverflow.com/questions/25266672/access-a-dictionary-element-in-the-django-template-with-a-variable&grqid=f2CFq5XB&hl=en-IN

Body:
I'm struggling with printing a formatted JSON response from Watson's NLU API. I'm using Python 2.7 and Django 1.11. My views.py looks like this:

def nlu_analysis(request):
    if request.method == 'POST':
        text2send = request.POST.get('text2send')
        natural_language_understanding = NLUV1(
            version='2017-02-27',
            username='####',
            password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ... features.SemanticRoles()])

        parsedData = json.dumps(response, indent=2)
    return render(request, 'analysis.html', {'data': parsedData})

My analysis.html looks like this:

{{ data }}

The result of all of this is the data, with JSON brackets being printed on one line like this:

{ "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized": "be" }, "sentence": "Batman and Superman are fighting the bad guys", ... "keywords": [ { "relevance": 0.931284, "text": "bad guys" }, { "relevance": 0.790756, "text": "Superman" }, { "relevance": 0.752557, "text": "Batman" } ] }

If I run this within a for loop

    {% for d in data %}

{{ d }}

    {% endfor %}

it simply prints on character on each line

{

"

s

e

m

...

suggesting that {{ data }} is a string, nothing more.

Clearly I am fundamentally misunderstanding something. Either it is something with respect to how json.dumps (including 'indent=2') works or how to deal with it properly in my template. I suspect the later as the information being passed via 'data' clearly contains all of the JSON syntax. If I place the one line result above result in a JSON validator it reformats and validates perfectly.

Any help for a complete rookie out there? Thanks.

Body:
If you want to access the value for a key in the dict object, you just need to do like this (for your example data),

{{ response.semantic_roles }}

Here semantic_roles will be interpreted as a literal string and not using the value of the variable “semantics”, if one exists in the template context. And response is the name of the context variable.

Or, If you want to get value of each key in he dict object using a loop, you may need to create a custom filter for your template,

from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

And in your template,

{% for key in response %}
{{ response|get_item:key }}
{% endfor %}

Of course, make sure to call load on your template tags so they're visible to the renderer.

Here are some helpful links,

https://docs.djangoproject.com/en/1.11/ref/templates/api/#variables-and-lookups

Accessing dictionary by key in Django template,

https://code.djangoproject.com/ticket/3371

http://stackoverflow.com/questions/25266672/access-a-dictionary-element-in-the-django-template-with-a-variable&grqid=f2CFq5XB&hl=en-IN


问:
How to change button URL through JS?
I have been spending a lot of time researching how to change a button href dynamically in my website using JS.  I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.

I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.

One of the simplest solutions that should work was found here:
  How to make option selection change button link?

I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed.  I added window.onload() to prevent the JS from running before elements were loaded.

I am trying to do something similar with the following HTML & JS code:

HTML Code:

```<code><input type="hidden" id="input-book-type" value="GlassCrystal">

<br><br>

<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>

<br><br>

<input id="input-project-title" value="Optional Project Title">

<br><br>

<a class="button" id="design-button" href="http://">Design Now</a>
</code>```

JS Code:

```<code>window.onload = function() {

document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");

this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};

}
</code>```

JS Fiddle:
https://jsfiddle.net/w65c9x2d/

答:
Here is example code:

```<code><a href="#" id="abc">jhg</a>
<a href="#" id="myLink">jhhghj</a>

<script type="text/javascript">
   document.getElementById("myLink").onclick = function() {
   document.getElementById("abc").href="xyz.php";
   return false;
};
</script>
</code>```

I took this from  here

Title: How to change button URL through JS?

Body:
I have been spending a lot of time researching how to change a button href dynamically in my website using JS.  I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.

I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.

One of the simplest solutions that should work was found here:
  How to make option selection change button link?

I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed.  I added window.onload() to prevent the JS from running before elements were loaded.

I am trying to do something similar with the following HTML & JS code:

HTML Code:

<input type="hidden" id="input-book-type" value="GlassCrystal">

<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>

<input id="input-project-title" value="Optional Project Title">

Design Now

JS Code:

window.onload = function() {

document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");

this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};

}

JS Fiddle:
https://jsfiddle.net/w65c9x2d/

Body:
Here is example code:

<a href="#" id="abc">jhg</a>
<a href="#" id="myLink">jhhghj</a>

<script type="text/javascript">
   document.getElementById("myLink").onclick = function() {
   document.getElementById("abc").href="xyz.php";
   return false;
};
</script>

I took this from  here


答:
Change your button to this:

```<code><button class="button" id="design-button" onclick="redirect()">Design Now</button>
</code>```

Now instead of using a link, simply do a function that will take the inputs and change the window.location.href (or whatever method you prefer) to change the page.

```<code>redirect(obj) {
    window.location.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/"
}
</code>```

Obviously change it to your liking :)

Title: How to change button URL through JS?

Body:
Change your button to this:

<button class="button" id="design-button" onclick="redirect()">Design Now</button>

Now instead of using a link, simply do a function that will take the inputs and change the window.location.href (or whatever method you prefer) to change the page.

redirect(obj) {
    window.location.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/"
}

Obviously change it to your liking :)


问:
Springboot relationship management
I have a question about using springboot with thymeleaf and relationship management.

I have three objects that needs to be fully bi-directional:

obj1(Many)--TO--(One)obj2(One)--TO--(Many)obj3

They are setup:

```<code>public class Obj1 {
@Id
private long id;
@ManyToOne(cascade=CascadeType.ALL)
private Obj2 obj2;

public class Obj2 {
@Id
private long id;
@OneToOne
private User planUser
// Other fields
@OneToMany(mappedby = obj2)
private List<Obj1> obj1;
@OneToMany(mappedby obj2)
private List<Obj3> obj3;

public class Obj3 {
@Id
private Long id;
@ManyToOne
private Obj2 obj2;
</code>```

In terms of the view, there is a page called view1 which is for populating Obj1. This works.

There is another page called view2 for :
 1. Displaying some basic details from Obj1
 2. Populating/Updating Obj2 and Obj3

The problem is on submitting view2 to update/create Obj2 and Obj3.

I have tried to get the controller to call methods on the Obj1 Service:

```<code>@Override
@Transactional
public Obj1 associateObj1ToObj2(Long Obj2Id, Obj1 newObj1) {
    final Obj2 obj2 = ojbj2Repository.findOne( obj2Id );
    obj2.getObj1().add( newObj1);
    newObj1.setObj2( obj2 );
    return obj1Repository.save( newObj1 );
}
</code>```

Questions:

Even if I have the @Post in the form controller obj2Repo.save(obj2) when I try to recall it in associateObj1ToObj2- the values that should have been saved (like userPlan) aren't. Why?

Can and should a single root object serve multiple pages in a situation like above? (The suggested alternative apparently is to create a hybrid class to use for backing pages like view2 - link to git example be great (is this called a DTO)).

Is it correct that springboot will not handle the relationship settings, at least in a case where a childs child needs to be updated)

What is the life of the Hibernate session?

Note: By Many relationships really should be called few - the collections on the relationships almost always number less than 10.

This answer seems to be partly related : Could not initialize proxy - no Session

答:
I was going to discuss both sides of using conversation based support frameworks here, however, I think that is irrelevant in hindsight.  While those frameworks can help with the boilerplate necessary to ultimately handle view/controller/domain object consistency, I don't think that changes how you should be designing your controllers and views to interact with users.

I would say most developers often take the stance of sending their entity beans to the view to be that backing bean representation.  For small, non-complex, imo play projects that will suffice but typically this approach starts to break down when entity relationships or UI layouts become complex.

By using non-entities as your backing beans for your view, you allow your UI and View to grow organically without be constrained by decisions and choices to model your database tables and persistence relationships.  It also means that you can leverage database schema design choices without influencing how you layout and interact with users in your UI.   This becomes extremely useful during refactoring your code or improving the user's experience through UI changes.

Even if I have the @Post in the form controller obj2Repo.save(obj2) when I try to recall it in associateObj1ToObj2- the values that should have been saved (like userPlan) aren't. Why?

Did the form actually send that information back in the post?

Lets assume we have a very simple object:

```<code>class SomeEntity {
  private Integer id;
  private String name;
  private String address;
  private List<String> nicknames;
}
</code>```

If all the form allows is the user to change their address but the form doesn't actually send us back the value for name, it'll be empty when we inspect that SomeEntity instance in the controller.  Is that really what we want?  The same happens if you have a relationship.  If the form doesn't actually send us back the list of nick names, that relationship will be empty too.

To me, this highlights why backing beans for views should ultimately represent the view's use case and only that.  We know precisely what fields the view needs and returns and we manage the lifecycle of that data independent of the data which our entity models require to be considered valid both in the perspective of our application and the persistence provider.

Can and should a single root object serve multiple pages in a situation like above? (The suggested alternative apparently is to create a hybrid class to use for backing pages like view2 - link to git example be great (is this called a DTO)).

This is simply a preference design choice.  A single backing bean for a view is perfectly fine.  There are reasons to consider multiple backing beans though:

Treat your view as a composition of smaller pieces.

This allows code reuse of those components in other UI layouts.

Isolate mutable vs immutable form attributes.

Typically I prefer (1) as the default choice.  The only time I advocate the use of (2) are situations where the view has a fair amount of read-only fields giving the user contextual information and they only can mutate a smaller portion of the overall number of attributes.

Is it correct that springboot will not handle the relationship settings, at least in a case where a childs child needs to be updated)

This isn't a spring-boot concern.  A lot of precisely how this happens is dependent on other factors as I have mentioned previously.

What data was serialized in the form and conversely sent back to the controller.

How was the form organized, was it serialized back properly.

Are you using a conversation framework / configuration.

What is the life of the Hibernate session?

This varies depending on your configuration setup.

Spring boot does allow the OpenSessionInView or OpenEntityManagerInView filter to be used which extends the lifecycle of a Hibernate session to the point that the web request has ended.  In my opinion, you should never use this other than for simple prototypes as it comes with its own share of problems, which include performance and unexpected insertions, updates, and deletions based on poor assumptions or code.

Title: Springboot relationship management

Body:
I have a question about using springboot with thymeleaf and relationship management.

I have three objects that needs to be fully bi-directional:

obj1(Many)--TO--(One)obj2(One)--TO--(Many)obj3

They are setup:

public class Obj1 {
@Id
private long id;
@ManyToOne(cascade=CascadeType.ALL)
private Obj2 obj2;

public class Obj2 {
@Id
private long id;
@OneToOne
private User planUser
// Other fields
@OneToMany(mappedby = obj2)
private List<Obj1> obj1;
@OneToMany(mappedby obj2)
private List<Obj3> obj3;

public class Obj3 {
@Id
private Long id;
@ManyToOne
private Obj2 obj2;

In terms of the view, there is a page called view1 which is for populating Obj1. This works.

There is another page called view2 for :
 1. Displaying some basic details from Obj1
 2. Populating/Updating Obj2 and Obj3

The problem is on submitting view2 to update/create Obj2 and Obj3.

I have tried to get the controller to call methods on the Obj1 Service:

@Override
@Transactional
public Obj1 associateObj1ToObj2(Long Obj2Id, Obj1 newObj1) {
    final Obj2 obj2 = ojbj2Repository.findOne( obj2Id );
    obj2.getObj1().add( newObj1);
    newObj1.setObj2( obj2 );
    return obj1Repository.save( newObj1 );
}

Questions:

Even if I have the @Post in the form controller obj2Repo.save(obj2) when I try to recall it in associateObj1ToObj2- the values that should have been saved (like userPlan) aren't. Why?

Can and should a single root object serve multiple pages in a situation like above? (The suggested alternative apparently is to create a hybrid class to use for backing pages like view2 - link to git example be great (is this called a DTO)).

Is it correct that springboot will not handle the relationship settings, at least in a case where a childs child needs to be updated)

What is the life of the Hibernate session?

Note: By Many relationships really should be called few - the collections on the relationships almost always number less than 10.

This answer seems to be partly related : Could not initialize proxy - no Session

Body:
I was going to discuss both sides of using conversation based support frameworks here, however, I think that is irrelevant in hindsight.  While those frameworks can help with the boilerplate necessary to ultimately handle view/controller/domain object consistency, I don't think that changes how you should be designing your controllers and views to interact with users.

I would say most developers often take the stance of sending their entity beans to the view to be that backing bean representation.  For small, non-complex, imo play projects that will suffice but typically this approach starts to break down when entity relationships or UI layouts become complex.

By using non-entities as your backing beans for your view, you allow your UI and View to grow organically without be constrained by decisions and choices to model your database tables and persistence relationships.  It also means that you can leverage database schema design choices without influencing how you layout and interact with users in your UI.   This becomes extremely useful during refactoring your code or improving the user's experience through UI changes.

Even if I have the @Post in the form controller obj2Repo.save(obj2) when I try to recall it in associateObj1ToObj2- the values that should have been saved (like userPlan) aren't. Why?

Did the form actually send that information back in the post?

Lets assume we have a very simple object:

class SomeEntity {
  private Integer id;
  private String name;
  private String address;
  private List<String> nicknames;
}

If all the form allows is the user to change their address but the form doesn't actually send us back the value for name, it'll be empty when we inspect that SomeEntity instance in the controller.  Is that really what we want?  The same happens if you have a relationship.  If the form doesn't actually send us back the list of nick names, that relationship will be empty too.

To me, this highlights why backing beans for views should ultimately represent the view's use case and only that.  We know precisely what fields the view needs and returns and we manage the lifecycle of that data independent of the data which our entity models require to be considered valid both in the perspective of our application and the persistence provider.

Can and should a single root object serve multiple pages in a situation like above? (The suggested alternative apparently is to create a hybrid class to use for backing pages like view2 - link to git example be great (is this called a DTO)).

This is simply a preference design choice.  A single backing bean for a view is perfectly fine.  There are reasons to consider multiple backing beans though:

Treat your view as a composition of smaller pieces.

This allows code reuse of those components in other UI layouts.

Isolate mutable vs immutable form attributes.

Typically I prefer (1) as the default choice.  The only time I advocate the use of (2) are situations where the view has a fair amount of read-only fields giving the user contextual information and they only can mutate a smaller portion of the overall number of attributes.

Is it correct that springboot will not handle the relationship settings, at least in a case where a childs child needs to be updated)

This isn't a spring-boot concern.  A lot of precisely how this happens is dependent on other factors as I have mentioned previously.

What data was serialized in the form and conversely sent back to the controller.

How was the form organized, was it serialized back properly.

Are you using a conversation framework / configuration.

What is the life of the Hibernate session?

This varies depending on your configuration setup.

Spring boot does allow the OpenSessionInView or OpenEntityManagerInView filter to be used which extends the lifecycle of a Hibernate session to the point that the web request has ended.  In my opinion, you should never use this other than for simple prototypes as it comes with its own share of problems, which include performance and unexpected insertions, updates, and deletions based on poor assumptions or code.


问:
Iterate 2 lists of same length; create a list of n consecutive numbers without using generators
I have seen questions asking about creating a list of N numbers in python. Say an input N = 6 should create [0,1,2,3,4,5]. All answers I saw had the range function. Now I am using Python 3. On executing the range function to create a list, I have seen that code executes slowly, popping 1 digit at a time because range is a generator function.

Is there an alternative to create a list of consecutive numbers(assuming a very large one) that doesn't use a generator function like range so that there is no slow down? I can use a C type approach of checking if n < N but is there a more Pythonic way of doing it?

Please run this code in IDLE to understand my question more clearly:

```<code>x = list(range(14))
for n in x:
    print(n)
</code>```

答:
My bad. I checked and found that the delay I was talking about was not because of using the generator. It looks like IDLE executes the print statement slowly as compared to my IDE PyCharm. In Pycharm, all the output is printed together and instantly.

The same code runs much slower in IDLE compared to Pycharm.

Body:
I have seen questions asking about creating a list of N numbers in python. Say an input N = 6 should create [0,1,2,3,4,5]. All answers I saw had the range function. Now I am using Python 3. On executing the range function to create a list, I have seen that code executes slowly, popping 1 digit at a time because range is a generator function.

Is there an alternative to create a list of consecutive numbers(assuming a very large one) that doesn't use a generator function like range so that there is no slow down? I can use a C type approach of checking if n < N but is there a more Pythonic way of doing it?

Please run this code in IDLE to understand my question more clearly:

x = list(range(14))
for n in x:
    print(n)


问:
Best way to sort files by type depending on mimetype
Here is my challenge:

I have a file input with which I can select multiple files. I can easily get access to the mimetype of each of the selected files and manipulate them before they are added to the upload queue. What i want to do is to sort those files into 6 categories.

I have this objects :

```<code>files:{
   audio_type:[],
   video_type:[],
   image_type:[],
   pdf_type:[],
   text_type:[],
   other_type:[]
}
</code>```

For each file added with the file input, i want to be able to put it inside the right category node of my files object above.

The thing is, for each category, i only accept certain mimetype. For example in "audio_type" only the mime types equal to "audio/mpeg" or "audio/wav" should be push, if the file's mimetype is not one of those, it is pushed inside "other_type"

I came up with several basic solution, for example with a regexp " if mimetype begins with image/* put it inside the 'image_type' object", but maybe there is a better / faster / scalable method to do so ? Plus this method does not consider my requirements on some mimetype.

I have the big picture here and i should be able to do it by myself, but not in the cleanest way possible I think.

答:
You could use an object as hash table for the filetypes, like

```<code>var types = {
    "audio/mpeg": "audio_type",
    "audio/wav": "audio_type",
    // ...
    default:  "other_type"
}
</code>```

Usage:

```<code>upload.files[types[object.filetype] || types.default].push(object);
</code>```

Body:
Here is my challenge:

I have a file input with which I can select multiple files. I can easily get access to the mimetype of each of the selected files and manipulate them before they are added to the upload queue. What i want to do is to sort those files into 6 categories.

I have this objects :

files:{
   audio_type:[],
   video_type:[],
   image_type:[],
   pdf_type:[],
   text_type:[],
   other_type:[]
}

For each file added with the file input, i want to be able to put it inside the right category node of my files object above.

The thing is, for each category, i only accept certain mimetype. For example in "audio_type" only the mime types equal to "audio/mpeg" or "audio/wav" should be push, if the file's mimetype is not one of those, it is pushed inside "other_type"

I came up with several basic solution, for example with a regexp " if mimetype begins with image/* put it inside the 'image_type' object", but maybe there is a better / faster / scalable method to do so ? Plus this method does not consider my requirements on some mimetype.

I have the big picture here and i should be able to do it by myself, but not in the cleanest way possible I think.

Body:
You could use an object as hash table for the filetypes, like

var types = {
    "audio/mpeg": "audio_type",
    "audio/wav": "audio_type",
    // ...
    default:  "other_type"
}

Usage:

upload.files[types[object.filetype] || types.default].push(object);


问:
Why is my logout script not logging out
So, I have a registration and login system working perfectly using PHP and MySQL. My logout isn't working. I have my logout button linked to this script, when I click it the page refreshes but i'm still logged in. Any suggestions</p>

```<code><?php
 session_start();
 if (!isset($_SESSION['Name'])) {
 header("Location: ../index.php");
 } else if(isset($_SESSION['Name'])!="") {
 header("Location: Home.php");
 }

 if (isset($_GET['Name'])) {
 unset($_SESSION['Name']);
 session_unset();
 session_destroy();
 header("Location: ../index.php");
 exit;
 }

 ?>
</code>```

答:
You have to correct the line

```<code>else if(isset($_SESSION['Name'])!="")
</code>```

to

```<code>else if(isset($_SESSION['Name']) && $_SESSION['Name'] !="")
</code>```

Otherwise it tries to compare a boolean with a string.

Title: Why is my logout script not logging out

Body:
So, I have a registration and login system working perfectly using PHP and MySQL. My logout isn't working. I have my logout button linked to this script, when I click it the page refreshes but i'm still logged in. Any suggestions

<?php
 session_start();
 if (!isset($_SESSION['Name'])) {
 header("Location: ../index.php");
 } else if(isset($_SESSION['Name'])!="") {
 header("Location: Home.php");
 }

 if (isset($_GET['Name'])) {
 unset($_SESSION['Name']);
 session_unset();
 session_destroy();
 header("Location: ../index.php");
 exit;
 }

 ?>

Body:
You have to correct the line

else if(isset($_SESSION['Name'])!="")

to

else if(isset($_SESSION['Name']) && $_SESSION['Name'] !="")

Otherwise it tries to compare a boolean with a string.


问:
Implicit conversions and pointers?
Why does an implicit conversion not happen when making a float pointer point to an integer, such as when you assign a float variable an integer value?</p>

答:
Because a pointer, well, it needs to point someplace. Because that's what a pointer is. When you have an

```<code>int *p;
</code>```

And you dereference it, like, for example:

```<code>foo(*p);
</code>```

You expect to dereference the pointer and end up with an int.

Now, if you start with a float:

```<code>float *q;
</code>```

And let's say, for the sake of argument, you can do this:

```<code>int *p=q;
</code>```

Then where exactly do you expect this pointer to point to, now? It can't point to wherever q is pointing to. Because the only thing over there is a float.

So, you have to do it yourself, manually:

```<code>int n= (int)*q;
int *p= &n;
</code>```

And, of course, you have to make sure that n remains in scope as long as the p pointer gets dereferenced. And, if *q is changed to a different value, it won't affect what p is pointing to. But those would be different questions...

Title: Implicit conversions and pointers?

Body:
Because a pointer, well, it needs to point someplace. Because that's what a pointer is. When you have an

int *p;

And you dereference it, like, for example:

foo(*p);

You expect to dereference the pointer and end up with an int.

Now, if you start with a float:

float *q;

And let's say, for the sake of argument, you can do this:

int *p=q;

Then where exactly do you expect this pointer to point to, now? It can't point to wherever q is pointing to. Because the only thing over there is a float.

So, you have to do it yourself, manually:

int n= (int)*q;
int *p= &n;

And, of course, you have to make sure that n remains in scope as long as the p pointer gets dereferenced. And, if *q is changed to a different value, it won't affect what p is pointing to. But those would be different questions...


问:
SQL Query to check if student1 has a course with student 2
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

```
Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)
```

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

答:
The idea is that you have to join the table to itself. In the first half you look for user 1 and in the second half you look for user 2. And of course only those rows that have the same id_group in both half are relevant:

```<code>SELECT count(*)
FROM jos_gj_users As j1, jos_gj_users As j2
WHERE j1.id_user = 20 AND j2.id_user = 21
AND j1.id_group = j2.id_group
</code>```

This will always return one row with one column: The number of shared courses. If it is 0, they don't share any courses.

Body:
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

Body:
The idea is that you have to join the table to itself. In the first half you look for user 1 and in the second half you look for user 2. And of course only those rows that have the same id_group in both half are relevant:

SELECT count(*)
FROM jos_gj_users As j1, jos_gj_users As j2
WHERE j1.id_user = 20 AND j2.id_user = 21
AND j1.id_group = j2.id_group

This will always return one row with one column: The number of shared courses. If it is 0, they don't share any courses.


问:
UIImagePickerController Use Photo / Retake buttons don't work
I use default UIImagePickerController for taking photos / choosing them from a library. At some point, I present other ViewController over UIImagePickerController for customization of chosen photo. If a user selects Cancel option, I want to get him back to image choosing screen - in a case of camera source to screen with Use Photo / Retake buttons. After dismissing ViewController with customization buttons don't work (they work before).

I would rather not use AVFoundation here.

Here is some related code:

```<code>let storyBuilder = StoryBuilderViewController.storyboardController()

storyBuilder.delegate = self

photoPickerController.present(storyBuilder, animated: true)
</code>```

This way I'm presenting my customization screen.

```<code>func resetButtonTapped(_ storyBuilder: StoryBuilderViewController) {
    storyBuilder.dismiss(animated: true)
}
</code>```

This code runs after dismissing.

So, nothing special, but buttons stop working

View Hierarchy looks like this:

So, there is nothing over this screen. Buttons properties isEnabled set to true. UIImagePickerController isn't nil. isUserInteractionEnabled is true

I've created a simple project with this error. It doesn't work either.
Also, I've just had a case, when camera stops work entirely, even after app restart, with logs full of errors. Only restart of my phone helps.

More description

I have a start screen - RootViewController. I need to present UIImagePickerController with a camera over it. After a user makes a photo I need to present another controller - EditViewController (not dismissing UIImagePickerController, so if a user wants to take another photo - he just goes back). I do it like this:

```<code>picker(editController, animated: true) //picker - UIImagePickerController, editController - edit controller
</code>```

As I said before, my user can go back - and here is a problem - if I dismiss editController, buttons on UIImagePickerController don't work.

Please, ask some questions, I don't understand, why is it hard to get my issue correctly.

答:
So your problem is that you´re stacking your controllers. You don´t need to do that. Another thing is that your cancel button in your viewController has no usage. You do also need to hold a reference of the UIImagePickerController making it an instance property of your view controller and present it.

Code below:

```<code>import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    let photoPickerController = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        photoPickerController.delegate = self
    }

    @IBAction func cancelBtnTapped(_ sender: UIButton) {
        showFrontCamera()
    }

    @IBAction func showCamera(_ sender: Any) {
        showFrontCamera()
    }

    func showFrontCamera() {
        photoPickerController.sourceType = .camera
        photoPickerController.cameraDevice = .front
        present(photoPickerController, animated: true)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print("didFinishPickingMediaWithInfo")
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            // your image
        }

        picker.dismiss(animated: true){
            // any code after dismissing the controller
        }
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("imagePickerControllerDidCancel")
        picker.dismiss(animated: true){
            // any code after dismissing the controller
        }
    }
}
</code>```

Body:
I use default UIImagePickerController for taking photos / choosing them from a library. At some point, I present other ViewController over UIImagePickerController for customization of chosen photo. If a user selects Cancel option, I want to get him back to image choosing screen - in a case of camera source to screen with Use Photo / Retake buttons. After dismissing ViewController with customization buttons don't work (they work before).

I would rather not use AVFoundation here.

Here is some related code:

let storyBuilder = StoryBuilderViewController.storyboardController()

storyBuilder.delegate = self

photoPickerController.present(storyBuilder, animated: true)

This way I'm presenting my customization screen.

func resetButtonTapped(_ storyBuilder: StoryBuilderViewController) {
    storyBuilder.dismiss(animated: true)
}

This code runs after dismissing.

So, nothing special, but buttons stop working

View Hierarchy looks like this:

So, there is nothing over this screen. Buttons properties isEnabled set to true. UIImagePickerController isn't nil. isUserInteractionEnabled is true

I've created a simple project with this error. It doesn't work either.
Also, I've just had a case, when camera stops work entirely, even after app restart, with logs full of errors. Only restart of my phone helps.

More description

I have a start screen - RootViewController. I need to present UIImagePickerController with a camera over it. After a user makes a photo I need to present another controller - EditViewController (not dismissing UIImagePickerController, so if a user wants to take another photo - he just goes back). I do it like this:

picker(editController, animated: true) //picker - UIImagePickerController, editController - edit controller

As I said before, my user can go back - and here is a problem - if I dismiss editController, buttons on UIImagePickerController don't work.

Please, ask some questions, I don't understand, why is it hard to get my issue correctly.

Body:
So your problem is that you´re stacking your controllers. You don´t need to do that. Another thing is that your cancel button in your viewController has no usage. You do also need to hold a reference of the UIImagePickerController making it an instance property of your view controller and present it.

Code below:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    let photoPickerController = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        photoPickerController.delegate = self
    }

    @IBAction func cancelBtnTapped(_ sender: UIButton) {
        showFrontCamera()
    }

    @IBAction func showCamera(_ sender: Any) {
        showFrontCamera()
    }

    func showFrontCamera() {
        photoPickerController.sourceType = .camera
        photoPickerController.cameraDevice = .front
        present(photoPickerController, animated: true)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print("didFinishPickingMediaWithInfo")
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            // your image
        }

        picker.dismiss(animated: true){
            // any code after dismissing the controller
        }
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("imagePickerControllerDidCancel")
        picker.dismiss(animated: true){
            // any code after dismissing the controller
        }
    }
}


问:
Adding a fade opacity to my Div scroll function?
I've managed to get div(s) to stick at the top offset by 64px on scroll but I also want the same div's opacity to fade to 0. I can't figure out how to add this? An example of what I have done so far.</p>

```<code>$(window).scroll(function(){
  var scrollTop = $(this).scrollTop();
  $(".ComponentOne").css("top",Math.max(64,800-scrollTop));
});
</code>```

答:
css

```<code>.ComponentOne{
    height:100px;
    width:200px;
    background:pink;
    position:absolute;
    top:800px;
    opacity:0;
}
</code>```

js

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

    $(window).scroll(function(){
        var scrollTop = $(this).scrollTop();
        var compTop = $('.ComponentOne').offset().top;

        var controllOpacity = 1400;

        if(scrollTop + 100 > compTop)
        {
            $(".ComponentOne").css("top","64px");
            $(".ComponentOne").css("position","fixed");
            $(".ComponentOne").css("opacity", ((scrollTop - 800)/(controllOpacity - 800)));

        }
        if(scrollTop < 800){
            $(".ComponentOne").css("top","800px");
            $(".ComponentOne").css("position","absolute");
            $(".ComponentOne").css("opacity", ((scrollTop - 800)/(controllOpacity - 800)));
        }

    });

});
</code>```

Just adjust the value of controlOpacity variable according to you. It is used to control the range within which the div should fadeout completely. So if you lower it the div will fadeout quickly as you scoll and if you keep it large then div will fadeout slowly with scroll

JSFiddle for the example

Body:
I've managed to get div(s) to stick at the top offset by 64px on scroll but I also want the same div's opacity to fade to 0. I can't figure out how to add this? An example of what I have done so far.

$(window).scroll(function(){
  var scrollTop = $(this).scrollTop();
  $(".ComponentOne").css("top",Math.max(64,800-scrollTop));
});

Body:
css

.ComponentOne{
    height:100px;
    width:200px;
    background:pink;
    position:absolute;
    top:800px;
    opacity:0;
}

js

$("document").ready(function(){

    $(window).scroll(function(){
        var scrollTop = $(this).scrollTop();
        var compTop = $('.ComponentOne').offset().top;

        var controllOpacity = 1400;

        if(scrollTop + 100 > compTop)
        {
            $(".ComponentOne").css("top","64px");
            $(".ComponentOne").css("position","fixed");
            $(".ComponentOne").css("opacity", ((scrollTop - 800)/(controllOpacity - 800)));

        }
        if(scrollTop < 800){
            $(".ComponentOne").css("top","800px");
            $(".ComponentOne").css("position","absolute");
            $(".ComponentOne").css("opacity", ((scrollTop - 800)/(controllOpacity - 800)));
        }

    });

});

Just adjust the value of controlOpacity variable according to you. It is used to control the range within which the div should fadeout completely. So if you lower it the div will fadeout quickly as you scoll and if you keep it large then div will fadeout slowly with scroll

JSFiddle for the example


问:
Is it possible for Eclipse to only open one JFrame?
When run the project second time, can the previous JFrame closed before open the new one ?

So I no need to close the JFrame when trying to run the project second time.

Is it possible to open only one JFrame?

答:
Apparently, eclipse offers some special options to get what you want.

For other people who might be using a different editor: it's possible, but you'd need some kind of communication between the processes.

What you can do is this, make a server application that runs independently and have it open before you start your regular application. When you run your regular application, connect to the server. This server now messages the other application that was running to close down.

If running a server application is too much trouble, you can run both the server and the client in the same application. When you start the application, check if the designated port is busy, if not, create a server. If it is busy, connect to the server and tell it to shut down. After that, open the server socket in the new application.


问:
One on one mapping between texels and screen pixels in OpenGL
I am doing the following with OpenGL. My screen is of size 512*512. I have a texture of the same size as the screen. I want to draw a quad that covers the whole screen and establishes a one on one mapping between pixels and texels, so that I can do texelFetch with screen coordinates in shaders.

First, if I setup the corners of the quad like the following:

```<code>(-1, 1)+-----------+(1,1)
       |           |
       |           |
       |           |
       |           |
       |           |
(-1,-1)+-----------+(1,-1)
</code>```

and set their corresponding texture coordinates as:

```<code>(0,511)+-----------+(511,511)
       |           |
       |           |
       |           |
       |           |
       |           |
(0,  0)+-----------+(511,0)
</code>```

I just got a white screen using the following fragment shader which tries to assign different colors to its four boundaries:

```<code>#version 330

in vec2 fUV;                              // sent from vertex shader

out vec4 color;

void main() {
    if (fUV.x == 0)                       // leftmost
        color = vec4(1.0, 0.0, 0.0, 1.0);
    else if (fUV.y == 0)                  // bottom
        color = vec4(0.0, 1.0, 0.0, 1.0);
    else if (fUV.x == 511)                // rightmost
        color = vec4(0.0, 0.0, 1.0, 1.0);
    else if (fUV.y == 511)                // top
        color = vec4(1.0, 0.0, 1.0, 1.0);
    else                                  // otherwise
        color = vec4(1.0, 1.0, 1.0, 1.0);

    // check if uv equals an integer
    if (fUV.y == 100)
        color = vec4(0.0, 0.0, 0.0, 1.0);
}
</code>```

which means all equality test have failed.

Secondly, If I add a half pixel width offset d= 1.0 / 512 to all -1 coordinates:

```<code>(-1+d, 1 )+-----------+(1,1)
          |           |
          |           |
          |           |
          |           |
          |           |
(-1+d,-1+d)+-----------+(1,-1+d)
</code>```

keeping other things unchanged, I got the leftmost red line drawn on the screen.

The above results I got are really confusing. Why was only the leftmost column drawn while the bottom row was not?

I would like to know how should I draw a quad and set their coordinates so that I can establish a one on one mapping between pixels and texels.

答:
You misinterpret pixels as points. OpenGL, by default, treats them as squares with half-integer coordinates at the centers. That means that if you submit the following texture coordinates:

```<code>(0,511)+-----------+(511,511)
       |           |
       |           |
       |           |
       |           |
       |           |
(0,  0)+-----------+(511,0)
</code>```

then the bottom right fragment at screen coordinates (511, 0) will be sampled at (511.5, 0.5), and will get the texture coordinates interpolated giving (510.501, 0.499023).

There are a few ways to achieve your goal.

Use the following texture coordinates and truncate:

```<code>(0,512)+-----------+(512,512)
       |           |
       |           |
       |           |
       |           |
       |           |
(0,  0)+-----------+(512,0)
</code>```

Now interpolating the coordinates at (511.5, 0.5) gives (511.5, 0.5), and truncating to integers gives (511, 0), which is the coordinates of the pixel for texelFetch.

Use gl_FragCoord.xy instead of texture coordinates. It contains the same numbers as the interpolated texture coordinates in the previous item.

Use normalized [0,1] texture coordinates and texture instead of texelFetch for lookup:

```<code>(0,1)+-----------+(1,1)
     |           |
     |           |
     |           |
     |           |
     |           |
(0,0)+-----------+(1,0)
</code>```

If your viewport is exactly of the same size as the texture then this will establish an exact mapping between pixels and texels.

This approach is the most flexible and I highly recommend it to the others.

Body:
I am doing the following with OpenGL. My screen is of size 512*512. I have a texture of the same size as the screen. I want to draw a quad that covers the whole screen and establishes a one on one mapping between pixels and texels, so that I can do texelFetch with screen coordinates in shaders.

First, if I setup the corners of the quad like the following:

(-1, 1)+-----------+(1,1)
       |           |
       |           |
       |           |
       |           |
       |           |
(-1,-1)+-----------+(1,-1)

and set their corresponding texture coordinates as:

(0,511)+-----------+(511,511)
       |           |
       |           |
       |           |
       |           |
       |           |
(0,  0)+-----------+(511,0)

I just got a white screen using the following fragment shader which tries to assign different colors to its four boundaries:

#version 330

in vec2 fUV;                              // sent from vertex shader

out vec4 color;

void main() {
    if (fUV.x == 0)                       // leftmost
        color = vec4(1.0, 0.0, 0.0, 1.0);
    else if (fUV.y == 0)                  // bottom
        color = vec4(0.0, 1.0, 0.0, 1.0);
    else if (fUV.x == 511)                // rightmost
        color = vec4(0.0, 0.0, 1.0, 1.0);
    else if (fUV.y == 511)                // top
        color = vec4(1.0, 0.0, 1.0, 1.0);
    else                                  // otherwise
        color = vec4(1.0, 1.0, 1.0, 1.0);

    // check if uv equals an integer
    if (fUV.y == 100)
        color = vec4(0.0, 0.0, 0.0, 1.0);
}

which means all equality test have failed.

Secondly, If I add a half pixel width offset d= 1.0 / 512 to all -1 coordinates:

(-1+d, 1 )+-----------+(1,1)
          |           |
          |           |
          |           |
          |           |
          |           |
(-1+d,-1+d)+-----------+(1,-1+d)

keeping other things unchanged, I got the leftmost red line drawn on the screen.

The above results I got are really confusing. Why was only the leftmost column drawn while the bottom row was not?

I would like to know how should I draw a quad and set their coordinates so that I can establish a one on one mapping between pixels and texels.

Body:
You misinterpret pixels as points. OpenGL, by default, treats them as squares with half-integer coordinates at the centers. That means that if you submit the following texture coordinates:

(0,511)+-----------+(511,511)
       |           |
       |           |
       |           |
       |           |
       |           |
(0,  0)+-----------+(511,0)

then the bottom right fragment at screen coordinates (511, 0) will be sampled at (511.5, 0.5), and will get the texture coordinates interpolated giving (510.501, 0.499023).

There are a few ways to achieve your goal.

Use the following texture coordinates and truncate:

(0,512)+-----------+(512,512)
       |           |
       |           |
       |           |
       |           |
       |           |
(0,  0)+-----------+(512,0)

Now interpolating the coordinates at (511.5, 0.5) gives (511.5, 0.5), and truncating to integers gives (511, 0), which is the coordinates of the pixel for texelFetch.

Use gl_FragCoord.xy instead of texture coordinates. It contains the same numbers as the interpolated texture coordinates in the previous item.

Use normalized [0,1] texture coordinates and texture instead of texelFetch for lookup:

(0,1)+-----------+(1,1)
     |           |
     |           |
     |           |
     |           |
     |           |
(0,0)+-----------+(1,0)

If your viewport is exactly of the same size as the texture then this will establish an exact mapping between pixels and texels.

This approach is the most flexible and I highly recommend it to the others.


问:
How to reference first list item inside ListView?
I would like to add Top Margin on the first item in the ListView. Is that possible?
Or, how can I reference first list item in the List View?

I tried

```<code>lv = (ListView)getListView();
View myRowItem = lv.getChildAt(0);
</code>```

Probably, it doesn't work, because at the moment I executed it, list items didn't exist yet. I assume I should try above code in something like onPostRender event. Is there something like that in Java Android?

答: You would have to create your own adapter, and put that condition in the getView method. However, I'd like to know why you would want to add top margin just to the first item... wouldn't it behaves the same if you put that top margin to the ListView itself?

Body:
I would like to add Top Margin on the first item in the ListView. Is that possible?
Or, how can I reference first list item in the List View?

I tried

lv = (ListView)getListView();
View myRowItem = lv.getChildAt(0);

Probably, it doesn't work, because at the moment I executed it, list items didn't exist yet. I assume I should try above code in something like onPostRender event. Is there something like that in Java Android?


问:
Setters: Consumer vs. direct method call
Why would you use a Consumer

```<code>public Consumer<String> setValue();
</code>```

instead of direct function call

```<code>public void setValue(String value);
</code>```

for setters?

I only see disadvantages:

the direct method call is more readable

another disadvantage of the Consumer variant is, that the calling code must always handle exceptions explicitly

```<code>try {
    instance.setValue().accept("newValue");
} catch (Exception e) {
    // handle exception
}
</code>```

答:
Consumer is an interface intended mostly for internal use within RxJava. Since you are getting started with RxJava, you shouldn't worry about it.

The whole purpose of RxJava is to flow data, the more you use it the less you handle state or use setters.

Body:
Why would you use a Consumer

public Consumer<String> setValue();

instead of direct function call

public void setValue(String value);

for setters?

I only see disadvantages:

the direct method call is more readable

another disadvantage of the Consumer variant is, that the calling code must always handle exceptions explicitly

try {
    instance.setValue().accept("newValue");
} catch (Exception e) {
    // handle exception
}


问:
How to create modules in spring
I am a very very beginner with Spring. And I need to understand how the following problem is soled in Spring.

Lets suppose I have a two pages - cars and car. On cars page list of all cars is generated and user can apply different filters. On car page user can read information about certain car. These are main parts of two pages.

However, both pages contain and two additional modules, lets say ads, and last user comments. Every module has its own logic and can use data from url/post/get. I mean

```<code>-------------------------
|  ----------           |
|  | Ads    |           |
|  ----------    Car[s] |
|  ----------    Page   |
|  | Comms  |           |
|  ----------           |
-------------------------
</code>```

So we see that in result we have two pages and some shared modules. Of course the code of these modules mustn't be duplicated for every page. How are such shared components are created in Spring? Please, give at least the name of the method/component, the rest I can read in internet.

答:
From the backend side you can create request mapping for

@Path(/Cars) ModelAndView cars(...)

@Path(/Car) ModelAndView car(id)

@Path(/Ads) ModelAndView ads(...)

Each path will be connected with handler which could return ModelAndView object. When you will send a request for /cars you handler method will do some operations and also it can invoke method handler for each /car - car(id) and also ads().

```<code>ModelAndView cars(ids) {
   doRequestSpecificOps()
   result = new ModelAndView()
   foreach id in ids
       result put car(id)

   result put ads()
   return result
}
</code>```

From the frontend side you should separate each representation block. It depends on your framework.

Title: How to create modules in spring

Body:
I am a very very beginner with Spring. And I need to understand how the following problem is soled in Spring.

Lets suppose I have a two pages - cars and car. On cars page list of all cars is generated and user can apply different filters. On car page user can read information about certain car. These are main parts of two pages.

However, both pages contain and two additional modules, lets say ads, and last user comments. Every module has its own logic and can use data from url/post/get. I mean

-------------------------
|  ----------           |
|  | Ads    |           |
|  ----------    Car[s] |
|  ----------    Page   |
|  | Comms  |           |
|  ----------           |
-------------------------

So we see that in result we have two pages and some shared modules. Of course the code of these modules mustn't be duplicated for every page. How are such shared components are created in Spring? Please, give at least the name of the method/component, the rest I can read in internet.

Body:
From the backend side you can create request mapping for

@Path(/Cars) ModelAndView cars(...)

@Path(/Car) ModelAndView car(id)

@Path(/Ads) ModelAndView ads(...)

Each path will be connected with handler which could return ModelAndView object. When you will send a request for /cars you handler method will do some operations and also it can invoke method handler for each /car - car(id) and also ads().

ModelAndView cars(ids) {
   doRequestSpecificOps()
   result = new ModelAndView()
   foreach id in ids
       result put car(id)

   result put ads()
   return result
}

From the frontend side you should separate each representation block. It depends on your framework.


问:
UDP torrent trackers not replying
I've finally gotten to the stage of getting a response from a UDP tracker.

Here's an exmaple, that I split into an array:

[ 1,   3765366842, 1908, 0, 2, 0 ]

```<code>Action, request ID, interval, leechers, seeders, peers.
</code>```

No matter which torrent I chose, I get 1/2 seeders, which I'm assuming is the server tracking me, and no peers / leechers.

Am I not using the correct info hash?

This is how I retrieve it from a magnet link:

```<code>magnet:?xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871&dn=Ubuntu+16.04.1+LTS+Desktop+64-bit&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969
</code>```

...

h = 9f9165d9a281a9b8e782cd5176bbcc8256fd1871

Now I split this into chunks of two, and parse them, for hex bytes:

```<code>bytes = [];
for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));
</code>```

[153, 153, 102, 221, 170, 136, 170, 187, 238, 136, 204, 85, 119, 187, 204, 136, 85, 255, 17, 119]

There's no need to encode this, so I send it along with my request.

This is the only point causing trouble, yet it seems so simple...

http://xbtt.sourceforge.net/udp_tracker_protocol.html

答:
9f91

should result in the first two bytes being 159, 145, so your hex-decoding is incorrect.

Beyond that you should compare your implementation with a working one through wireshark.

http://xbtt.sourceforge.net/udp_tracker_protocol.html

As was already mentioned in an answer to another question official and up-to-date specs reside at bittorrent.org, that includes the UDP tracker spec. The xbtt page is not maintained.

Title: UDP torrent trackers not replying

Body:
I've finally gotten to the stage of getting a response from a UDP tracker.

Here's an exmaple, that I split into an array:

[ 1,   3765366842, 1908, 0, 2, 0 ]

Action, request ID, interval, leechers, seeders, peers.

No matter which torrent I chose, I get 1/2 seeders, which I'm assuming is the server tracking me, and no peers / leechers.

Am I not using the correct info hash?

This is how I retrieve it from a magnet link:

magnet:?xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871&dn=Ubuntu+16.04.1+LTS+Desktop+64-bit&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969

...

h = 9f9165d9a281a9b8e782cd5176bbcc8256fd1871

Now I split this into chunks of two, and parse them, for hex bytes:

bytes = [];
for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));

[153, 153, 102, 221, 170, 136, 170, 187, 238, 136, 204, 85, 119, 187, 204, 136, 85, 255, 17, 119]

There's no need to encode this, so I send it along with my request.

This is the only point causing trouble, yet it seems so simple...

http://xbtt.sourceforge.net/udp_tracker_protocol.html


问:
ORDER BY CASE CONDITIONAL BACKGROUND WORKING
I was practicing SQL queries online when I came across this question:

Write a SQL query to find all the details of 1970 winners by the ordered to subject and winner name; but the list contain the subject Economics and Chemistry at last.

Below is the solution for the above question. But I cannot understand the below solution. I surfed the net to look for the understanding of the ORDER BY clause but could not find a clear explanation. I cannot understand what happens when we assign '1' or '0' and why do we do that. I want to know what actually happens when this query gets executed.

```<code>SELECT *
    FROM nobel_win
    WHERE year=1970
    ORDER BY
     CASE
        WHEN subject IN ('Economics','Chemistry') THEN 1
        ELSE 0
     END ASC,
     subject,
     winner;
</code>```

答:
Your first order condition is

```<code> CASE
    WHEN subject IN ('Economics','Chemistry') THEN 1
    ELSE 0
 END ASC
</code>```

This sorts the complete result set first according to that condition.

So all records where subject IN ('Economics','Chemistry') get the order result 1 and all other the order result 0. Then this gets ordered ASC (ascending) - so "0"-records come first, "1"-records second.

You could use any other number in the case statement. 2 and 3 or 20 and 93. It is just an indicator what comes first.

In MySQL the result of a boolean condition automatically evaluates to 1 and 0. So in MySQL you could reduce that to

```<code>order by subject IN ('Economics','Chemistry'),
         subject,
         winner;
</code>```

Body:
I was practicing SQL queries online when I came across this question:

Write a SQL query to find all the details of 1970 winners by the ordered to subject and winner name; but the list contain the subject Economics and Chemistry at last.

Below is the solution for the above question. But I cannot understand the below solution. I surfed the net to look for the understanding of the ORDER BY clause but could not find a clear explanation. I cannot understand what happens when we assign '1' or '0' and why do we do that. I want to know what actually happens when this query gets executed.

SELECT *
    FROM nobel_win
    WHERE year=1970
    ORDER BY
     CASE
        WHEN subject IN ('Economics','Chemistry') THEN 1
        ELSE 0
     END ASC,
     subject,
     winner;

Body:
Your first order condition is

 CASE
    WHEN subject IN ('Economics','Chemistry') THEN 1
    ELSE 0
 END ASC

This sorts the complete result set first according to that condition.

So all records where subject IN ('Economics','Chemistry') get the order result 1 and all other the order result 0. Then this gets ordered ASC (ascending) - so "0"-records come first, "1"-records second.

You could use any other number in the case statement. 2 and 3 or 20 and 93. It is just an indicator what comes first.

In MySQL the result of a boolean condition automatically evaluates to 1 and 0. So in MySQL you could reduce that to

order by subject IN ('Economics','Chemistry'),
         subject,
         winner;


问:
Iterate on a range of iterable
I have interface that returns a iterable object.
I need to iterate on the first 1000 items of it.
What is the best way to combine iterating using Iterator and stop after a certain count is reached.

Thanks

答: I'd use a loop that iterates and have a counter variable incremented; then break out of the loop when the counter reaches 1000.</p>

Title: Iterate on a range of iterable