问:
Unable to save data to composite Table Via Spring Data rest json post
I have 3 Tables in db

training

   - training_id (pk)

user_profile

    - profile_id (pk)

-training_profile (composite table)

   - training_id

  - profile_id

I have already record in user_profile table having profile_id=44 and want to create new record for training table ,and also to associate this new training with already existing user_profile record which has id 44,but after post data is saved to training table but it is not inserted into lookup table user_training.

My Object Classes Are
 - Training Class

```<code>@Entity
@Table(name = "training", schema = "public")
public class Training implements java.io.Serializable {

    @Id @GeneratedValue
    @Column(name = "training_id", unique = true, nullable = false)
    private Long trainingId;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "trainings")
    private Set<UserProfile> userProfiles = new HashSet<UserProfile>(0);

    @Column(name = "training_subject", length = 200)
    private String trainingSubject;

    public Training() {
    }

    public Long getTrainingId() {
        return this.trainingId;
    }

    public void setTrainingId(Long trainingId) {
        this.trainingId = trainingId;
    }

    public String getTrainingSubject() {
        return this.trainingSubject;
    }

    public void setTrainingSubject(String trainingSubject) {
        this.trainingSubject = trainingSubject;
    }

    public Set<UserProfile> getUserProfiles() {
        return this.userProfiles;
    }

    public void setUserProfiles(Set<UserProfile> userProfiles) {
        this.userProfiles = userProfiles;
    }
}
</code>```

UserProfile

@Entity
@Table(name = "user_profile", schema = "public")

public class UserProfile implements java.io.Serializable {

```<code>@Id @GeneratedValue
@Column(name = "profile_id", unique = true, nullable = false)
private Long profileId;

@Column(name = "profile_description")
private String profileDescription;

@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinTable(name = "user_training", schema = "public", joinColumns = {
        @JoinColumn(name = "profile_id", nullable = false, updatable = false) }, inverseJoinColumns = {
                @JoinColumn(name = "training_id", nullable = false, updatable = false) })
private Set<Training> trainings = new HashSet<Training>(0);

public UserProfile() {
}

public String getProfileDescription() {
    return this.profileDescription;
}

public void setProfileDescription(String profileDescription) {
    this.profileDescription = profileDescription;
}

public Set<Training> getTrainings() {
    return this.trainings;
}

public void setTrainings(Set<Training> trainings) {
    this.trainings = trainings;
}
</code>```

}

My json post via postman

And Response I get

Response show that new training record inserted in table having training_id as 67
No association found for this new saved training

again it created new record for training and does not associate with existing user profile , I post curl -i -X POST -H "Content-Type:application/json" -d "{ \"trainingSubject\" : \"Oracle\", \"userProfiles\":[\"/userProfiles/44\"] }" http://localhost:8080/api/trainings

答:
You could use the relative url assignment:

```<code>{
    "trainingSubject": "oracle",
    "userProfiles":["/userProfiles/44"]
}
</code>```

Maybe also try with the full url: http://localhost:8080/api/userProfiles/44

EDITED

If you move the owning site of the ManyToMany relation to Training it will work with the above JSON. So currently the owner is allowed to set the realtions. If you do it like that:

```<code>@ManyToMany
@JoinTable(name = "user_training"
, joinColumns = {@JoinColumn(name = "profile_id") }
, inverseJoinColumns = {@JoinColumn(name = "training_id") })
private List<UserProfile> userProfiles = new ArrayList<>();
</code>```

plus

```<code>@ManyToMany(mappedBy = "userProfiles")
private List<Training> trainings = new ArrayList<>();
</code>```

Training owns the relation within userProfiles.

I think in your case it's the best option for now. Another option would be, when keeping the owner site at UserProfile on transactions, to update the relation there like:

```<code>PATCH http://localhost:8080/api/userProfiles/44
{
    "trainings": ["trainings/66", "trainings/67"]
}
</code>```

But with this you would need multible rest calls (1. POST new training and get the new Id 2. GET current training list 3. PATCH trainings list with newly added training)

Last option would be to add the REST-controller on your own.

Complete files for the first approach:

```<code>@Entity
@Table
public class Training implements Serializable {

    @Id
    @GeneratedValue
    private Long trainingId;

    @ManyToMany
    @JoinTable(name = "user_training"
    , joinColumns = {@JoinColumn(name = "profile_id") }
    , inverseJoinColumns = {@JoinColumn(name = "training_id") })
    private List<UserProfile> userProfiles = new ArrayList<>();

    @Column(name = "training_subject", length = 200)
    private String trainingSubject;

@Entity
@Table
public class UserProfile implements Serializable {

    @Id
    @GeneratedValue
    private Long profileId;

    @Column(name = "profile_description")
    private String profileDescription;

    @ManyToMany(mappedBy = "userProfiles")
    private List<Training> trainings = new ArrayList<>();

public interface TrainingRepository extends JpaRepository<Training, Long> {
}

public interface UserProfileRepository extends JpaRepository<UserProfile, Long> {
}
</code>```

With the upper JSON this will work, I tested it. You will not see the correct result directly in the response of curl-POST. To see the added relation you must follow the userProfiles-link like GET http://localhost:8080/transactions/<newId>/userProfiles

Body:
I have 3 Tables in db

training

   - training_id (pk)

user_profile

    - profile_id (pk)

-training_profile (composite table)

   - training_id

  - profile_id

I have already record in user_profile table having profile_id=44 and want to create new record for training table ,and also to associate this new training with already existing user_profile record which has id 44,but after post data is saved to training table but it is not inserted into lookup table user_training.

My Object Classes Are
 - Training Class

@Entity
@Table(name = "training", schema = "public")
public class Training implements java.io.Serializable {

    @Id @GeneratedValue
    @Column(name = "training_id", unique = true, nullable = false)
    private Long trainingId;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "trainings")
    private Set<UserProfile> userProfiles = new HashSet<UserProfile>(0);

    @Column(name = "training_subject", length = 200)
    private String trainingSubject;

    public Training() {
    }

    public Long getTrainingId() {
        return this.trainingId;
    }

    public void setTrainingId(Long trainingId) {
        this.trainingId = trainingId;
    }

    public String getTrainingSubject() {
        return this.trainingSubject;
    }

    public void setTrainingSubject(String trainingSubject) {
        this.trainingSubject = trainingSubject;
    }

    public Set<UserProfile> getUserProfiles() {
        return this.userProfiles;
    }

    public void setUserProfiles(Set<UserProfile> userProfiles) {
        this.userProfiles = userProfiles;
    }
}

UserProfile

@Entity
@Table(name = "user_profile", schema = "public")

public class UserProfile implements java.io.Serializable {

@Id @GeneratedValue
@Column(name = "profile_id", unique = true, nullable = false)
private Long profileId;

@Column(name = "profile_description")
private String profileDescription;

@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinTable(name = "user_training", schema = "public", joinColumns = {
        @JoinColumn(name = "profile_id", nullable = false, updatable = false) }, inverseJoinColumns = {
                @JoinColumn(name = "training_id", nullable = false, updatable = false) })
private Set<Training> trainings = new HashSet<Training>(0);

public UserProfile() {
}

public String getProfileDescription() {
    return this.profileDescription;
}

public void setProfileDescription(String profileDescription) {
    this.profileDescription = profileDescription;
}

public Set<Training> getTrainings() {
    return this.trainings;
}

public void setTrainings(Set<Training> trainings) {
    this.trainings = trainings;
}

}

My json post via postman

And Response I get

Response show that new training record inserted in table having training_id as 67
No association found for this new saved training

again it created new record for training and does not associate with existing user profile , I post curl -i -X POST -H "Content-Type:application/json" -d "{ \"trainingSubject\" : \"Oracle\", \"userProfiles\":[\"/userProfiles/44\"] }" http://localhost:8080/api/trainings

Body:
You could use the relative url assignment:

{
    "trainingSubject": "oracle",
    "userProfiles":["/userProfiles/44"]
}

Maybe also try with the full url: http://localhost:8080/api/userProfiles/44

EDITED

If you move the owning site of the ManyToMany relation to Training it will work with the above JSON. So currently the owner is allowed to set the realtions. If you do it like that:

@ManyToMany
@JoinTable(name = "user_training"
, joinColumns = {@JoinColumn(name = "profile_id") }
, inverseJoinColumns = {@JoinColumn(name = "training_id") })
private List<UserProfile> userProfiles = new ArrayList<>();

plus

@ManyToMany(mappedBy = "userProfiles")
private List<Training> trainings = new ArrayList<>();

Training owns the relation within userProfiles.

I think in your case it's the best option for now. Another option would be, when keeping the owner site at UserProfile on transactions, to update the relation there like:

PATCH http://localhost:8080/api/userProfiles/44
{
    "trainings": ["trainings/66", "trainings/67"]
}

But with this you would need multible rest calls (1. POST new training and get the new Id 2. GET current training list 3. PATCH trainings list with newly added training)

Last option would be to add the REST-controller on your own.

Complete files for the first approach:

@Entity
@Table
public class Training implements Serializable {

    @Id
    @GeneratedValue
    private Long trainingId;

    @ManyToMany
    @JoinTable(name = "user_training"
    , joinColumns = {@JoinColumn(name = "profile_id") }
    , inverseJoinColumns = {@JoinColumn(name = "training_id") })
    private List<UserProfile> userProfiles = new ArrayList<>();

    @Column(name = "training_subject", length = 200)
    private String trainingSubject;

@Entity
@Table
public class UserProfile implements Serializable {

    @Id
    @GeneratedValue
    private Long profileId;

    @Column(name = "profile_description")
    private String profileDescription;

    @ManyToMany(mappedBy = "userProfiles")
    private List<Training> trainings = new ArrayList<>();

public interface TrainingRepository extends JpaRepository<Training, Long> {
}

public interface UserProfileRepository extends JpaRepository<UserProfile, Long> {
}

With the upper JSON this will work, I tested it. You will not see the correct result directly in the response of curl-POST. To see the added relation you must follow the userProfiles-link like GET http://localhost:8080/transactions/<newId>/userProfiles


来源: stackexchange

问:
Is it save to store server response in SharedPreferences
I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

```<code>private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}
</code>```

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method

   parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
works properly first time when directly from server but when we use this method in another it does not work.

答:
Data stored in SharedPreference does not loss until unless:

You clear it by manually or programmatically.

Any cache clearing application won't clear application cache.

You uninstall your application.

Depending on scenario you can opt from following approach to save/cache your json data/response:

SharedPreference more convenient to use.

Writing it text file as private or public in external/internal storage. Data stored in external store won't loss even if you uninstall application.

If json is big and there is trade off associated with calling server every time you can go creating Sqlite database or can choose ORM tools like ORMLite, GreeDao etc.

Caching library can be used to cache server response.

ContentLicense: CC BY-SA 3.0

Body:
I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method

   parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
works properly first time when directly from server but when we use this method in another it does not work.


问:
convert string to date object give sunday web, GMT 00+ time i need in date formate dd/mm/yyyy
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is </p>

```<code> String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
</code>```

<p>I need same formate in date object not string . </p>

答:
The 'format' method returns a String object from a Date object according to the pattern you specified. What you need is the .parse(String) method, which returns a Date from a String.

```<code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy/dd/MM");
String yourDate = "2017/03/30";
try {
        Date startDate = sdf.parse(yourDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
</code>```

Note that you have to comply with the given pattern, your date must be "2017/03/30". Hope this helps.

Body:
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is

 String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

I need same formate in date object not string .

Body:
The 'format' method returns a String object from a Date object according to the pattern you specified. What you need is the .parse(String) method, which returns a Date from a String.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/dd/MM");
String yourDate = "2017/03/30";
try {
        Date startDate = sdf.parse(yourDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

Note that you have to comply with the given pattern, your date must be "2017/03/30". Hope this helps.


问:
Android Opengl ES dark pixels on edge of objects
I would like to draw you attention to the following pictures

First the original image

then how it is rendered on the  screen

as you can see on the original everything is nice and yellow, the edges have a slight transparency to look smooth.

but when I render I have some darkened pixels that appear.

To avoid the usual answer I get

I use

```<code>gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, GL10.GL_RGBA, width, height, 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer);
</code>```

and not the glutil tool

also

```<code>gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
</code>```

Anybody has a solution for that ?

Thanks

Jason

Edit

I did some digging. in the original image my background is already the same color as the coin and I use an alpha mask.
I've also checked, when I load the bitmap it seems that all the bitmap who have an alpha 0 are automatically set to 0,0,0,0. this might be the problem.

edit
actually it seems to be the issue. I checked the values of the bitmap I open, the values for transparent pixels are 0,0,0,0 instead of the color I set. Is this a problem with Bitmap or how I created my image?

```<code>// Load up, and flip the texture:
            Bitmap temp = BitmapFactory.decodeResource(context.getResources(), resource, opts);
            Bitmap bmp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true);
            temp.recycle();
</code>```

答:
Your image probably has premultipled alpha values.  Try using gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);

See this post for more details.

ContentLicense: CC BY-SA 2.5

Body:
I would like to draw you attention to the following pictures

First the original image

then how it is rendered on the  screen

as you can see on the original everything is nice and yellow, the edges have a slight transparency to look smooth.

but when I render I have some darkened pixels that appear.

To avoid the usual answer I get

I use

gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, GL10.GL_RGBA, width, height, 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer);

and not the glutil tool

also

gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

Anybody has a solution for that ?

Thanks

Jason

Edit

I did some digging. in the original image my background is already the same color as the coin and I use an alpha mask.
I've also checked, when I load the bitmap it seems that all the bitmap who have an alpha 0 are automatically set to 0,0,0,0. this might be the problem.

edit
actually it seems to be the issue. I checked the values of the bitmap I open, the values for transparent pixels are 0,0,0,0 instead of the color I set. Is this a problem with Bitmap or how I created my image?

// Load up, and flip the texture:
            Bitmap temp = BitmapFactory.decodeResource(context.getResources(), resource, opts);
            Bitmap bmp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true);
            temp.recycle();


问:
selecting rank from millions of records
I will ask SO for help since I could not find similar situation, questions/post with my question

Assuming I have millions of records, columns are

user_id - assuming its recorded from 1 to 1,000,000

name - assume its also recorded up to 20 characters in alphabet

score - 0 to 100 assuming its also recorded

date - date it was recorded (timestamp)

```<code>user_id |   name   | score |        date       |
------------------------------------------------
23131   |   name1  |   15  | 2017-01-04 02:01:25
26824   |   name2  |   63  | 2017-01-04 02:41:33
19684   |   name3  |   28  | 2017-01-04 02:56:15
74937   |   name4  |   01  | 2017-01-04 04:07:55
27486   |   name5  |   75  | 2017-01-04 13:07:45
86476   |   name6  |   56  | 2017-01-04 14:21:47
36479   |   name7  |   19  | 2017-01-04 17:11:15
86752   |   name8  |   38  | 2017-01-04 18:22:23
11267   |   name9  |  100  | 2017-01-04 20:34:42
88763   |   name10 |   89  | 2017-01-04 22:45:43
</code>```

I want to know my own rank assuming I know what my user_id is

I also want to get other 10 user records above and below my ranking, let's say my rank is 100, I also want to select user with rank of 90 to 99 (above my rank) and 101 to 110 (below my rank).

if different user has same score order rank by date recorded, earlier record has higher rank.

is it possible?

assuming all records are unique and no index are set.

I know how to sort ranking

```<code>SELECT * FROM record order by score
</code>```

but this would let me select all the records, what are the practical way of selecting specific data without selecting every record?

here is what I would like to achieve

```<code>user_id |   name   | score |        date          |     rank     |
------------------------------------------------------------------
12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
11322   |   namee  |   71  | 2017-01-04 22:51:54  |     109      |
86633   |   namew  |   70  | 2017-01-04 22:55:33  |     110      |
</code>```

ok so here is what I got as of now, sorry that I did not mention anything about not using union or union all, I cannot use that in my project.

but anyway here is my query
I used "multi_query()" function

```<code>$sql = "SELECT score, date FROM table_name WHERE user_id=your_user_id;" //assume you already know your user_id
$sql .= "SELECT name, score, date FROM table_name WHERE score >= your_score ORDER BY score, date LIMIT 10;"; //to get 10 rows that have greater or same score of your score order by date, earlier date is higher rank if score is the same with other user.
$sql .= "SELECT name, score, date table_name WHERE score <= your_score DESC, date ASC LIMIT 10"; //select score less than or equal to my score order by score and date
</code>```

and I get something like this

```<code>my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
</code>```

```<code>12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
</code>```

```<code>74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
</code>```

my problem is when using multiple query, it is still the same as doing 3 different query since I have 3 queries, how can I combine it as one? without using union or union all?

and on the 3rd query how can I set my starting point from my data?

答:
In MySQL, view is like a function in other languages.

```<code>CREATE VIEW rankall AS SELECT * FROM record ORDER BY score;

SELECT * FROM rankall
    WHERE rank > (SELECT rank FROM rankall WHERE user_id = ID) - 11
    AND rank < (SELECT rank FROM rankall WHERE user_id = ID) + 11;
</code>```

That's the basic idea, but no guarantee that above code will work :P

Title: selecting rank from millions of records

Body:
I will ask SO for help since I could not find similar situation, questions/post with my question

Assuming I have millions of records, columns are

user_id - assuming its recorded from 1 to 1,000,000

name - assume its also recorded up to 20 characters in alphabet

score - 0 to 100 assuming its also recorded

date - date it was recorded (timestamp)

user_id |   name   | score |        date       |
------------------------------------------------
23131   |   name1  |   15  | 2017-01-04 02:01:25
26824   |   name2  |   63  | 2017-01-04 02:41:33
19684   |   name3  |   28  | 2017-01-04 02:56:15
74937   |   name4  |   01  | 2017-01-04 04:07:55
27486   |   name5  |   75  | 2017-01-04 13:07:45
86476   |   name6  |   56  | 2017-01-04 14:21:47
36479   |   name7  |   19  | 2017-01-04 17:11:15
86752   |   name8  |   38  | 2017-01-04 18:22:23
11267   |   name9  |  100  | 2017-01-04 20:34:42
88763   |   name10 |   89  | 2017-01-04 22:45:43

I want to know my own rank assuming I know what my user_id is

I also want to get other 10 user records above and below my ranking, let's say my rank is 100, I also want to select user with rank of 90 to 99 (above my rank) and 101 to 110 (below my rank).

if different user has same score order rank by date recorded, earlier record has higher rank.

is it possible?

assuming all records are unique and no index are set.

I know how to sort ranking

SELECT * FROM record order by score

but this would let me select all the records, what are the practical way of selecting specific data without selecting every record?

here is what I would like to achieve

user_id |   name   | score |        date          |     rank     |
------------------------------------------------------------------
12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
11322   |   namee  |   71  | 2017-01-04 22:51:54  |     109      |
86633   |   namew  |   70  | 2017-01-04 22:55:33  |     110      |

ok so here is what I got as of now, sorry that I did not mention anything about not using union or union all, I cannot use that in my project.

but anyway here is my query
I used "multi_query()" function

$sql = "SELECT score, date FROM table_name WHERE user_id=your_user_id;" //assume you already know your user_id
$sql .= "SELECT name, score, date FROM table_name WHERE score >= your_score ORDER BY score, date LIMIT 10;"; //to get 10 rows that have greater or same score of your score order by date, earlier date is higher rank if score is the same with other user.
$sql .= "SELECT name, score, date table_name WHERE score <= your_score DESC, date ASC LIMIT 10"; //select score less than or equal to my score order by score and date

and I get something like this

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |

my problem is when using multiple query, it is still the same as doing 3 different query since I have 3 queries, how can I combine it as one? without using union or union all?

and on the 3rd query how can I set my starting point from my data?

Body:
In MySQL, view is like a function in other languages.

CREATE VIEW rankall AS SELECT * FROM record ORDER BY score;

SELECT * FROM rankall
    WHERE rank > (SELECT rank FROM rankall WHERE user_id = ID) - 11
    AND rank < (SELECT rank FROM rankall WHERE user_id = ID) + 11;

That's the basic idea, but no guarantee that above code will work :P


问:
when i set icon to drawer menu then the drawer menu become slow in android

I'm new in Android

when i set icon in drawer_menu.xml code then after when i open the
  navigation drawer menu it open slowly why?

If any one have answer to this question or ever faced this type of
  issues then plz reply to this question.

Here is my drawer_menu.xml code.

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/home_id"
            android:icon="@drawable/home"
            android:title="Home"></item>

        <item
            android:id="@+id/id_setting"
            android:icon="@drawable/setting"
            android:title="Settings"></item>
    </group>

    <item android:title="Others">
        <menu>
            <item
                android:id="@+id/notifications"
                android:icon="@drawable/noti"
                android:title="Notifications"></item>

            <item
                android:id="@+id/about_us"
                android:icon="@drawable/aboutus"
                android:title="About us"></item>
        </menu>

    </item>

</menu>
</code>```

答:
What is the size of icon?
use 300*300 </p>

Body:
I'm new in Android

when i set icon in drawer_menu.xml code then after when i open the
  navigation drawer menu it open slowly why?

If any one have answer to this question or ever faced this type of
  issues then plz reply to this question.

Here is my drawer_menu.xml code.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/home_id"
            android:icon="@drawable/home"
            android:title="Home"></item>

        <item
            android:id="@+id/id_setting"
            android:icon="@drawable/setting"
            android:title="Settings"></item>
    </group>

    <item android:title="Others">
        <menu>
            <item
                android:id="@+id/notifications"
                android:icon="@drawable/noti"
                android:title="Notifications"></item>

            <item
                android:id="@+id/about_us"
                android:icon="@drawable/aboutus"
                android:title="About us"></item>
        </menu>

    </item>

</menu>

Body:
What is the size of icon?
use 300*300


问:
draw sphere in OpenGL 4.0
my OpenGL version is 4.0. I would like to draw a sphere through latitude and longitude. I use this method:

```<code>x=ρsinϕcosθ
y=ρsinϕsinθ
z=ρcosϕ
</code>```

This is a part of my code:

```<code>glm::vec3 buffer[1000];
glm::vec3 outer;
buffercount = 1000;
float section = 10.0f;
GLfloat  alpha, beta;
int index = 0;
for (alpha = 0.0 ; alpha <= PI; alpha += PI/section)
{
    for (beta = 0.0 ; beta <= 2* PI; beta += PI/section)
    {

        outer.x = radius*cos(beta)*sin(alpha);
        outer.y = radius*sin(beta)*sin(alpha);
        outer.z = radius*cos(alpha);

        buffer[index] = outer;
        index = index +1;

    }

}

GLuint sphereVBO, sphereVAO;

glGenVertexArrays(1, &sphereVAO);
glGenBuffers(1,&sphereVBO);
glBindVertexArray(sphereVAO);

glBindBuffer(GL_ARRAY_BUFFER,sphereVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec3) *buffercount  ,&buffer[0], GL_STATIC_DRAW);

glEnableVertexAttribArray(0);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
...
while (!glfwWindowShouldClose(window))
{
...
...

 for (GLuint i = 0; i < buffercount; i++)
    {
        ...
        ...
        glm::mat4 model;
        model = glm::translate(model, buffer[i]);
        GLfloat angle = 10.0f * i;
        model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f));
        glUniformMatrix4fv(modelMat, 1, GL_FALSE, glm::value_ptr(model));
    }

    glDrawArrays(GL_TRIANGLE_FAN, 0, 900);
    glfwSwapBuffers(window);
}
</code>```

if section = 5, the performance is like this:

if section = 20. the performance is like this:

I think that I might have logic problem in my code. I am struggle in this problem...

-----update-----

I edited my code, It doesn't have any error, but I got a blank screen. I guess that something wrong in my vertex shader. I might pass wrong variables to vertex sheder. Please help me.

gluperspective is deprecated in my OpenGL 4.1
I switch to :

```<code>float aspect=float(4.0f)/float(3.0f);
glm::mat4 projection_matrix =  glm::perspective(60.0f/aspect,aspect,0.1f,100.0f);
</code>```

It shows that this error:  constant expression evaluates to -1 which cannot be narrowed to type 'GLuint'(aka 'unsigned int')

```<code>GLuint sphere_vbo[4]={-1,-1,-1,-1};
GLuint sphere_vao[4]={-1,-1,-1,-1};
</code>```

I'm not sure how to revise it...I switch to:

```<code>GLuint sphere_vbo[4]={1,1,1,1};
GLuint sphere_vao[4]={1,1,1,1};
</code>```

I put Spektre's code in spherer.h file

This is a part of my main.cpp file:

```<code>...
...
Shader shader("basic.vert", "basic.frag");

sphere_init();

while (!glfwWindowShouldClose(window))
{

    glfwPollEvents();

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    shader.Use();

    GLuint MatrixID = glGetUniformLocation(shader.Program, "MVP");

    GLfloat radius = 10.0f;
    GLfloat camX = sin(glfwGetTime()) * radius;
    GLfloat camZ = cos(glfwGetTime()) * radius;

    // view matrix
    glm::mat4 view;
    view = glm::lookAt(glm::vec3(camX, 0.0, camZ), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
    glm::mat4 view_matrix  = view;

    // projection matrix
    float aspect=float(4.0f)/float(3.0f);
    glm::mat4 projection_matrix = glm::perspective(60.0f/aspect,aspect,0.1f,100.0f);

    // model matrix
    glm::mat4 model_matrix = glm::mat4(1.0f);// identity

    //ModelViewProjection
    glm::mat4 model_view_projection = projection_matrix * view_matrix * model_matrix;

    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &model_view_projection[0][0]);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-10.0);

    glEnable(GL_DEPTH_TEST);
    glDisable(GL_TEXTURE_2D);
    sphere_draw();
    glFlush();
    glfwSwapBuffers(window);
}

sphere_exit();
glfwTerminate();
return 0;
}
</code>```

This is my vertex shader file:

```<code>#version 410 core

uniform mat4 MVP;

layout(location = 0) in vec3 vertexPosition_modelspace;
out vec4 vertexColor;

void main()
{
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
    vertexColor = vec4(0, 1, 0, 1.0);
}
</code>```

I added error-check function get_log in my shader.h file.

```<code>...
...
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
get_log(vertex);

...
...
void get_log(GLuint shader){

GLint isCompiled = 0;
    GLchar infoLog[1024];
    glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
    if(isCompiled == GL_FALSE)
    {
        printf("----error--- \n");
        GLint maxLength = 0;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
        glGetShaderInfoLog(shader, 1024, NULL, infoLog);
        std::cout << "| ERROR::::" << &infoLog << "\n| -- ------------------    --------------------------------- -- |" << std::endl;

        glDeleteShader(shader); // Don't leak the shader.

    }else{
        printf("---no error --- \n");
    }

}
</code>```

I tested both fragment shader and vertex shader, it both showed ---no error---

答:
As I mentioned in the comments you need to add indices to your mesh VAO/VBO. Not sure why GL_QUADS is not implemented on your machine that makes no sense as it is basic primitive so to make this easy to handle I use only GL_TRIANGLES which is far from ideal but what to heck ... Try this:

//---------------------------------------------------------------------------
const int na=36;        // vertex grid size
const int nb=18;
const int na3=na*3;     // line in grid size
const int nn=nb*na3;    // whole grid size
GLfloat sphere_pos[nn]; // vertex
GLfloat sphere_nor[nn]; // normal
//GLfloat sphere_col[nn];   // color
GLuint  sphere_ix [na*(nb-1)*6];    // indices
GLuint sphere_vbo[4]={-1,-1,-1,-1};
GLuint sphere_vao[4]={-1,-1,-1,-1};

void sphere_init()
    {
    // generate the sphere data
    GLfloat x,y,z,a,b,da,db,r=3.5;
    int ia,ib,ix,iy;
    da=2.0*M_PI/GLfloat(na);
    db=    M_PI/GLfloat(nb-1);
    // [Generate sphere point data]
    // spherical angles a,b covering whole sphere surface
    for (ix=0,b=-0.5*M_PI,ib=0;ib<nb;ib++,b+=db)
     for (a=0.0,ia=0;ia<na;ia++,a+=da,ix+=3)
        {
        // unit sphere
        x=cos(b)*cos(a);
        y=cos(b)*sin(a);
        z=sin(b);
        sphere_pos[ix+0]=x*r;
        sphere_pos[ix+1]=y*r;
        sphere_pos[ix+2]=z*r;
        sphere_nor[ix+0]=x;
        sphere_nor[ix+1]=y;
        sphere_nor[ix+2]=z;
        }
    // [Generate GL_TRIANGLE indices]
    for (ix=0,iy=0,ib=1;ib<nb;ib++)
        {
        for (ia=1;ia<na;ia++,iy++)
            {
            // first half of QUAD
            sphere_ix[ix]=iy;      ix++;
            sphere_ix[ix]=iy+1;    ix++;
            sphere_ix[ix]=iy+na;   ix++;
            // second half of QUAD
            sphere_ix[ix]=iy+na;   ix++;
            sphere_ix[ix]=iy+1;    ix++;
            sphere_ix[ix]=iy+na+1; ix++;
            }
        // first half of QUAD
        sphere_ix[ix]=iy;       ix++;
        sphere_ix[ix]=iy+1-na;  ix++;
        sphere_ix[ix]=iy+na;    ix++;
        // second half of QUAD
        sphere_ix[ix]=iy+na;    ix++;
        sphere_ix[ix]=iy-na+1;  ix++;
        sphere_ix[ix]=iy+1;     ix++;
        iy++;
        }
    // [VAO/VBO stuff]
    GLuint i;
    glGenVertexArrays(4,sphere_vao);
    glGenBuffers(4,sphere_vbo);
    glBindVertexArray(sphere_vao[0]);
    i=0; // vertex
    glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_pos),sphere_pos,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
    i=1; // indices
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(sphere_ix),sphere_ix,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,4,GL_UNSIGNED_INT,GL_FALSE,0,0);
    i=2; // normal
    glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_nor),sphere_nor,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
/*
    i=3; // color
    glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_col),sphere_col,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
*/
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    }
void sphere_exit()
    {
    glDeleteVertexArrays(4,sphere_vao);
    glDeleteBuffers(4,sphere_vbo);
    }
void sphere_draw()
    {
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glBindVertexArray(sphere_vao[0]);
//  glDrawArrays(GL_POINTS,0,sizeof(sphere_pos)/sizeof(GLfloat));                   // POINTS ... no indices for debug
    glDrawElements(GL_TRIANGLES,sizeof(sphere_ix)/sizeof(GLuint),GL_UNSIGNED_INT,0);    // indices (choose just one line not both !!!)
    glBindVertexArray(0);
    }

void gl_draw()
    {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float aspect=float(xs)/float(ys);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0/aspect,aspect,0.1,100.0);
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-10.0);

    glEnable(GL_DEPTH_TEST);
    glDisable(GL_TEXTURE_2D);
    sphere_draw();

    glFlush();
    SwapBuffers(hdc);
    }
//---------------------------------------------------------------------------
```

Usage is simple after OpenGL context is created and extensions loaded call sphere_init() before closing app call sphere_exit() (while OpenGL context is still running) and when you want to render call sphere_draw(). I make an gl_draw() example with some settings and here the preview of it:

The point is to create 2D grid of points covering whole surface of sphere (via spherical long,lat a,b angles) and then just create triangles covering whole grid...

Title: draw sphere in OpenGL 4.0

Body:
my OpenGL version is 4.0. I would like to draw a sphere through latitude and longitude. I use this method:

x=ρsinϕcosθ
y=ρsinϕsinθ
z=ρcosϕ

This is a part of my code:

glm::vec3 buffer[1000];
glm::vec3 outer;
buffercount = 1000;
float section = 10.0f;
GLfloat  alpha, beta;
int index = 0;
for (alpha = 0.0 ; alpha <= PI; alpha += PI/section)
{
    for (beta = 0.0 ; beta <= 2* PI; beta += PI/section)
    {

        outer.x = radius*cos(beta)*sin(alpha);
        outer.y = radius*sin(beta)*sin(alpha);
        outer.z = radius*cos(alpha);

        buffer[index] = outer;
        index = index +1;

    }

}

GLuint sphereVBO, sphereVAO;

glGenVertexArrays(1, &sphereVAO);
glGenBuffers(1,&sphereVBO);
glBindVertexArray(sphereVAO);

glBindBuffer(GL_ARRAY_BUFFER,sphereVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec3) *buffercount  ,&buffer[0], GL_STATIC_DRAW);

glEnableVertexAttribArray(0);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
...
while (!glfwWindowShouldClose(window))
{
...
...

 for (GLuint i = 0; i < buffercount; i++)
    {
        ...
        ...
        glm::mat4 model;
        model = glm::translate(model, buffer[i]);
        GLfloat angle = 10.0f * i;
        model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f));
        glUniformMatrix4fv(modelMat, 1, GL_FALSE, glm::value_ptr(model));
    }

    glDrawArrays(GL_TRIANGLE_FAN, 0, 900);
    glfwSwapBuffers(window);
}

if section = 5, the performance is like this:

if section = 20. the performance is like this:

I think that I might have logic problem in my code. I am struggle in this problem...

-----update-----

I edited my code, It doesn't have any error, but I got a blank screen. I guess that something wrong in my vertex shader. I might pass wrong variables to vertex sheder. Please help me.

gluperspective is deprecated in my OpenGL 4.1
I switch to :

float aspect=float(4.0f)/float(3.0f);
glm::mat4 projection_matrix =  glm::perspective(60.0f/aspect,aspect,0.1f,100.0f);

It shows that this error:  constant expression evaluates to -1 which cannot be narrowed to type 'GLuint'(aka 'unsigned int')

GLuint sphere_vbo[4]={-1,-1,-1,-1};
GLuint sphere_vao[4]={-1,-1,-1,-1};

I'm not sure how to revise it...I switch to:

GLuint sphere_vbo[4]={1,1,1,1};
GLuint sphere_vao[4]={1,1,1,1};

I put Spektre's code in spherer.h file

This is a part of my main.cpp file:

...
...
Shader shader("basic.vert", "basic.frag");

sphere_init();

while (!glfwWindowShouldClose(window))
{

    glfwPollEvents();

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    shader.Use();

    GLuint MatrixID = glGetUniformLocation(shader.Program, "MVP");

    GLfloat radius = 10.0f;
    GLfloat camX = sin(glfwGetTime()) * radius;
    GLfloat camZ = cos(glfwGetTime()) * radius;

    // view matrix
    glm::mat4 view;
    view = glm::lookAt(glm::vec3(camX, 0.0, camZ), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
    glm::mat4 view_matrix  = view;

    // projection matrix
    float aspect=float(4.0f)/float(3.0f);
    glm::mat4 projection_matrix = glm::perspective(60.0f/aspect,aspect,0.1f,100.0f);

    // model matrix
    glm::mat4 model_matrix = glm::mat4(1.0f);// identity

    //ModelViewProjection
    glm::mat4 model_view_projection = projection_matrix * view_matrix * model_matrix;

    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &model_view_projection[0][0]);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-10.0);

    glEnable(GL_DEPTH_TEST);
    glDisable(GL_TEXTURE_2D);
    sphere_draw();
    glFlush();
    glfwSwapBuffers(window);
}

sphere_exit();
glfwTerminate();
return 0;
}

This is my vertex shader file:

#version 410 core

uniform mat4 MVP;

layout(location = 0) in vec3 vertexPosition_modelspace;
out vec4 vertexColor;

void main()
{
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
    vertexColor = vec4(0, 1, 0, 1.0);
}

I added error-check function get_log in my shader.h file.

...
...
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
get_log(vertex);

...
...
void get_log(GLuint shader){

GLint isCompiled = 0;
    GLchar infoLog[1024];
    glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
    if(isCompiled == GL_FALSE)
    {
        printf("----error--- \n");
        GLint maxLength = 0;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
        glGetShaderInfoLog(shader, 1024, NULL, infoLog);
        std::cout << "| ERROR::::" << &infoLog << "\n| -- ------------------    --------------------------------- -- |" << std::endl;

        glDeleteShader(shader); // Don't leak the shader.

    }else{
        printf("---no error --- \n");
    }

}

I tested both fragment shader and vertex shader, it both showed ---no error---

Body:
As I mentioned in the comments you need to add indices to your mesh VAO/VBO. Not sure why GL_QUADS is not implemented on your machine that makes no sense as it is basic primitive so to make this easy to handle I use only GL_TRIANGLES which is far from ideal but what to heck ... Try this:

//---------------------------------------------------------------------------
const int na=36;        // vertex grid size
const int nb=18;
const int na3=na*3;     // line in grid size
const int nn=nb*na3;    // whole grid size
GLfloat sphere_pos[nn]; // vertex
GLfloat sphere_nor[nn]; // normal
//GLfloat sphere_col[nn];   // color
GLuint  sphere_ix [na*(nb-1)*6];    // indices
GLuint sphere_vbo[4]={-1,-1,-1,-1};
GLuint sphere_vao[4]={-1,-1,-1,-1};

void sphere_init()
    {
    // generate the sphere data
    GLfloat x,y,z,a,b,da,db,r=3.5;
    int ia,ib,ix,iy;
    da=2.0*M_PI/GLfloat(na);
    db=    M_PI/GLfloat(nb-1);
    // [Generate sphere point data]
    // spherical angles a,b covering whole sphere surface
    for (ix=0,b=-0.5*M_PI,ib=0;ib<nb;ib++,b+=db)
     for (a=0.0,ia=0;ia<na;ia++,a+=da,ix+=3)
        {
        // unit sphere
        x=cos(b)*cos(a);
        y=cos(b)*sin(a);
        z=sin(b);
        sphere_pos[ix+0]=x*r;
        sphere_pos[ix+1]=y*r;
        sphere_pos[ix+2]=z*r;
        sphere_nor[ix+0]=x;
        sphere_nor[ix+1]=y;
        sphere_nor[ix+2]=z;
        }
    // [Generate GL_TRIANGLE indices]
    for (ix=0,iy=0,ib=1;ib<nb;ib++)
        {
        for (ia=1;ia<na;ia++,iy++)
            {
            // first half of QUAD
            sphere_ix[ix]=iy;      ix++;
            sphere_ix[ix]=iy+1;    ix++;
            sphere_ix[ix]=iy+na;   ix++;
            // second half of QUAD
            sphere_ix[ix]=iy+na;   ix++;
            sphere_ix[ix]=iy+1;    ix++;
            sphere_ix[ix]=iy+na+1; ix++;
            }
        // first half of QUAD
        sphere_ix[ix]=iy;       ix++;
        sphere_ix[ix]=iy+1-na;  ix++;
        sphere_ix[ix]=iy+na;    ix++;
        // second half of QUAD
        sphere_ix[ix]=iy+na;    ix++;
        sphere_ix[ix]=iy-na+1;  ix++;
        sphere_ix[ix]=iy+1;     ix++;
        iy++;
        }
    // [VAO/VBO stuff]
    GLuint i;
    glGenVertexArrays(4,sphere_vao);
    glGenBuffers(4,sphere_vbo);
    glBindVertexArray(sphere_vao[0]);
    i=0; // vertex
    glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_pos),sphere_pos,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
    i=1; // indices
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(sphere_ix),sphere_ix,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,4,GL_UNSIGNED_INT,GL_FALSE,0,0);
    i=2; // normal
    glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_nor),sphere_nor,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
/*
    i=3; // color
    glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_col),sphere_col,GL_STATIC_DRAW);
    glEnableVertexAttribArray(i);
    glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
*/
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    }
void sphere_exit()
    {
    glDeleteVertexArrays(4,sphere_vao);
    glDeleteBuffers(4,sphere_vbo);
    }
void sphere_draw()
    {
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glBindVertexArray(sphere_vao[0]);
//  glDrawArrays(GL_POINTS,0,sizeof(sphere_pos)/sizeof(GLfloat));                   // POINTS ... no indices for debug
    glDrawElements(GL_TRIANGLES,sizeof(sphere_ix)/sizeof(GLuint),GL_UNSIGNED_INT,0);    // indices (choose just one line not both !!!)
    glBindVertexArray(0);
    }

void gl_draw()
    {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float aspect=float(xs)/float(ys);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0/aspect,aspect,0.1,100.0);
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-10.0);

    glEnable(GL_DEPTH_TEST);
    glDisable(GL_TEXTURE_2D);
    sphere_draw();

    glFlush();
    SwapBuffers(hdc);
    }
//---------------------------------------------------------------------------

Usage is simple after OpenGL context is created and extensions loaded call sphere_init() before closing app call sphere_exit() (while OpenGL context is still running) and when you want to render call sphere_draw(). I make an gl_draw() example with some settings and here the preview of it:

The point is to create 2D grid of points covering whole surface of sphere (via spherical long,lat a,b angles) and then just create triangles covering whole grid...


问:
Scroll using setContentOffSet button
I am trying to figure out Scroll Views and how to make them scroll programatically.

I have set up 2 screens (image views) in one view controller.

I add contraints to the image views and the scroll view by selecting the top bottom left and right, and the height and width.

My view controller has this

```<code>import UIKit

class ViewController: UIViewController {
var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override var prefersStatusBarHidden: Bool {
    return true
}

@IBAction func toFloorplan(_ sender: Any) {
    scrollView.setContentOffset(CGPoint(x:1366, y:0), animated: false)
}}
</code>```

and a simple button that calls toFloorPlan.

I can scroll left and right using paging, but when I click the button, my app quits and I get the following print out. Thanks for your help!!

2017-03-30 18:20:13.423801 VHThenNow[78847:14546188] [LayoutConstraints] Unable to simultaneously satisfy constraints.
      Probably at least one of the constraints in the following list is one you don't want.
      Try this:
          (1) look at each constraint and try to figure out which you don't expect;
          (2) find the code that added the unwanted constraint or constraints and fix it.
  (
      "",
      "",
      "",
      ""
  )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
  The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in  may also be helpful.
  fatal error: unexpectedly found nil while unwrapping an Optional value
  (lldb)

答:
```<code>@IBOutlet weak var scrollView: UIScrollView!
</code>```

And create outlet - connect scrollview in storyboard with scrollview variable.

Your constraint wrong but it does not reason of crash

Title: Scroll using setContentOffSet button

Body:
I am trying to figure out Scroll Views and how to make them scroll programatically.

I have set up 2 screens (image views) in one view controller.

I add contraints to the image views and the scroll view by selecting the top bottom left and right, and the height and width.

My view controller has this

import UIKit

class ViewController: UIViewController {
var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override var prefersStatusBarHidden: Bool {
    return true
}

@IBAction func toFloorplan(_ sender: Any) {
    scrollView.setContentOffset(CGPoint(x:1366, y:0), animated: false)
}}

and a simple button that calls toFloorPlan.

I can scroll left and right using paging, but when I click the button, my app quits and I get the following print out. Thanks for your help!!

2017-03-30 18:20:13.423801 VHThenNow[78847:14546188] [LayoutConstraints] Unable to simultaneously satisfy constraints.
      Probably at least one of the constraints in the following list is one you don't want.
      Try this:
          (1) look at each constraint and try to figure out which you don't expect;
          (2) find the code that added the unwanted constraint or constraints and fix it.
  (
      "",
      "",
      "",
      ""
  )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
  The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in  may also be helpful.
  fatal error: unexpectedly found nil while unwrapping an Optional value
  (lldb)

Body:
@IBOutlet weak var scrollView: UIScrollView!

And create outlet - connect scrollview in storyboard with scrollview variable.

Your constraint wrong but it does not reason of crash


问:
Get Text from SVG selenium java
I am uable to getText from Text tag in SVG. I am Attaching HTML

```<code><svg width="553" height="200" style="overflow: hidden;" aria-label="A chart.">
     <defs id="defs">
     <rect x="0" y="0" width="553" height="200" stroke="none" stroke-width="0" fill="#ffffff">
     <g>
         <text text-anchor="start" x="77" y="22.85" font-family="Arial" font-size="11" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">Clustering done on Mar 30, 2017 11:13 AM</text>
         <rect x="77" y="13.5" width="400" height="11" stroke="none" stroke-width="0" fill-opacity="0" fill="#ffffff">
     </g>
</code>```

The get I want to get is Clustering done on Mar 30, 2017 11:13 AM

答:
This locator should work:

String text=driver.findElement(By.xpath("//[@id='divClusters']//*[name()='svg' and @aria-label='A chart.']//*[name()='g']")).getText();
System.out.print(text);

Explanation:

.//div - remove . to search the whole document, not just in currently selected context element

remove absolute /div[1]/.. divs reference since it's not reliable

refer to svg element as //*[name()='svg']

add some meaningful attribute @aria-label='A chart.' to svg element

Elements inside svg should be handled in the same way: //*[name()="g"], //*[name()="defs"] - thanks to  Andersson for clarifying this.

Title: Get Text from SVG selenium java

Body:
I am uable to getText from Text tag in SVG. I am Attaching HTML

<svg width="553" height="200" style="overflow: hidden;" aria-label="A chart.">
     <defs id="defs">
     <rect x="0" y="0" width="553" height="200" stroke="none" stroke-width="0" fill="#ffffff">
     <g>
         <text text-anchor="start" x="77" y="22.85" font-family="Arial" font-size="11" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">Clustering done on Mar 30, 2017 11:13 AM</text>
         <rect x="77" y="13.5" width="400" height="11" stroke="none" stroke-width="0" fill-opacity="0" fill="#ffffff">
     </g>

The get I want to get is Clustering done on Mar 30, 2017 11:13 AM


问:
Java- Getting variables from method into other method
I am struggling with getting variables (all kinds: arrays, Strings, int) from a method (the method where I create the my GUI fields) into another method (the method where i manage my keypress events) I managed to get the fields, via their names, but I don't know how to get some variables.

Example: In the Field Method i got this part:
I manage My timestuff and put it into the input field(s) (rest is cut out)

```<code>DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
long todayDateUnix = Instant.now().getEpochSecond();;
String reportDate = df.format(todayDate);
String CustomDate = "meinDatum";
String[] parts = reportDate.split("/");
String DateDay = parts[0];
String DateMonth = parts[1];
String DateYear = parts[2];

JTextField input_day =new JTextField(DateDay);
//  input_day.setFocusTraversalKeysEnabled(false);
input_day.setName("input_day");
input_day.setBounds(102, 37, 25, 20);
input_day.setColumns(10);
</code>```

and in the other method I need these variables:

```<code>input_datum.setText(reportDate);
if(check_datum.isSelected()){
    CustomDateFinal[0] = datumvar;
    input_datum.setText(CustomDateFinal[0]);

}
</code>```

Don't care for the others but how for example do I get "reportDate"?
Thanks in advance :)

EDIT:
I want the variables from "createFields" to "customKeyevent"
PICTURE

答: Are these methods in the same class? If so, why don't you declare the variables outside the method? That way their scope is across all methods. If not, you could create getters/setters for each variable.</p>

Body:
I am struggling with getting variables (all kinds: arrays, Strings, int) from a method (the method where I create the my GUI fields) into another method (the method where i manage my keypress events) I managed to get the fields, via their names, but I don't know how to get some variables.

Example: In the Field Method i got this part:
I manage My timestuff and put it into the input field(s) (rest is cut out)

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
long todayDateUnix = Instant.now().getEpochSecond();;
String reportDate = df.format(todayDate);
String CustomDate = "meinDatum";
String[] parts = reportDate.split("/");
String DateDay = parts[0];
String DateMonth = parts[1];
String DateYear = parts[2];

JTextField input_day =new JTextField(DateDay);
//  input_day.setFocusTraversalKeysEnabled(false);
input_day.setName("input_day");
input_day.setBounds(102, 37, 25, 20);
input_day.setColumns(10);

and in the other method I need these variables:

input_datum.setText(reportDate);
if(check_datum.isSelected()){
    CustomDateFinal[0] = datumvar;
    input_datum.setText(CustomDateFinal[0]);

}

Don't care for the others but how for example do I get "reportDate"?
Thanks in advance :)

EDIT:
I want the variables from "createFields" to "customKeyevent"
PICTURE


问:
browser.explore() vs the old ways to debug in Prortractor
In Protractor 5.0.0, there was a new browser.explore() method added to the API.

How is it different from the previous browser.pause() or browser.debugger() or the browser.enterRepl()? What is the preferred way to debug tests in Protractor?

答:
Each one has their own advantages and disadvantages.

browser.explore() is pretty new one and also this has great advantage of debugging the test using the same script we are using in our test cases for eg.

```<code>element(by.cssContainingText('Username')).click();
</code>```

browser.pause() is just allowing to type command 'c'
Every time you press c like below in command prompt. You will be jumped to the next step/line/breakpoints to perform in the test script.

```<code>wd-debug> c
</code>```

browser.debugger() can be used from the browser console instead of using from command prompts where web driver is running.  This will enable the user to use the client side scripts on the console.

The other one i haven't worked with may be once i try let you know that too.

Body:
Each one has their own advantages and disadvantages.

browser.explore() is pretty new one and also this has great advantage of debugging the test using the same script we are using in our test cases for eg.

element(by.cssContainingText('Username')).click();

browser.pause() is just allowing to type command 'c'
Every time you press c like below in command prompt. You will be jumped to the next step/line/breakpoints to perform in the test script.

wd-debug> c

browser.debugger() can be used from the browser console instead of using from command prompts where web driver is running.  This will enable the user to use the client side scripts on the console.

The other one i haven't worked with may be once i try let you know that too.


问:
Get rid of space when printing a new line using standard output in c++ and ncurses
Hello I'd like to know how to get rid of the space created
when printing a new line in c++ using ncurses library.

```<code>#include <iostream>
#include <ncurses.h>

using namespace std;

int main(){

    initscr();
    noecho();

    cout << "Hello" << endl;
    cout << "World" << endl;

    endwin();

    return 0;
}
</code>```

I have this output

Hello

----World

(The dashes are the space I mean)

答:
Offhand, I'd expect this output:

```<code>Hello
     World
</code>```

since curses puts the screen into raw mode, suppressing the cooked-mode feature that converts output line-feeds into carriage-return/line-feed.  If you really want to print

```<code>Hello
World
</code>```

you should use curses calls (which also happen to work with curses output buffering):

```<code>addstr("Hello\n");
addstr("World\n");
</code>```

Besides the misformatted output, mixing cout with curses can cause your output to be sent in a different order than the curses calls.  That's what I meant by buffering.

Body:
Hello I'd like to know how to get rid of the space created
when printing a new line in c++ using ncurses library.

#include <iostream>
#include <ncurses.h>

using namespace std;

int main(){

    initscr();
    noecho();

    cout << "Hello" << endl;
    cout << "World" << endl;

    endwin();

    return 0;
}

I have this output

Hello

----World

(The dashes are the space I mean)

Body:
Offhand, I'd expect this output:

Hello
     World

since curses puts the screen into raw mode, suppressing the cooked-mode feature that converts output line-feeds into carriage-return/line-feed.  If you really want to print

Hello
World

you should use curses calls (which also happen to work with curses output buffering):

addstr("Hello\n");
addstr("World\n");

Besides the misformatted output, mixing cout with curses can cause your output to be sent in a different order than the curses calls.  That's what I meant by buffering.


问:
On click how can I get the closet getAttribute('data-name') with the same id
When I click on #tag-list-item it should get the closet data-name

How ever it works fine for the first one but if I click on the second #tag-list-item it gets the first data-name and not the closet one.

Question when I click on my #tag-list-item how can I make sure it gets
  the correct getAttribute('data-name') with same id?

```<code><script type="text/javascript">
$(document).on('click', '#tag-list-item', function(e){
    var taglistitem = document.getElementById("tag-list-item");

    var tagbar = document.getElementById("tag-menu");

    var tagmenuitem = document.createElement("li");
    tagmenuitem.id = "tag-menu-item";
    tagbar.appendChild(tagmenuitem);

    var label = document.createElement("span");
    label.className = "label label-default";
    label.innerHTML = taglistitem.getAttribute('data-name');
    tagmenuitem.appendChild(label);
});
</script>
</code>```

Full View

```<code><div id="tag">
<?php if ($tags) {?>
<div id="tag-list-group">
<?php foreach (array_chunk($tags, 4) as $tag) { ?>
<div class="row">
<?php foreach ($tag as $tag) {?>
<div class="col-sm-3 col-xs-6 text-center">
<a>
<span id="tag-list-item" data-id="<?php echo $tag['tag_id'];?>" data-name="<?php echo $tag['name'];?>"><?php echo $tag['tag_name'];?></span>
</a>
</div>
<?php }?>
</div>
<?php }?>
</div>
<?php }?>

<div id="tagbar"><ul id="tag-menu" class="list-inline"></ul></div>
</div>

<script type="text/javascript">
$(document).on('click', '#tag-list-item', function(e){
    var taglistitem = document.getElementById("tag-list-item");

    var tagbar = document.getElementById("tag-menu");

    var tagmenuitem = document.createElement("li");
    tagmenuitem.id = "tag-menu-item";
    tagbar.appendChild(tagmenuitem);

    var label = document.createElement("span");
    label.className = "label label-default";
    label.innerHTML = taglistitem.getAttribute('data-name');
    tagmenuitem.appendChild(label);
});
</script>
</code>```

答:
The problem is because you're repeating the same id multiple times when they must be unique. You need to use a common class instead.

You'll then need to amend the code in your click handler to reference the element that raised the event specifically, instead of attempting to select it by its id. You also have an odd mix of jQuery and plain JS code which can be simplified. Try this:

```<code><!-- note the 'class' is added -->
<span class="tag-list-item" data-id="<?php echo $tag['tag_id'];?>" data-name="<?php echo $tag['name'];?>"><?php echo $tag['tag_name'];?></span>
</code>```

$(document).on('click', '.tag-list-item', function(e){
    var $taglistitem = $(this);
    var $tagbar = $("#tag-menu");
    var $tagmenuitem = $('

').appendTo($tagbar);
    $('' + $taglistitem.data('name') + '</span').appendTo($tagmenuitem);
});
```

Body:
When I click on #tag-list-item it should get the closet data-name

How ever it works fine for the first one but if I click on the second #tag-list-item it gets the first data-name and not the closet one.

Question when I click on my #tag-list-item how can I make sure it gets
  the correct getAttribute('data-name') with same id?

Full View

<?php if ($tags) {?>

<?php foreach (array_chunk($tags, 4) as $tag) { ?>

<?php foreach ($tag as $tag) {?>

<span id="tag-list-item" data-id="<?php echo $tag['tag_id'];?>" data-name="<?php echo $tag['name'];?>"><?php echo $tag['tag_name'];?>

<?php }?>

<?php }?>

<?php }?>

Body:
The problem is because you're repeating the same id multiple times when they must be unique. You need to use a common class instead.

You'll then need to amend the code in your click handler to reference the element that raised the event specifically, instead of attempting to select it by its id. You also have an odd mix of jQuery and plain JS code which can be simplified. Try this:

<!-- note the 'class' is added -->
<span class="tag-list-item" data-id="<?php echo $tag['tag_id'];?>" data-name="<?php echo $tag['name'];?>"><?php echo $tag['tag_name'];?></span>

$(document).on('click', '.tag-list-item', function(e){
    var $taglistitem = $(this);
    var $tagbar = $("#tag-menu");
    var $tagmenuitem = $('<li class="tag-menu-item"></li>').appendTo($tagbar);
    $('<span class="label label-default">' + $taglistitem.data('name') + '</span').appendTo($tagmenuitem);
});


问:
How do I get localized date pattern string?
It is quite easy to format and parse Java Date (or Calendar) classes using instances of DateFormat.

I could format the current date into a short localized date like this:

```<code>DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String today = formatter.format(new Date());
</code>```

My problem is that I need to obtain this localized pattern string (something like "MM/dd/yy").

This should be a trivial task, but I just couldn't find the provider.

答:
Please find in the below code which accepts the locale instance and returns the locale specific data format/pattern.</p>

```<code> public static String getLocaleDatePattern(Locale locale) {
    // Validating if Locale instance is null
    if (locale == null || locale.getLanguage() == null) {
        return "MM/dd/yyyy";
    }
    // Fetching the locale specific date pattern
    String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance(
            DateFormat.SHORT, locale)).toPattern();
    // Validating if locale type is having language code for Chinese and country
    // code for (Hong Kong) with Date Format as - yy'?'M'?'d'?'
    if (locale.toString().equalsIgnoreCase("zh_hk")) {
        // Expected application Date Format for Chinese (Hong Kong) locale type
        return "yyyy'MM'dd";
    }
    // Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern
    localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd").replaceAll(
            "M{1,2}", "MM").replaceAll("y{1,4}|Gy", "yyyy");
    // Replacing all blank spaces in the locale date pattern
    localeDatePattern = localeDatePattern.replace(" ", "");
    // Validating the date pattern length to remove any extract characters
    if (localeDatePattern.length() > 10) {
        // Keeping the standard length as expected by the application
        localeDatePattern = localeDatePattern.substring(0, 10);
    }
    return localeDatePattern;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It is quite easy to format and parse Java Date (or Calendar) classes using instances of DateFormat.

I could format the current date into a short localized date like this:

DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String today = formatter.format(new Date());

My problem is that I need to obtain this localized pattern string (something like "MM/dd/yy").

This should be a trivial task, but I just couldn't find the provider.

Body:
Please find in the below code which accepts the locale instance and returns the locale specific data format/pattern.

 public static String getLocaleDatePattern(Locale locale) {
    // Validating if Locale instance is null
    if (locale == null || locale.getLanguage() == null) {
        return "MM/dd/yyyy";
    }
    // Fetching the locale specific date pattern
    String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance(
            DateFormat.SHORT, locale)).toPattern();
    // Validating if locale type is having language code for Chinese and country
    // code for (Hong Kong) with Date Format as - yy'?'M'?'d'?'
    if (locale.toString().equalsIgnoreCase("zh_hk")) {
        // Expected application Date Format for Chinese (Hong Kong) locale type
        return "yyyy'MM'dd";
    }
    // Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern
    localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd").replaceAll(
            "M{1,2}", "MM").replaceAll("y{1,4}|Gy", "yyyy");
    // Replacing all blank spaces in the locale date pattern
    localeDatePattern = localeDatePattern.replace(" ", "");
    // Validating the date pattern length to remove any extract characters
    if (localeDatePattern.length() > 10) {
        // Keeping the standard length as expected by the application
        localeDatePattern = localeDatePattern.substring(0, 10);
    }
    return localeDatePattern;
}


问:
Developing a macro for placing pictures next to each other
I have around 100 sheet music files that contain notes under each other. What I would like to do now is to create one long string of notes.

So there I need to do the following:

Cut out specific parts of the .pdf file.

Glue them together horizontally

So I have for example this file:

https://www.flickr.com/photos/113328996@N07/33326243881/in/dateposted-public/

Cut into two parts:

https://www.flickr.com/photos/113328996@N07/33326247491/in/dateposted-public/

https://www.flickr.com/photos/113328996@N07/33326247401/in/dateposted-public/

and now I would like to add these together in a line (automatically)

I got the first part covered but have some problems with the second part. Could anybody tell me if there's a way to load 1 picture and place it of a certain x,y coordinate and then load another picture on another certain x,y coordinate? Think this would require a VBA / Excel equivalent of Photoshop.

Any thoughts?

答:
I would do this with ImageMagick which is installed on most Linux distros and is available for free on macOS/OSX and Windows. You just type the commands into the Terminal/Command Prompt.

At its simplest, you can append two images side-by-side like this:

```<code>magick stave1.png stave2.png +append result.png
</code>```

You can append images top-to-bottom like this:

```<code>magick stave1.png stave2.png -append result.png
</code>```

The difference is the +/- sign preceding append.

You can also append two images side-by-side and then append the results top-to-bottom:

```<code>magick stave1.png stave2.png +append \
    \( stave1.png stave2.png +append \) -append result.png
</code>```

You can also create a large canvas, of any colour you like (I chose magenta so you can see it on the white StackOverflow background) and splat (a technical term meaning "to carefully position") your images wherever you like and save that as a PDF like you asked.

```<code>magick -size 1000x400 xc:magenta            \
    stave1.png  -geometry +30+10 -composite \
    stave2.png -geometry +550+200 -composite result.pdf
</code>```

If you are unfortunate enough to have to use Windows, there are some differences in quoting. The slashes I have at the end of the lines (continuation characters) are represented by circumflexes (^) in Windows, I think. And the slashes preceding parentheses are probably not required in Windows.

Body:
I would do this with ImageMagick which is installed on most Linux distros and is available for free on macOS/OSX and Windows. You just type the commands into the Terminal/Command Prompt.

At its simplest, you can append two images side-by-side like this:

magick stave1.png stave2.png +append result.png

You can append images top-to-bottom like this:

magick stave1.png stave2.png -append result.png

The difference is the +/- sign preceding append.

You can also append two images side-by-side and then append the results top-to-bottom:

magick stave1.png stave2.png +append \
    \( stave1.png stave2.png +append \) -append result.png

You can also create a large canvas, of any colour you like (I chose magenta so you can see it on the white StackOverflow background) and splat (a technical term meaning "to carefully position") your images wherever you like and save that as a PDF like you asked.

magick -size 1000x400 xc:magenta            \
    stave1.png  -geometry +30+10 -composite \
    stave2.png -geometry +550+200 -composite result.pdf

If you are unfortunate enough to have to use Windows, there are some differences in quoting. The slashes I have at the end of the lines (continuation characters) are represented by circumflexes (^) in Windows, I think. And the slashes preceding parentheses are probably not required in Windows.


问:
How do I create .swiftlint.yml file & where I need to put it?
I want to use Swiftlint in my Swift project.
I followed the Realm instruction and installed Swiftlint by brew install swiftlint. Further I face the problem to create .swiftlint.yml file.

So please suggest me how I proceed?

答:
I suggest you read the documentation:

Configure SwiftLint by adding a .swiftlint.yml file from the directory you'll run SwiftLint from.

I'd suggest your project or source root.

An extensive example file follows; start from there.

As for the available rules and defaults, there does not seem to be good documentation besides running

swiftlint rules > swiftlint_rules.txt

and have very wide screen.


问:
How can I check if a string contains a specifig character with any digit in front of it in Python 2.7
I've got a question about my code(below). I'm trying to make a function to check if a string contains a gram unit. The code loops checks each string for a g with a digit in front of it. If it find this, it will loop backwards through the indices of the string until the index is not a digit. The code is working for me but I'm wondering how I can improve this code and if there is a better way to do this.

```<code>lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]

for lineIndex, line in enumerate(lines): # loop through lines
    line = line.lower() # make line lowercase
    line = "".join(line.split()) # delete whitespaces

    check = False

    for charIndex, char in enumerate(line): # loop through every index from string
        if char == "g" and line[charIndex-1].isdigit() == True: #check for a g with in front a digit
            index = charIndex - 1
            myList = []

            #loop until the index in front is not a digit
            while True:
                if line[index].isdigit() == True:
                    myList.append(line[index])
                    index -= 1
                else:
                    break

            # make a string from the list and print it
            myList.reverse()
            result = ""
            for letter in myList:
                result += letter
            result += "g"
            print("Line: %s\nBecomes: %s" % (line, result))

            # make check False
            check = True

    if check is False:
        print("Line: %s\nDoes not contain grams" % (line))
</code>```

Result of code:

答:
A neat expression (from the interpreter):

```<code>>>> import re
>>> re.findall(r'\s*(\d+)\s*g(?:r|ram)?s*\b', ' '.join(lines))
['100', '100', '100', '15', '85']
</code>```

```<code>>>> for res in re.findall(r'\s*(\d+)(\s*)([^\d\s]+)?\b', ' '.join(lines)):
    print 'input:', ''.join(res)
    print 'ouput:', '%sg' % res[0] if res[2] in ['g', 'gr', 'gram'] else 'No gram unit'
...
input: 100gr
ouput: 100g
input: 100 gram
ouput: 100g
input: 100 g
ouput: 100g
input: 15 gram
ouput: 15g
input: 1 pack
ouput: No gram unit
input: 8
ouput: No gram unit
input: 3 oz
ouput: No gram unit
input: 85 g
ouput: 85g
input: 100
ouput: No gram unit
</code>```

Body:
I've got a question about my code(below). I'm trying to make a function to check if a string contains a gram unit. The code loops checks each string for a g with a digit in front of it. If it find this, it will loop backwards through the indices of the string until the index is not a digit. The code is working for me but I'm wondering how I can improve this code and if there is a better way to do this.

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]

for lineIndex, line in enumerate(lines): # loop through lines
    line = line.lower() # make line lowercase
    line = "".join(line.split()) # delete whitespaces

    check = False

    for charIndex, char in enumerate(line): # loop through every index from string
        if char == "g" and line[charIndex-1].isdigit() == True: #check for a g with in front a digit
            index = charIndex - 1
            myList = []

            #loop until the index in front is not a digit
            while True:
                if line[index].isdigit() == True:
                    myList.append(line[index])
                    index -= 1
                else:
                    break

            # make a string from the list and print it
            myList.reverse()
            result = ""
            for letter in myList:
                result += letter
            result += "g"
            print("Line: %s\nBecomes: %s" % (line, result))

            # make check False
            check = True

    if check is False:
        print("Line: %s\nDoes not contain grams" % (line))

Result of code:

Body:
A neat expression (from the interpreter):

>>> import re
>>> re.findall(r'\s*(\d+)\s*g(?:r|ram)?s*\b', ' '.join(lines))
['100', '100', '100', '15', '85']

>>> for res in re.findall(r'\s*(\d+)(\s*)([^\d\s]+)?\b', ' '.join(lines)):
    print 'input:', ''.join(res)
    print 'ouput:', '%sg' % res[0] if res[2] in ['g', 'gr', 'gram'] else 'No gram unit'
...
input: 100gr
ouput: 100g
input: 100 gram
ouput: 100g
input: 100 g
ouput: 100g
input: 15 gram
ouput: 15g
input: 1 pack
ouput: No gram unit
input: 8
ouput: No gram unit
input: 3 oz
ouput: No gram unit
input: 85 g
ouput: 85g
input: 100
ouput: No gram unit


问:
Attempted to load class "PDO" from namespace
when I run this line

```<code>$pdo = new \PDO('mysql:host=localhost;dbname=mydata','root', null);
</code>```

I get this error

```<code>  [Symfony\Component\Debug\Exception\ClassNotFoundException]
  Attempted to load class "PDO" from namespace "check\roomsBundle\Command".
  Did you forget a "use" statement for another namespace?
</code>```

I tried to add this line to my parametrs.yml

```<code>database_driver: pdo_pgsql
and
database_driver: pdo_mysql
</code>```

but I still get this error I using symfony2.8 and mysql

```<code>class SocketCommand extends ContainerAwareCommand
{
    protected function configure()
    {
      //some code here
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        //somecode here

        $pdo = new \PDO('mysql:host=localhost;dbname=mydata', 'root', null);

}
</code>```

答:
Seems like you just haven't PDO extension because syntax is right.
On Ubuntu/Debian you should be able to install the necessary PDO parts from apt using

```<code>sudo apt-get install php-mysql
</code>```

or
apt-get install php5-mysql on old repo

Also you have to enable it in php.ini: extension=pdo_mysql.so

But in case when you have extension you can try to add

```<code> use \PDO;
</code>```

in your bundle

Body:
when I run this line

$pdo = new \PDO('mysql:host=localhost;dbname=mydata','root', null);

I get this error

  [Symfony\Component\Debug\Exception\ClassNotFoundException]
  Attempted to load class "PDO" from namespace "check\roomsBundle\Command".
  Did you forget a "use" statement for another namespace?

I tried to add this line to my parametrs.yml

database_driver: pdo_pgsql
and
database_driver: pdo_mysql

but I still get this error I using symfony2.8 and mysql

class SocketCommand extends ContainerAwareCommand
{
    protected function configure()
    {
      //some code here
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        //somecode here

        $pdo = new \PDO('mysql:host=localhost;dbname=mydata', 'root', null);

}

Body:
Seems like you just haven't PDO extension because syntax is right.
On Ubuntu/Debian you should be able to install the necessary PDO parts from apt using

sudo apt-get install php-mysql

or
apt-get install php5-mysql on old repo

Also you have to enable it in php.ini: extension=pdo_mysql.so

But in case when you have extension you can try to add

 use \PDO;

in your bundle


问:
Call a method of the object which is created in another class
I have a little problem.

I have a 3 classes looks "like" this:

```<code>public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager()
    {
        gun = new Gun();
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    Gun gun;

    public HudScreen()
    {
        gun = new Gun();
    }

    public void GunShotButton()
    {
        gun.Shoot();
    }
}
</code>```

The problem is I have two Gun objects and i want to have one but use it in both classes HudScreen and GameManager.

So, if I create a new Gun object in GameManager, how to "call" this object from the HudScreen class?

Thanks, MM.

答: register a ScreenController to every NiftyGUI screen.  create a ScreenController by creating a Java class that implements the de.lessvoid.nifty.screen.ScreenController interface and its abstract methods.</p>

Body:
I have a little problem.

I have a 3 classes looks "like" this:

public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager()
    {
        gun = new Gun();
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    Gun gun;

    public HudScreen()
    {
        gun = new Gun();
    }

    public void GunShotButton()
    {
        gun.Shoot();
    }
}

The problem is I have two Gun objects and i want to have one but use it in both classes HudScreen and GameManager.

So, if I create a new Gun object in GameManager, how to "call" this object from the HudScreen class?

Thanks, MM.


问:
React.js broke dispatchEvent
for example:

I add event handler in react:

```<code><div onClick={someHandler}/>
</code>```

Then I dispatch event:

```<code>let clickEvt = new MouseEvent('click', {
    'bubbles': false,
    'cancelable': true
});

elm.dispatchEvent(clickEvt);
</code>```

But nothing happens. I hear you can use elm.click() to trigger the react event. I'm wondering if that is the proper way to do it in react? Also what is the difference between click() and dispatchEvent()? Because I kinda want to stick to dispatchEvent().

答:
All

I figured it out. bubbles must be set to true for react to receive the event, which is why click() method works, because it automatically bubbles.

Title: React.js broke dispatchEvent

Body:
for example:

I add event handler in react:

Then I dispatch event:

let clickEvt = new MouseEvent('click', {
    'bubbles': false,
    'cancelable': true
});

elm.dispatchEvent(clickEvt);

But nothing happens. I hear you can use elm.click() to trigger the react event. I'm wondering if that is the proper way to do it in react? Also what is the difference between click() and dispatchEvent()? Because I kinda want to stick to dispatchEvent().