问:
Empty json object when read text file
I'm testing a python script with text data. Able to run the script and return valid json file if the text include in the script but I got empty json object when run the script and with separate text file.

The output only empty json file

```<code>{
  "ospf": []
}
</code>```

The code below return empty json object when run it with read text file

```<code>import json

result = {}
l = []

with open('data.txt') as myf:
   for i in myf:
     if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))

with open('data.json', 'w') as json_file:
    json.dump(result, json_file)
</code>```

When executed the code below ok with the text data include as data..no problem

```<code>import json

data = '''
  Type      : Router
  Ls id     : 1.1.1.2
  Adv rtr   : 1.1.1.2
  Ls age    : 201
  Len       : 84
  Link count: 5
   * Link ID: 1.1.1.2
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.4
     Data   : 192.168.100.34
     Link Type: P-2-P
     Metric : 1
   * Link ID: 192.168.100.33
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.1
     Data   : 192.168.100.53
     Link Type: P-2-P
     Metric : 1
   * Link ID: 192.168.100.54
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium

  Type      : Router
  Ls id     : 1.1.1.1
  Adv rtr   : 1.1.1.1
  Ls age    : 1699
  Len       : 96
  Options   :  ASBR  E
  seq#      : 80008d72
  chksum    : 0x16fc
  Link count: 6
   * Link ID: 1.1.1.1
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.1
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 12
     Priority : Medium
   * Link ID: 1.1.1.3
     Data   : 192.168.100.26
     Link Type: P-2-P
     Metric : 10
   * Link ID: 192.168.100.25
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 10
     Priority : Medium
   * Link ID: 1.1.1.2
     Data   : 192.168.100.54
     Link Type: P-2-P
     Metric : 10
   * Link ID: 192.168.100.53
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 10
     Priority : Medium'''

import json

result = {}
l = []
for i in data.split("\n\n"):
    if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))

with open('data.json', 'w') as json_file:
    json.dump(result, json_file)
</code>```

I'm not sure where i make wrong. Please advise me further. Thank you.

答:
A simple workaround would be to concat the file to one large string. then your code works as expected. This is definetly no clean answer but you could let the rest of your code unchanged.</p>

```<code>import json

result = {}
l = []

with open('data.txt') as myf:

    a = ''.join(myf)
    for i in a.split("\n\n"):
     if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))
with open('data.json', 'w') as json_file:
    json.dump(result, json_file)
</code>```

Title: Empty json object when read text file

Body:
I'm testing a python script with text data. Able to run the script and return valid json file if the text include in the script but I got empty json object when run the script and with separate text file.

The output only empty json file

{
  "ospf": []
}

The code below return empty json object when run it with read text file

import json

result = {}
l = []

with open('data.txt') as myf:
   for i in myf:
     if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))

with open('data.json', 'w') as json_file:
    json.dump(result, json_file)

When executed the code below ok with the text data include as data..no problem

import json

data = '''
  Type      : Router
  Ls id     : 1.1.1.2
  Adv rtr   : 1.1.1.2
  Ls age    : 201
  Len       : 84
  Link count: 5
   * Link ID: 1.1.1.2
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.4
     Data   : 192.168.100.34
     Link Type: P-2-P
     Metric : 1
   * Link ID: 192.168.100.33
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.1
     Data   : 192.168.100.53
     Link Type: P-2-P
     Metric : 1
   * Link ID: 192.168.100.54
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium

  Type      : Router
  Ls id     : 1.1.1.1
  Adv rtr   : 1.1.1.1
  Ls age    : 1699
  Len       : 96
  Options   :  ASBR  E
  seq#      : 80008d72
  chksum    : 0x16fc
  Link count: 6
   * Link ID: 1.1.1.1
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.1
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 12
     Priority : Medium
   * Link ID: 1.1.1.3
     Data   : 192.168.100.26
     Link Type: P-2-P
     Metric : 10
   * Link ID: 192.168.100.25
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 10
     Priority : Medium
   * Link ID: 1.1.1.2
     Data   : 192.168.100.54
     Link Type: P-2-P
     Metric : 10
   * Link ID: 192.168.100.53
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 10
     Priority : Medium'''

import json

result = {}
l = []
for i in data.split("\n\n"):
    if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))

with open('data.json', 'w') as json_file:
    json.dump(result, json_file)

I'm not sure where i make wrong. Please advise me further. Thank you.

Body:
A simple workaround would be to concat the file to one large string. then your code works as expected. This is definetly no clean answer but you could let the rest of your code unchanged.

import json

result = {}
l = []

with open('data.txt') as myf:

    a = ''.join(myf)
    for i in a.split("\n\n"):
     if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))
with open('data.json', 'w') as json_file:
    json.dump(result, json_file)


来源: stackexchange

问:
Reading rich text from an Excel cell
I am attempting to read an excel spreadsheet in which some cells contain rich text.  I would like to convert this to a plain text format that encodes the formatting in some way.  For example, given the text:

"Here's some text with italics in the middle of it."

I would like to convert this to:

"Here's some text [i]with italics in the middle[/i] of it".

The problem is that I haven't found a way to extract rich text from an excel cell.  Interop.Office.Excel allows me to get a Range and examine its Style property, but that only tells me whether the cell itself is italicized; it doesn't give me information about any of the individual characters.  The best "solution" I've found involves copying the contents of the cell to the clipboard and calling Clipboard.GetData(System.Windows.DataFormats.Rtf), and it's too slow to be practical.

Is there a smart way to access the rich text contained in an excel cell that I'm missing?

答:
```<code>i dont have answer for your question
</code>```

but I suggest you to study the site
 http://www.winnovative-software.com/
 from this site you can get wnuxls.dll
file which have all the functionality which we want to perform with excel try it

ContentLicense: CC BY-SA 3.0

Title: Reading rich text from an Excel cell

Body:
i dont have answer for your question

but I suggest you to study the site
 http://www.winnovative-software.com/
 from this site you can get wnuxls.dll
file which have all the functionality which we want to perform with excel try it


问:
Get Data from API using retrofit
I need to get the details from the API and display them in textviews.

Here's my API in JSON format  : https://imgur.com/a/WI98ymx

I need to get the data like username, user image, user phone number etc in Strings and display them in textviews.
How do i request all the fields and show the list in different textviews?

Here's my Login interface

```<code>package com.example.hb.loginapi;

import java.util.List;

   import retrofit2.Call;
   import retrofit2.http.GET;

  import retrofit2.http.POST;

   import retrofit2.http.Query;

    interface Login {

   @POST("user_login_v1")
   Call<ResObj>  loginInfo(@Query("password") String password,
   @Query("email") String email);

   @GET("user_login_v1")
   Call<List> getUserDetails();

}
</code>```

Here's my ResObj class

```<code>package com.example.hb.loginapi;

import com.google.gson.annotations.SerializedName;
import java.util.List;

 public class ResObj {

@SerializedName("settings")
private Settings settings;

@SerializedName("data")
private List<DataItem> data;

public void setSettings(Settings settings){
    this.settings = settings;
}

public Settings getSettings(){
    return settings;
}

public void setData(List<DataItem> data){
    this.data = data;
}

public List<DataItem> getData(){
    return data;
}

public class Settings {

    @SerializedName("success")
    private String success;

    @SerializedName("message")
    private String message;

    @SerializedName("fields")
    private List<String> fields;

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getSuccess() {
        return success;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }

    public List<String> getFields() {
        return fields;
    }
}

public class DataItem{

    @SerializedName("user_name")
    private String userName;

    @SerializedName("search_report_count")
    private String searchReportCount;

    @SerializedName("access_token")
    private String accessToken;

    @SerializedName("profile_image")
    private String profileImage;

    @SerializedName("is_social")
    private String isSocial;

    @SerializedName("is_notification_enabled")
    private String isNotificationEnabled;

    @SerializedName("user_id")
    private String userId;

    @SerializedName("phone")
    private String phone;

    @SerializedName("plate_number")
    private String plateNumber;

    @SerializedName("state_id")
    private String stateId;

    @SerializedName("state")
    private String state;

    @SerializedName("email")
    private String email;

    @SerializedName("status")
    private String status;

    public void setUserName(String userName){
        this.userName = userName;
    }

    public String getUserName(){
        return userName;
    }

    public void setSearchReportCount(String searchReportCount){
        this.searchReportCount = searchReportCount;
    }

    public String getSearchReportCount(){
        return searchReportCount;
    }

    public void setAccessToken(String accessToken){
        this.accessToken = accessToken;
    }

    public String getAccessToken(){
        return accessToken;
    }

    public void setProfileImage(String profileImage){
        this.profileImage = profileImage;
    }

    public String getProfileImage(){
        return profileImage;
    }

    public void setIsSocial(String isSocial){
        this.isSocial = isSocial;
    }

    public String getIsSocial(){
        return isSocial;
    }

    public void setIsNotificationEnabled(String isNotificationEnabled){
        this.isNotificationEnabled = isNotificationEnabled;
    }

    public String getIsNotificationEnabled(){
        return isNotificationEnabled;
    }

    public void setUserId(String userId){
        this.userId = userId;
    }

    public String getUserId(){
        return userId;
    }

    public void setPhone(String phone){
        this.phone = phone;
    }

    public String getPhone(){
        return phone;
    }

    public void setPlateNumber(String plateNumber){
        this.plateNumber = plateNumber;
    }

    public String getPlateNumber(){
        return plateNumber;
    }

    public void setStateId(String stateId){
        this.stateId = stateId;
    }

    public String getStateId(){
        return stateId;
    }

    public void setState(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }

    public void setEmail(String email){
        this.email = email;
    }

    public String getEmail(){
        return email;
    }

    public void setStatus(String status){
        this.status = status;
    }

    public String getStatus(){
        return status;
    }
}

}
</code>```

My Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#e9edf6"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/userProfilePic"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_width="150dp"
        android:layout_height="150dp"
        />

        <TextView
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyNameText"
            android:layout_marginTop="50dp"
            />

        <TextView
            android:id="@+id/userID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyUserIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/emailID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyEmailText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStatus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStatusText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userPlateNum"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyPlateNumText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateNameText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userSearchReportCount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummySearchReportCountText"
            android:layout_marginTop="20dp"
            />

    </LinearLayout>
</ScrollView>
</code>```

My MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

List emList=new ArrayList();

List dataList=new ArrayList();

List userDets=new ArrayList();

ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;

String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;

String email;

Login login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emList.add(email);

    userName=findViewById(R.id.userName);

    email=getIntent().getStringExtra("email");

     login=ApiUtils.getLoginClass();

    getUserData();
}

private void getUserData(){
    Call<List> call=login.getUserDetails();

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful()){
                List resObj=(List)response.body();

                for(int i=0;i<resObj.size();i++){
                    Log.e("data",resObj.get(i).toString());
                }
 }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}
</code>```

}

I don't know what to write in the onResponse() method.

答:
Create ResObj.class using Android studio plugin "GsonFormat"
It will create a perfect POJO class for your APICall, just past the API GET response from Postman.
It will create a suitable POJO class, from which you can simply call

```<code> private void callApi() {
    Log.e(TAG, "callApi: inside apiCall");
    Call<List> call =
 login.getUserDetails();

 call.enqueue(new Callback<List>() {
        @Override
        public void onResponse(Call<List> call, @NonNull Response<List>response) {
            List items = response.body();

            items = list.data;
            String user_id = items.getUserID();
        }

        @Override
        public void onFailure(Call<LiveMatches> call, Throwable t) {

        }
</code>```

call callApi() method where you want to get data;
This method and method will not work if you copy and paste it you need to alter it according to your POJO class but this will provide help
Also add your layout and activity code to give us context

ContentLicense: CC BY-SA 4.0

Title: Get Data from API using retrofit

Body:
I need to get the details from the API and display them in textviews.

Here's my API in JSON format  : https://imgur.com/a/WI98ymx

I need to get the data like username, user image, user phone number etc in Strings and display them in textviews.
How do i request all the fields and show the list in different textviews?

Here's my Login interface

package com.example.hb.loginapi;

import java.util.List;

   import retrofit2.Call;
   import retrofit2.http.GET;

  import retrofit2.http.POST;

   import retrofit2.http.Query;

    interface Login {

   @POST("user_login_v1")
   Call<ResObj>  loginInfo(@Query("password") String password,
   @Query("email") String email);

   @GET("user_login_v1")
   Call<List> getUserDetails();

}

Here's my ResObj class

package com.example.hb.loginapi;

import com.google.gson.annotations.SerializedName;
import java.util.List;

 public class ResObj {

@SerializedName("settings")
private Settings settings;

@SerializedName("data")
private List<DataItem> data;

public void setSettings(Settings settings){
    this.settings = settings;
}

public Settings getSettings(){
    return settings;
}

public void setData(List<DataItem> data){
    this.data = data;
}

public List<DataItem> getData(){
    return data;
}

public class Settings {

    @SerializedName("success")
    private String success;

    @SerializedName("message")
    private String message;

    @SerializedName("fields")
    private List<String> fields;

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getSuccess() {
        return success;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }

    public List<String> getFields() {
        return fields;
    }
}

public class DataItem{

    @SerializedName("user_name")
    private String userName;

    @SerializedName("search_report_count")
    private String searchReportCount;

    @SerializedName("access_token")
    private String accessToken;

    @SerializedName("profile_image")
    private String profileImage;

    @SerializedName("is_social")
    private String isSocial;

    @SerializedName("is_notification_enabled")
    private String isNotificationEnabled;

    @SerializedName("user_id")
    private String userId;

    @SerializedName("phone")
    private String phone;

    @SerializedName("plate_number")
    private String plateNumber;

    @SerializedName("state_id")
    private String stateId;

    @SerializedName("state")
    private String state;

    @SerializedName("email")
    private String email;

    @SerializedName("status")
    private String status;

    public void setUserName(String userName){
        this.userName = userName;
    }

    public String getUserName(){
        return userName;
    }

    public void setSearchReportCount(String searchReportCount){
        this.searchReportCount = searchReportCount;
    }

    public String getSearchReportCount(){
        return searchReportCount;
    }

    public void setAccessToken(String accessToken){
        this.accessToken = accessToken;
    }

    public String getAccessToken(){
        return accessToken;
    }

    public void setProfileImage(String profileImage){
        this.profileImage = profileImage;
    }

    public String getProfileImage(){
        return profileImage;
    }

    public void setIsSocial(String isSocial){
        this.isSocial = isSocial;
    }

    public String getIsSocial(){
        return isSocial;
    }

    public void setIsNotificationEnabled(String isNotificationEnabled){
        this.isNotificationEnabled = isNotificationEnabled;
    }

    public String getIsNotificationEnabled(){
        return isNotificationEnabled;
    }

    public void setUserId(String userId){
        this.userId = userId;
    }

    public String getUserId(){
        return userId;
    }

    public void setPhone(String phone){
        this.phone = phone;
    }

    public String getPhone(){
        return phone;
    }

    public void setPlateNumber(String plateNumber){
        this.plateNumber = plateNumber;
    }

    public String getPlateNumber(){
        return plateNumber;
    }

    public void setStateId(String stateId){
        this.stateId = stateId;
    }

    public String getStateId(){
        return stateId;
    }

    public void setState(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }

    public void setEmail(String email){
        this.email = email;
    }

    public String getEmail(){
        return email;
    }

    public void setStatus(String status){
        this.status = status;
    }

    public String getStatus(){
        return status;
    }
}

}

My Layout

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#e9edf6"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/userProfilePic"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_width="150dp"
        android:layout_height="150dp"
        />

        <TextView
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyNameText"
            android:layout_marginTop="50dp"
            />

        <TextView
            android:id="@+id/userID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyUserIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/emailID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyEmailText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStatus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStatusText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userPlateNum"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyPlateNumText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateNameText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userSearchReportCount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummySearchReportCountText"
            android:layout_marginTop="20dp"
            />

    </LinearLayout>
</ScrollView>

My MainActivity.java

public class MainActivity extends AppCompatActivity {

List emList=new ArrayList();

List dataList=new ArrayList();

List userDets=new ArrayList();

ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;

String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;

String email;

Login login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emList.add(email);

    userName=findViewById(R.id.userName);

    email=getIntent().getStringExtra("email");

     login=ApiUtils.getLoginClass();

    getUserData();
}

private void getUserData(){
    Call<List> call=login.getUserDetails();

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful()){
                List resObj=(List)response.body();

                for(int i=0;i<resObj.size();i++){
                    Log.e("data",resObj.get(i).toString());
                }
 }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}

}

I don't know what to write in the onResponse() method.

Body:
Create ResObj.class using Android studio plugin "GsonFormat"
It will create a perfect POJO class for your APICall, just past the API GET response from Postman.
It will create a suitable POJO class, from which you can simply call

 private void callApi() {
    Log.e(TAG, "callApi: inside apiCall");
    Call<List> call =
 login.getUserDetails();

 call.enqueue(new Callback<List>() {
        @Override
        public void onResponse(Call<List> call, @NonNull Response<List>response) {
            List items = response.body();

            items = list.data;
            String user_id = items.getUserID();
        }

        @Override
        public void onFailure(Call<LiveMatches> call, Throwable t) {

        }

call callApi() method where you want to get data;
This method and method will not work if you copy and paste it you need to alter it according to your POJO class but this will provide help
Also add your layout and activity code to give us context


问:
Is there anyway to restrict an object to a particular data type in Python?
I need to accept a number from the user and print the sum. I want the object defined to accept the characters entered by the user to be of integer type only.

I do not want to check the type of the object after the value is entered. I would like a method by which the program doesn't even accept strings  or other data types, only integers.

答:
I'm quite sure you'd be fine with try/except and converting the user's input to an int:

```<code># Repeat until a "break" is issued
while True:

    number = input('Enter number: ')

    # Attempt to convert the input to an integer
    try:
        number = int(number)

    # If there was an error converting...
    except ValueError:
        print("That's not a number! Try again.")

    # Break the loop if no error, i.e. conversion was successful
    else:
        break
</code>```

Body:
I'm quite sure you'd be fine with try/except and converting the user's input to an int:

# Repeat until a "break" is issued
while True:

    number = input('Enter number: ')

    # Attempt to convert the input to an integer
    try:
        number = int(number)

    # If there was an error converting...
    except ValueError:
        print("That's not a number! Try again.")

    # Break the loop if no error, i.e. conversion was successful
    else:
        break


问:
How to dynamically process nested object in Javascript if I don't know what is the depth?
Sorry, I don't know how to word this question properly but basically, I have this nested object nestedObj. I want to dynamically process this object but the depth of the object is not fixed. So for example:

```<code>nestedObj = {
    "property1":{
        "subProperty1": {
            "data": "This is the data for property1 > subProperty1"
        }
    },

    "property2":{
        "subProperty1": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty1 > anotherSubProperty1"
            }
        },
        "subProperty2": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty2 > anotherSubProperty1"
            }
        }
    },

    "property3":{
        "subProperty1": {
            "data": "This is the data for property3 > subProperty1"
        }
    }
}
</code>```

Now I want to process this object in a for of loop where my end goal is to get the value of data of certain nodes. Now, the path to the value of each object nodes are defined in another object:

```<code>dataPath = {
    "property1": "subProperty1.data",
    "property2": "subProperty2.anotherSubProperty1.data",
    "property3": "subProperty1.data",
}
</code>```

And then I used this for of loop to process them:

```<code>properties = ["property1", "property2", "property3"];
for(var property of properties) {
    path_to_data = dataPath[property].split(".");
    data = nestedObj[path_to_data[0]][path_to_data[1]];

    // Some other logic
}
</code>```

Obviously, this only works for "property1" and "property3". I have to add special handling for all the objects that have more than 2 inner nodes. For large data with varying numbers of depth, it would not be ideal to manually add these special handlers. So my question is, in Javascript, is there any way for me to dynamically process nested object when I have the "path" to a certain node.

答:
You can use reduce() to get the value from object with a path

const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];

const getValueFromObj = (obj,path) => path.split('.').reduce((ac,a) => (ac[a] || {}),obj);
let res = props.map(x => getValueFromObj(nestedObj,x+'.'+dataPath[x]))

console.log(res)```
</div>
</div>
</p>
<h3>using <code>for..of</code></h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];

const getValueFromObj = (obj,path) => path.split('.').reduce((ac,a) => (ac[a] || {}),obj);

for(let prop of props){
  let data = getValueFromObj(nestedObj,prop+'.'+dataPath[prop]);
  console.log(data)
}</code>```

Body:
Sorry, I don't know how to word this question properly but basically, I have this nested object nestedObj. I want to dynamically process this object but the depth of the object is not fixed. So for example:

nestedObj = {
    "property1":{
        "subProperty1": {
            "data": "This is the data for property1 > subProperty1"
        }
    },

    "property2":{
        "subProperty1": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty1 > anotherSubProperty1"
            }
        },
        "subProperty2": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty2 > anotherSubProperty1"
            }
        }
    },

    "property3":{
        "subProperty1": {
            "data": "This is the data for property3 > subProperty1"
        }
    }
}

Now I want to process this object in a for of loop where my end goal is to get the value of data of certain nodes. Now, the path to the value of each object nodes are defined in another object:

dataPath = {
    "property1": "subProperty1.data",
    "property2": "subProperty2.anotherSubProperty1.data",
    "property3": "subProperty1.data",
}

And then I used this for of loop to process them:

properties = ["property1", "property2", "property3"];
for(var property of properties) {
    path_to_data = dataPath[property].split(".");
    data = nestedObj[path_to_data[0]][path_to_data[1]];

    // Some other logic
}

Obviously, this only works for "property1" and "property3". I have to add special handling for all the objects that have more than 2 inner nodes. For large data with varying numbers of depth, it would not be ideal to manually add these special handlers. So my question is, in Javascript, is there any way for me to dynamically process nested object when I have the "path" to a certain node.

Body:
You can use reduce() to get the value from object with a path

const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];

const getValueFromObj = (obj,path) => path.split('.').reduce((ac,a) => (ac[a] || {}),obj);
let res = props.map(x => getValueFromObj(nestedObj,x+'.'+dataPath[x]))

console.log(res)

using for..of

const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];

const getValueFromObj = (obj,path) => path.split('.').reduce((ac,a) => (ac[a] || {}),obj);

for(let prop of props){
  let data = getValueFromObj(nestedObj,prop+'.'+dataPath[prop]);
  console.log(data)
}


问:
Aiohttp server max connections
I cannot understand the reason aiohttp (and asyncio in general) server implementation does not provide a way to limit max concurrent connections limit (number of accepted sockets, or number of running requests handlers).
(https://github.com/aio-libs/aiohttp/issues/675). Without this limit,  it is easy to run out of memory and/or file descriptors.

In the same time,  aiohttp client by default limits number of concurrent requests to 100 (https://docs.aiohttp.org/en/stable/client_advanced.html#limiting-connection-pool-size),  aiojobs limits number of running tasks and size of pending tasks list,  nginx has worker_connections limit,  any sync framework is limited by number of worker threads by design.

While aiohttp can handle a lot of concurrent requests,  this number is still limited. Docs on aiojobs says "The Scheduler has implied limit for amount of concurrent jobs (100 by default). ... It prevents a program over-flooding by running a billion of jobs at the same time". And still, we can happily spawn "billion"  (well,  until we run out of resources)  aiohttp handlers.

So the question is,  why is it implemented the way it is? Am I missing some important detail? I think we can somehow pause requests handlers using Semafor,  but the socket is still accepted by aiohttp and coroutine is spawned, in contrast with nginx. Also when deploying behind nginx,  the number of worker_connections and aiohttp desired limit will certainly be different.(because nginx may serve static files also)

答:
Based on the developers' comments on the linked issue, the reasons for this choice are the following:

The application can return a 4xx or 5xx response if it detects that the number of connections is larger than what it can reasonably handle. (This differs from the Semaphore idiom, which would effectively queue the connection.)

Throttling the number of server connections is more complicated than just specifying a number, because the limit might well depend on what your coroutines are doing, i.e. it should at least be path-based. Andrew Svetlov links to NGINX documentation about connection limiting to support this.

It is anyway recommended to put aiohttp behind a specialized front server such as NGINX.

More detail than this can only be provided by the developer(s), who have been known to read this tag.

At this point, it appears that the recommended solution is to either use a reverse proxy for limiting, or an application-based limit like this decorator (untested):

REQUEST_LIMIT = 100

def throttle_handle(real_handle):
    _nrequests = 0
    async def handle(request):
        nonlocal _nrequests
        if _nrequests >= REQUEST_LIMIT:
            return aiohttp.web.Response(
                status=429, text="Too many connections")
        _nrequests += 1
        try:
            return await real_handle(request)
        finally:
            _nrequests -= 1
    return handle

@throttle_handle
async def handle(request):
    ... your handler here ...
```

Title: Aiohttp server max connections


问:
How can I use findstr with newline regular expression
I'm on windows dos prompt. I have log file which contains log like:

```<code>Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341
</code>```

I want to extract all the item number who has give some sort of exception. I'm using findstr command for this. how can I use newline in my regular expression? I want to all lines which have Exception word and from next line the item no.

any help?

答:
I had a look into the findstr documentation and I think it is not able to do a multiline search.

Probably you should use more advanced tools like awk, or some versions of grep seems to support multiline regex too.

You can have a look at stackoverflow.com/questions/152708/

Body:
I'm on windows dos prompt. I have log file which contains log like:

Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341

I want to extract all the item number who has give some sort of exception. I'm using findstr command for this. how can I use newline in my regular expression? I want to all lines which have Exception word and from next line the item no.

any help?


问:
Split method and split on the ‘.’ character (without the csv extension)
Modify the constructor so that the name field is set to the filename
without the .csv extension. Hint: use the split method and split on
the ‘.’ character.

I used
filename.split('.');

```<code>public DataSet(String filename, color dataSetColor){

    name = filename;
    _dataSetColor = dataSetColor;
    _markList = new ArrayList<StudentMarks>();

    linesArray = loadStrings(filename);

    for(String l : linesArray){

        //Split the current line storing the values in csvArray
        csvArray = split(l, ',');
        if(csvArray.length == 3){
            String id = csvArray[0];
            int internalM = Integer.parseInt(csvArray[1]);
            int ExamM = Integer.parseInt(csvArray[2]);

            _markList.add(new StudentMarks(id,internalM,ExamM,_dataSetColor));
        } else {

            println("The length of the csvArray is not equal to 3");
        }
    }
}
</code>```

when I ran this, I want the result shows "dataSet", not the "dataSet.csv"

答:
Just change one line (use split with escape):

```<code>name = filename.split("\\.")[0];
</code>```

The problem is dot is a special symbol you need to escape.

One more solution is to use lastIndexOf method and substring:

```<code>name = fileneme.substring(0, filename.lastIndexOf("."));
</code>```

Second solution will work for the case when you'll have dots in file name.

Body:
Modify the constructor so that the name field is set to the filename
without the .csv extension. Hint: use the split method and split on
the ‘.’ character.

I used
filename.split('.');

public DataSet(String filename, color dataSetColor){

    name = filename;
    _dataSetColor = dataSetColor;
    _markList = new ArrayList<StudentMarks>();

    linesArray = loadStrings(filename);

    for(String l : linesArray){

        //Split the current line storing the values in csvArray
        csvArray = split(l, ',');
        if(csvArray.length == 3){
            String id = csvArray[0];
            int internalM = Integer.parseInt(csvArray[1]);
            int ExamM = Integer.parseInt(csvArray[2]);

            _markList.add(new StudentMarks(id,internalM,ExamM,_dataSetColor));
        } else {

            println("The length of the csvArray is not equal to 3");
        }
    }
}

when I ran this, I want the result shows "dataSet", not the "dataSet.csv"

Body:
Just change one line (use split with escape):

name = filename.split("\\.")[0];

The problem is dot is a special symbol you need to escape.

One more solution is to use lastIndexOf method and substring:

name = fileneme.substring(0, filename.lastIndexOf("."));

Second solution will work for the case when you'll have dots in file name.


问:
Regular Expression | Leap Years and More
I've recently been looking for a regular expression to do some client side date checking, and I haven't been able to find one that can satisfy the following criteria:

Has a range from 1800 - Now

Performs proper date checking with leap years

MM/DD/YYYY Form

Invalid Date Checking

(These constraints were outside of my scope and are a requirement as per the client, despite my efforts to convince them this wasn't the best route)

Current code:

```<code>$('input').keyup(function()
{
       var regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
       $(this).toggleClass('invalid',!regex.test($(this).val()));
});
</code>```

Update:

I should note that this is primarily to see if a regular expression like this would be possible (as the use of a Regex is not my choice in this matter). I am aware of the other (and better) options for validating a date, however as previously mentioned - this is to see if it was possible through a regular expression.

Body:
I've recently been looking for a regular expression to do some client side date checking, and I haven't been able to find one that can satisfy the following criteria:

Has a range from 1800 - Now

Performs proper date checking with leap years

MM/DD/YYYY Form

Invalid Date Checking

(These constraints were outside of my scope and are a requirement as per the client, despite my efforts to convince them this wasn't the best route)

Current code:

$('input').keyup(function()
{
       var regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
       $(this).toggleClass('invalid',!regex.test($(this).val()));
});

Update:

I should note that this is primarily to see if a regular expression like this would be possible (as the use of a Regex is not my choice in this matter). I am aware of the other (and better) options for validating a date, however as previously mentioned - this is to see if it was possible through a regular expression.

Body:
Hello Find RegEx for your Requirement

Has a range from 1800

Now Performs proper date checking with leap years

DD/MM/YYYY Format

Invalid Date Checking

^(?:(?:31(/)(?:0[13578]|1[02]))\1|(?:(?:29|30)(/)(?:0[13-9]|1[0-2])\2))(?:(?:18|19|20)\d{2})$|^(?:29(/)02\3(?:(?:(?:(?:18|19|20))(?:0[48]|[2468][048]|[13579][26]))))$|^(?:0?[1-9]|1\d|2[0-8])(/)(?:(?:0[1-9])|(?:1[0-2]))\4(?:(?:18|19|20)\d{2})$

Image and debug RegEx At https://www.debuggex.com/

Testing:

DD/MM/YYYY

01/12/190 Not Match

29/02/1903 Not Match

37/02/1903 Not Match

09/03/1703 Not Match

09/03/2103 Not Match

09/31/2103 Not Match

29/02/1904 - Match

01/12/1988 - Match


答:
lodash's _.get does exactly what you want. You can check out the source code to see the implementation.

```<code>const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];

props.forEach(property => {
  const nestedObjAtProperty = nestedObj[property]; // { "subProperty1": { "data": "This is the data for property1 > subProperty1" } }
  const dataPathForProperty = dataPath[property]; // "subProperty1.data"

  const data = _.get(nestedObjAtProperty, dataPathForProperty); // "This is the data for property1 > subProperty1"
  console.log(data);
}
</code>```

Title: How to dynamically process nested object in Javascript if I don't know what is the depth?

Body:
lodash's _.get does exactly what you want. You can check out the source code to see the implementation.

const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];

props.forEach(property => {
  const nestedObjAtProperty = nestedObj[property]; // { "subProperty1": { "data": "This is the data for property1 > subProperty1" } }
  const dataPathForProperty = dataPath[property]; // "subProperty1.data"

  const data = _.get(nestedObjAtProperty, dataPathForProperty); // "This is the data for property1 > subProperty1"
  console.log(data);
}


问:
Slick slider displays only one dot when is dynamic
this is my first ever question in this site, I apologize in advance for my level of English (not my first language)

My issue: Im working with Slick slider plugin in Laravel55. This plugin works perfectly with static declaration, but when I try to do it dynamically (using a compacted variable displayed through a foreach loop) it messes with the navigation part, it shows me only one dot and no arrows on the sides.

Looking through similar questions in this site, I've tried to compare the source code between static and dynamic attempts and it generates the same version with a slight indentation difference.

I've checked the charset, verified to load the plugin js after the jQuery and nothing seems to be wrong.

Dynamic

                        @foreach($testimonials as $t)

“ {{$t->comment}} ”

                                @for($i=0;$i<$t->rate;$i++)

                                @endfor

{{$t->name}}

{{$t->department}}

                        @endforeach

                    @foreach($testimonials as $tp)

                        pAvatar}}">

                    @endforeach

```

<p>Static</p>

<pre class="lang-html prettyprint-override"><code><section class="clients-feedback-area bg-white section_padding_100 clearfix" id="testimonials">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-12 col-md-10">
                    <div class="slider slider-for">
                        <!-- Client Feedback Text  -->
                        <div class="client-feedback-text text-center">
                            <div class="client">
                                <i class="fa fa-quote-left" aria-hidden="true"></i>
                            </div>
                            <div class="client-description text-center">
                                <p>“ Muchas gracias por todo. Buenisima experiencia. ”</p>
                            </div>
                            <div class="star-icon text-center">
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                            </div>
                            <div class="client-name text-center">
                                <h5>Dra. Alice Boyle</h5>
                                <p></p>
                            </div>
                        </div>
                        <!-- Client Feedback Text  -->
                        <div class="client-feedback-text text-center">
                            <div class="client">
                                <i class="fa fa-quote-left" aria-hidden="true"></i>
                            </div>
                            <div class="client-description text-center">
                                <p>“ Agradezco mucho la atención y excelente estadía. ”</p>
                            </div>
                            <div class="star-icon text-center">
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                            </div>
                            <div class="client-name text-center">
                                <h5>Carlos Navas</h5>
                                <p></p>
                            </div>
                        </div>
                        <!-- Client Feedback Text  -->
                        <div class="client-feedback-text text-center">
                            <div class="client">
                                <i class="fa fa-quote-left" aria-hidden="true"></i>
                            </div>
                            <div class="client-description text-center">
                                <p>“ Fue una experiencia buenísima visitar aquí y una estadía excelente y comoda ¡Gracias!.”</p>
                            </div>
                            <div class="star-icon text-center">
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                                <i class="ion-ios-star"></i>
                            </div>
                            <div class="client-name text-center">
                                <h5>Liam Reucle</h5>
                                <p></p>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Client Thumbnail Area -->
                <div class="col-12 col-md-6 col-lg-5">
                    <div class="slider slider-nav">
                        <div class="client-thumbnail">
                            <img src="img/icons/icon-user.png" alt="">
                        </div>
                        <div class="client-thumbnail">
                            <img src="img/icons/icon-user.png" alt="">
                        </div>
                        <div class="client-thumbnail">
                            <img src="img/icons/icon-user.png" alt="">
                        </div>
                        <div class="client-thumbnail">
                            <img src="img/icons/icon-user.png" alt="">
                        </div>
                    </div>
                </div>
            </div>
        </div>
</section>
</code>```

For better understanding of my situation and what i'm trying to achieve i've put visualization as follow (I can't insert images, doesn't have 10 points of reputation)

Dynamic behavior:
https://i.imgur.com/ktQ0Lsl.png

Static behavior:
https://i.imgur.com/CF7JKKD.png

Sorry for any information i may have skipped
Any help or comments will be appreciated

答:
It is because you have set the slidesToShow:3 and you have only three testimonials, slick slider adds slider when you have more than 3 testimonials. if you set the slidesToShow=2 then you will see the slider with dots and arrows and with 2 testimonials at the time.

Hope you will get the answer.

Body:
this is my first ever question in this site, I apologize in advance for my level of English (not my first language)

My issue: Im working with Slick slider plugin in Laravel55. This plugin works perfectly with static declaration, but when I try to do it dynamically (using a compacted variable displayed through a foreach loop) it messes with the navigation part, it shows me only one dot and no arrows on the sides.

Looking through similar questions in this site, I've tried to compare the source code between static and dynamic attempts and it generates the same version with a slight indentation difference.

I've checked the charset, verified to load the plugin js after the jQuery and nothing seems to be wrong.

Dynamic

                        @foreach($testimonials as $t)

“ {{$t->comment}} ”

                                @for($i=0;$i<$t->rate;$i++)

                                @endfor

{{$t->name}}

{{$t->department}}

                        @endforeach

                    @foreach($testimonials as $tp)

                        pAvatar}}">

                    @endforeach

Static

“ Muchas gracias por todo. Buenisima experiencia. ”

Dra. Alice Boyle

“ Agradezco mucho la atención y excelente estadía. ”

Carlos Navas

“ Fue una experiencia buenísima visitar aquí y una estadía excelente y comoda ¡Gracias!.”

Liam Reucle

For better understanding of my situation and what i'm trying to achieve i've put visualization as follow (I can't insert images, doesn't have 10 points of reputation)

Dynamic behavior:
https://i.imgur.com/ktQ0Lsl.png

Static behavior:
https://i.imgur.com/CF7JKKD.png

Sorry for any information i may have skipped
Any help or comments will be appreciated


问:
C# Async Await and general async question
I am trying to understand something about async programming in general.
In C# it seems that everyone is now using async await syntatic sugar for async operations that are IO bound.

My question is: Does any operation that is IO bound like a file reading, http request etc that was sync until now can become asnync by writting a wrapper function that is async?

Or since the underlying "old" implementation if it is sync will not help at all?
will the thread that used to wait until now will be released or not?

Anyone?

答:
Wrapping a method that is sync with an async method can have some benefits. The underlying method will still be synchronous, but you can offload that method to another thread, so the thread that used to wait can now continue it's execution. So in your example, if the UI thread calls the blocking method GetHTTPResource, you can achieve UI responsiveness by offloading that method to another thread using an asynchronous wrapper. I recommend you this blog post, which I think can give you a better understanding of what async over sync implies. (An this other covers sync over async).

With async over sync, there will still be a thread blocked. That is the reason why it makes little sense in case of a web application, using asynchronous wrappers for synchronous functions has no performance benefits. Quoting the aforementioned article (emphasis mine):

The ability to invoke a synchronous method asynchronously does nothing
  for scalability, because you’re typically still consuming the same
  amount of resources you would have if you’d invoked it synchronously
  (in fact, you’re using a bit more, since there’s overhead incurred to
  scheduling something ), you’re just using different resources to do
  it, e.g. a thread from a thread pool instead of the specific thread
  you were executing on.  The scalability benefits touted for
  asynchronous implementations are achieved by decreasing the amount of
  resources you use, and that needs to be baked into the implementation
  of an asynchronous method… it’s not something achieved by wrapping
  around it.

For instante, in case of an ASP.NET application, fully async code allows threads to process new requests while other requests are waiting for I/O operations to complete, thus achieving higher scalability. On the other hand, if the code has underlying synchronous methods for I/O operations, there will be threads blocked that won't be able to do anything but wait until these operations complete. So async over sync usually has no benefit in case of web applications.


问:
How to fix rest get, file download showing sometimes file not found error
So I'm trying to download a file that I upload before, using a rest get method but sometimes I get file not found error and other times it just works. I don't know where the problem is.

I also tried the code that is in this thread file downloading in restful web services and changed it a little but the problem with this code is that I don't see the contents of the files so my solution is a little better I think.

```<code>@GET
  @Path("/{fileName}")
  @Produces(MediaType.APPLICATION_OCTET_STREAM)
  public Response downloadFile(@PathParam("fileName") String fileName) throws IOException
  {
    File ivyFile = new File(fileName);
    byte[] data = ivyFile.readBinary().toByteArray();
    StreamingOutput fileStream = new StreamingOutput()
      {
        @Override
        public void write(java.io.OutputStream output)
        {
          try
          {
            output.write(data);
            output.flush();
          }
          catch (IOException e)
          {
            throw new WebApplicationException("Could not Find the file: '" + fileName + "'", e);
          }
        }
      };
    return Response.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "attachment; filename = " + fileName).build();
  }
</code>```

I expect to download the file with the content and be able to see it.

EDIT:
Also I get response 200 when this error occures. And this error as well:

```<code>MalformedChunkCodingException: CRLF expected at end of chunk
    FacesException: org.apache.http.MalformedChunkCodingException: CRLF expected at end of chunk
    Error during rendering of html dialog 'com.axonivy.connectivity.rest.FileUpload'
</code>```

答: I found the solution. The problem was with my IDE that was causing a timeout for the download.</p>

Body:
So I'm trying to download a file that I upload before, using a rest get method but sometimes I get file not found error and other times it just works. I don't know where the problem is.

I also tried the code that is in this thread file downloading in restful web services and changed it a little but the problem with this code is that I don't see the contents of the files so my solution is a little better I think.

@GET
  @Path("/{fileName}")
  @Produces(MediaType.APPLICATION_OCTET_STREAM)
  public Response downloadFile(@PathParam("fileName") String fileName) throws IOException
  {
    File ivyFile = new File(fileName);
    byte[] data = ivyFile.readBinary().toByteArray();
    StreamingOutput fileStream = new StreamingOutput()
      {
        @Override
        public void write(java.io.OutputStream output)
        {
          try
          {
            output.write(data);
            output.flush();
          }
          catch (IOException e)
          {
            throw new WebApplicationException("Could not Find the file: '" + fileName + "'", e);
          }
        }
      };
    return Response.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "attachment; filename = " + fileName).build();
  }

I expect to download the file with the content and be able to see it.

EDIT:
Also I get response 200 when this error occures. And this error as well:

MalformedChunkCodingException: CRLF expected at end of chunk
    FacesException: org.apache.http.MalformedChunkCodingException: CRLF expected at end of chunk
    Error during rendering of html dialog 'com.axonivy.connectivity.rest.FileUpload'


问:
Return a new string where everth xth character (starting at 0) is now followed by *?
I wanna write a function that takes a string, s, and an int, x. It should return a new string where every xth character (starting from zero) is now followed by an '*'.

So far I've tried this code:

```<code>def string_chunks(string, x):
    """
    >>> string_chunks("Once upon a time, in a land far, far away", 5)
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    for ch in string:
        return ch + "*"
</code>```

but I am very stuck and am unable to make it work.
I would appreciate any help. If you provide an answer, it would be nice if you could comment the code also.

答:
try this

```<code>def string_chunks(string, x):
    """
    >>>
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    count = 0
    newstring = []
    for ch in string:
        count = count + 1
        if count == x:
            newstring.append("*")
            newstring.append(ch)
            count = 0
        else:
            newstring.append(ch)
    return("".join(str(x) for x in newstring))
output_s = string_chunks("Once upon a time, in a land far, far away", 5)
print output_s
</code>```

Output:

```<code>Once* upon* a ti*me, i*n a l*and f*ar, f*ar aw*ay
</code>```

Body:
I wanna write a function that takes a string, s, and an int, x. It should return a new string where every xth character (starting from zero) is now followed by an '*'.

So far I've tried this code:

def string_chunks(string, x):
    """
    >>> string_chunks("Once upon a time, in a land far, far away", 5)
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    for ch in string:
        return ch + "*"

but I am very stuck and am unable to make it work.
I would appreciate any help. If you provide an answer, it would be nice if you could comment the code also.

Body:
try this

def string_chunks(string, x):
    """
    >>>
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    count = 0
    newstring = []
    for ch in string:
        count = count + 1
        if count == x:
            newstring.append("*")
            newstring.append(ch)
            count = 0
        else:
            newstring.append(ch)
    return("".join(str(x) for x in newstring))
output_s = string_chunks("Once upon a time, in a land far, far away", 5)
print output_s

Output:

Once* upon* a ti*me, i*n a l*and f*ar, f*ar aw*ay


问:
What's the most efficient way to remove all symbols from an object?
Let's say I have an object where I want to keep internal-only key/pairs with symbols.  Given...

```<code>let obj = {
    [Symbol.for('foo')]: 'internal-only member',
    a: 1,
    b: 2,
    c: 3
}
</code>```

When I return these to a client through my API, I want to strip out all Symbols from the Object because the client doesn't have any use for them.

I'd like a generic function that will return:

```<code>{
    a: 1,
    b: 2,
    c: 3
}
</code>```

In other words:

```<code>returnScrubbedObj = (obj) => {
    // filter/map/remove/copy etc the original object to a new object without symbols
    return objWithoutSymbols
}
</code>```

I know there are probably many different ways to do this; just looking for the best/most efficient one.

答:
You could get the entries and build a new object of the entries.

let obj = {
    [Symbol.for('foo')]: 'internal-only member',
    a: 1,
    b: 2,
    c: 3
}
console.log(Object.fromEntries(Object.entries(obj)));```

Body:
Let's say I have an object where I want to keep internal-only key/pairs with symbols.  Given...

let obj = {
    [Symbol.for('foo')]: 'internal-only member',
    a: 1,
    b: 2,
    c: 3
}

When I return these to a client through my API, I want to strip out all Symbols from the Object because the client doesn't have any use for them.

I'd like a generic function that will return:

{
    a: 1,
    b: 2,
    c: 3
}

In other words:

returnScrubbedObj = (obj) => {
    // filter/map/remove/copy etc the original object to a new object without symbols
    return objWithoutSymbols
}

I know there are probably many different ways to do this; just looking for the best/most efficient one.


问:
TypeError: list indices must be integers or slices, not str
I've got two lists that I want to merge into a single array and finally put it in a csv file.

How I can avoid this error :

def fill_csv(self, array_urls, array_dates, csv_file_path):
    result_array = []
    array_length = str(len(array_dates))

    # We fill the CSV file
    file = open(csv_file_path, "w")
    csv_file = csv.writer(file, delimiter=';', lineterminator='\n')

    # We merge the two arrays in one

    for i in array_length:
        result_array[i][0].append(array_urls[i])
        result_array[i][1].append(array_dates[i])
        i += 1

    csv_file.writerows(result_array)
```
<p>And got :</p>
<pre class="lang-none prettyprint-override"><code>  File "C:\Users\--\gcscan.py", line 63, in fill_csv
    result_array[i][0].append(array_urls[i])
TypeError: list indices must be integers or slices, not str
</code>```

How can my count work ?

答:
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when was iterating over the list of dictionaries and hit a list type object then I would get this error since I was trying to access keys within each dictionary.

I had to made sure that I only added dictionary objects to that list

Body:
I've got two lists that I want to merge into a single array and finally put it in a csv file.

How I can avoid this error :

def fill_csv(self, array_urls, array_dates, csv_file_path):
    result_array = []
    array_length = str(len(array_dates))

    # We fill the CSV file
    file = open(csv_file_path, "w")
    csv_file = csv.writer(file, delimiter=';', lineterminator='\n')

    # We merge the two arrays in one

    for i in array_length:
        result_array[i][0].append(array_urls[i])
        result_array[i][1].append(array_dates[i])
        i += 1

    csv_file.writerows(result_array)

And got :

  File "C:\Users\--\gcscan.py", line 63, in fill_csv
    result_array[i][0].append(array_urls[i])
TypeError: list indices must be integers or slices, not str

How can my count work ?


问:
Why Gerrit is unable to create branch by itself?
Following this answer and my own question, I have a simple (hope so) question.

If I'm pushing a particular branch, with all required refs properly set:

```<code>git checkout 82-blah-blah
git push origin HEAD:refs/for/82-blah-blah
</code>```

Why do I always get:

```<code>! [remote rejected] HEAD -> refs/for/82-blah-blah (branch 82-blah-blah not found)
</code>```

and I always have to go to Gerrit's UI and create that branch manually?

Isn't that an obvious step, that Gerrit could simply automate? Or am I missing something?

答:
Use this simple bash script to create and push a new branch to gerrit.
Usage: Branch_name and CommitId are 2 inputs needed</p>

```<code>#!/bin/bash
read -p "Enter New Branch Name: " Branch_Name

read -p "Enter CommitID:" CommitID

git fetch --all

git branch $Branch_Name $CommitID

git push origin $Branch_Name:$Branch_Name

git checkout $Branch_Name

git branch --set-upstream-to=origin/$Branch_Name $Branch_Name
</code>```

Body:
Following this answer and my own question, I have a simple (hope so) question.

If I'm pushing a particular branch, with all required refs properly set:

git checkout 82-blah-blah
git push origin HEAD:refs/for/82-blah-blah

Why do I always get:

! [remote rejected] HEAD -> refs/for/82-blah-blah (branch 82-blah-blah not found)

and I always have to go to Gerrit's UI and create that branch manually?

Isn't that an obvious step, that Gerrit could simply automate? Or am I missing something?

Body:
Use this simple bash script to create and push a new branch to gerrit.
Usage: Branch_name and CommitId are 2 inputs needed

#!/bin/bash
read -p "Enter New Branch Name: " Branch_Name

read -p "Enter CommitID:" CommitID

git fetch --all

git branch $Branch_Name $CommitID

git push origin $Branch_Name:$Branch_Name

git checkout $Branch_Name

git branch --set-upstream-to=origin/$Branch_Name $Branch_Name


问:
Clear my view page when I hit finish button
I'm creating a simple Queuing system my button BtnNext() dequeue the data that has been enqueued and render it on my view and on my CallScreen view.

Here is my button for BtnNext()

```<code>  public ActionResult BtnNext()
    {
        System.Threading.Thread.Sleep(500);
        var first = MyQueue.todayQueue.Dequeue();
        MyQueue.todayQueue.Count();
        TempData["QueueItem"] = first;
        TempData.Keep();
        return PartialView("_queuenumber");
    }
</code>```

when I hit the BtnNext() it will render the Dequeued data from my CallScreen view and its auto refreshing every 1 sec.

But my problem is I need to hit the BtnFinish() button to clear my CallScreen view and display nothing, right now its just displaying the previous QueueNumber, I want it to be cleared out.

Here is my Controller for my BtnFinish()

```<code>public PartialViewResult BtnFinish()
{
    System.Threading.Thread.Sleep(300);
    MyQueue.todayQueue.Count();
    TempData.Keep();
    return PartialView("_finish");
}
</code>```

Here is my view for my CallScreen:

```<code>@{
    var item = (Rosh.QueueMe.Web.Models.MyQueue)TempData["QueueItem"];
}

    <table id="auto">
        <tr style="font-family:'Arial Rounded MT'">
            <th class="tickets">TICKETS</th>
            <th class="name">NAME</th>
            <th class="counter">COUNTER</th>
            <th class="service">SERVICE</th>
        </tr>
        <tr class="data">
            <td>#@item.QueueNumber</td>
            <td>@item.Name</td>
            <td>Desk 1</td>
            <td>@item.ServiceId</td>
        </tr>
    </table>
</code>```

Its getting its data from my TempData["QueueItem"];

I tried using this code for my callscreen view, but for some reason its giving me an error that my @item.QueueNumber, @item.Name and @item.ServiceId does not exist in the current context anymore.

```<code>@if(TempData["QueueItem"] != null)
{
   var item = (Rosh.QueueMe.Web.Models.MyQueue)ViewBag.QueueItem;
}
</code>```

答:
I think you just need </p>

```<code>ViewData.Clear();
</code>```

Body:
I'm creating a simple Queuing system my button BtnNext() dequeue the data that has been enqueued and render it on my view and on my CallScreen view.

Here is my button for BtnNext()

  public ActionResult BtnNext()
    {
        System.Threading.Thread.Sleep(500);
        var first = MyQueue.todayQueue.Dequeue();
        MyQueue.todayQueue.Count();
        TempData["QueueItem"] = first;
        TempData.Keep();
        return PartialView("_queuenumber");
    }

when I hit the BtnNext() it will render the Dequeued data from my CallScreen view and its auto refreshing every 1 sec.

But my problem is I need to hit the BtnFinish() button to clear my CallScreen view and display nothing, right now its just displaying the previous QueueNumber, I want it to be cleared out.

Here is my Controller for my BtnFinish()

public PartialViewResult BtnFinish()
{
    System.Threading.Thread.Sleep(300);
    MyQueue.todayQueue.Count();
    TempData.Keep();
    return PartialView("_finish");
}

Here is my view for my CallScreen:

@{
    var item = (Rosh.QueueMe.Web.Models.MyQueue)TempData["QueueItem"];
}

            TICKETS
            NAME
            COUNTER
            SERVICE

            #@item.QueueNumber
            @item.Name
            Desk 1
            @item.ServiceId

Its getting its data from my TempData["QueueItem"];

I tried using this code for my callscreen view, but for some reason its giving me an error that my @item.QueueNumber, @item.Name and @item.ServiceId does not exist in the current context anymore.

@if(TempData["QueueItem"] != null)
{
   var item = (Rosh.QueueMe.Web.Models.MyQueue)ViewBag.QueueItem;
}

Body:
I think you just need

ViewData.Clear();


答:
Using a new string instead of a list

I thought it could be easier using a new string (ns) instead of a list to be joined, just adding each character of the original string (text = s) with a '' after each multiple of the interval x (checked with the if multiple_of_x. To check if the n (index of the character of s) is a multiple I used n % x == 0 that is equal to zero only for multiple of x (ex.: 5 10 15, because 5 % 5 = 0, 15 % 5 = 0.... and so on). If the result of n % x in not 0, it will add only the character without the ''.

```<code>def string_chunks(s,x=5):
    ns = ""
    for n,ch in enumerate(s):
        multiple_of_x = (n % x == 0)
        ns += ch + "*" if multiple_of_x else ch
    return ns

text = "Once upon a time, in a land far, far away"
print(string_chunks(text))
</code>```

Using a list

It can be done this way too.

```<code>def string_chunks(s,x=5):
    ns = []
    for n,ch in enumerate(s):
        multiple_of_interval = (n % x == 0)
        ns.append(ch + "*") if multiple_of_interval else ns.append(ch)
    ns = "".join(ns)
    return ns

text = "Once upon a time, in a land far, far away"
print(string_chunks(text))
</code>```

Output

```<code>O*nce u*pon a* time*, in *a lan*d far*, far* away*
</code>```

Title: Return a new string where everth xth character (starting at 0) is now followed by *?

Body:
Using a new string instead of a list

I thought it could be easier using a new string (ns) instead of a list to be joined, just adding each character of the original string (text = s) with a '' after each multiple of the interval x (checked with the if multiple_of_x. To check if the n (index of the character of s) is a multiple I used n % x == 0 that is equal to zero only for multiple of x (ex.: 5 10 15, because 5 % 5 = 0, 15 % 5 = 0.... and so on). If the result of n % x in not 0, it will add only the character without the ''.

def string_chunks(s,x=5):
    ns = ""
    for n,ch in enumerate(s):
        multiple_of_x = (n % x == 0)
        ns += ch + "*" if multiple_of_x else ch
    return ns

text = "Once upon a time, in a land far, far away"
print(string_chunks(text))

Using a list

It can be done this way too.

def string_chunks(s,x=5):
    ns = []
    for n,ch in enumerate(s):
        multiple_of_interval = (n % x == 0)
        ns.append(ch + "*") if multiple_of_interval else ns.append(ch)
    ns = "".join(ns)
    return ns

text = "Once upon a time, in a land far, far away"
print(string_chunks(text))

Output

O*nce u*pon a* time*, in *a lan*d far*, far* away*


答:
You could use JSON methods:

let obj = {[Symbol.for('foo')]:'internal-only member',a:1,b:2,c:3};
const res = JSON.parse(JSON.stringify(obj));
console.log(res);```
</div>
</div>
</p>

<p>A more verbose version using <code>reduce</code> and <code>typeof</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {[Symbol.for('foo')]:'internal-only member',a:1,b:2,c:3};
const res = Object.entries(obj).reduce((acc, [k, v]) => typeof k == "symbol" ? acc : (acc[k] = v, acc), {});
console.log(res);</code>```

And since you asked about the efficiency, the reduce method is faster.

Title: What's the most efficient way to remove all symbols from an object?

Body:
You could use JSON methods:

let obj = {[Symbol.for('foo')]:'internal-only member',a:1,b:2,c:3};
const res = JSON.parse(JSON.stringify(obj));
console.log(res);

A more verbose version using reduce and typeof:

let obj = {[Symbol.for('foo')]:'internal-only member',a:1,b:2,c:3};
const res = Object.entries(obj).reduce((acc, [k, v]) => typeof k == "symbol" ? acc : (acc[k] = v, acc), {});
console.log(res);

And since you asked about the efficiency, the reduce method is faster.


问:
Automation call using curl - Jmeter
Good afternoon people!

How do I add a call in Curler in Jmeter to get my header to use in tests later?

Which element of test? HTTP request same?

can you help me?

Follow the curl:
curl -X POST -vu xxx: b57f4a4f-a455-4014-9ac8-87c6dac7e8d3 https://apibpp.xvv.com.br/api/oauth/token -H "Accept: application / json" -d " password = xxxx & username = yyyy & grant_type = password & scope = read% 20write "

Thank you

答:
You can use jmeter HTTP recorder to record your curl request. It will provide the request and the required header values.

Please check the below links for more information:-

How to use curl request in JMeter?

testing a curl request with jmeter

You can find many other links for converting curl to jmeter.

Please check if that helps.

Update:-
In version 5.1.1, there is an option to import from cURL available under "Tools". Please check if that can help with your requirement.
For more info. check here

Kindly note that I have never used cURL, so I am just trying to see if you can able to handle it with the features available in the jmeter.

Title: Automation call using curl - Jmeter


问:
Instanceof with string name of class instead instantiating class
Is it possible to proof if a class is an instance of a specific class without generating a new object?

At example I've got an array with class names:

```<code>$classNames = [
    'TestClass',
    'ExampleClass',
    'OtherClass'
];
</code>```

Now I want to proof if these 3 classes are a instance of the main class (at example 'Classes').

In a loop it should proof like this:

```<code>foreach($classNames as $className)
{
   if($className instanceof Classes)
   {
      // some code
   }
}
</code>```

But this isn't working because firstly I must instantiate the classes like TestClass...

Is there any alternative? I want to check if the classes in the array are a instance of 'Classes'.

答:
You can use is_subclass_of to make this check:

```<code>foreach($classNames as $className)
{
   if(is_subclass_of($className, 'Classes')
   {
      // some code
   }
}
</code>```

Body:
Is it possible to proof if a class is an instance of a specific class without generating a new object?

At example I've got an array with class names:

$classNames = [
    'TestClass',
    'ExampleClass',
    'OtherClass'
];

Now I want to proof if these 3 classes are a instance of the main class (at example 'Classes').

In a loop it should proof like this:

foreach($classNames as $className)
{
   if($className instanceof Classes)
   {
      // some code
   }
}

But this isn't working because firstly I must instantiate the classes like TestClass...

Is there any alternative? I want to check if the classes in the array are a instance of 'Classes'.

Body:
You can use is_subclass_of to make this check:

foreach($classNames as $className)
{
   if(is_subclass_of($className, 'Classes')
   {
      // some code
   }
}


答:
You can use a Object.keys to loop through the dataPath object. Then you split the value and use it an a for loop and keep track of the data.

let nestedObj = {
    "property1": {
        "subProperty1": {
            "data": "This is the data for property1 > subProperty1"
        }
    },

    "property2": {
        "subProperty1": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty1 > anotherSubProperty1"
            }
        },
        "subProperty2": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty2 > anotherSubProperty1"
            }
        }
    },

    "property3": {
        "subProperty1": {
            "data": "This is the data for property3 > subProperty1"
        }
    }
}

let dataPath = {
    "property1": "subProperty1.data",
    "property2": "subProperty2.anotherSubProperty1.data",
    "property3": "subProperty1.data",
}

let properties = ["property1", "property2", "property3"]
for (let property of properties) {
    let path = dataPath[property].split('.')
    let data = nestedObj[property]
    for (let i = 0; i < path.length; i++) {
        data = data[path[i]]
        if (i + 1 === path.length) {
            console.log(data)
        }
    }
}```

Body:
Sorry, I don't know how to word this question properly but basically, I have this nested object nestedObj. I want to dynamically process this object but the depth of the object is not fixed. So for example:

nestedObj = {
    "property1":{
        "subProperty1": {
            "data": "This is the data for property1 > subProperty1"
        }
    },

    "property2":{
        "subProperty1": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty1 > anotherSubProperty1"
            }
        },
        "subProperty2": {
            "anotherSubProperty1": {
                "data": "This is the data for property2 > subProperty2 > anotherSubProperty1"
            }
        }
    },

    "property3":{
        "subProperty1": {
            "data": "This is the data for property3 > subProperty1"
        }
    }
}

Now I want to process this object in a for of loop where my end goal is to get the value of data of certain nodes. Now, the path to the value of each object nodes are defined in another object:

dataPath = {
    "property1": "subProperty1.data",
    "property2": "subProperty2.anotherSubProperty1.data",
    "property3": "subProperty1.data",
}

And then I used this for of loop to process them:

properties = ["property1", "property2", "property3"];
for(var property of properties) {
    path_to_data = dataPath[property].split(".");
    data = nestedObj[path_to_data[0]][path_to_data[1]];

    // Some other logic
}

Obviously, this only works for "property1" and "property3". I have to add special handling for all the objects that have more than 2 inner nodes. For large data with varying numbers of depth, it would not be ideal to manually add these special handlers. So my question is, in Javascript, is there any way for me to dynamically process nested object when I have the "path" to a certain node.


问:
How to check if data exist in Access table
I have created a userform that insert data into an Access table. while inserting data, I want to make sure that the ID inserted must exist in the Access table. I have used the DCOUNT function to do this but this is rendering a 'Type Mismatch' error. I have tried every solution found on the internet but nothing is working here. Please help!

I have modified the DCOUNT expression to put the form variable name into '', [], creating an external variable that refers to the DCOUNT function but nothing is working

```<code>Set conn = createobject("ADODB.connection")
set rs = createobject("ADODB.recordset")
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data source = C:\MyPathMyDB.accdb"
qry = "select * from employee"

with rs
.adnew
if isnumeric(ManagerID) = false then
msgbox "Invalid Manager ID"
exit sub
elseif application.worksheetfunction.dcount("Employee_ID","Employee","activ='Yes'  and Employee_ID='"  & [EmployeeForm.ManagerID] & "'") = 0 then
msgbox "Manager does not exist"
exit sub
else
. fields("Manager_ID").value = ManagerID
end if
end with
</code>```

I expect the function to determine if the Employeeform.ManagerID exist in Employee_ID. If yes, then proceed, else display error message

答:
Since you check for the ManagerID to be numeric, I guess its value isn't text, and active is probably a boolean, and as you can access ManagerID on its own, use it as is, and the criteria could read:

```<code>"activ=True and Employee_ID=" & ManagerID & ""
</code>```

Body:
I have created a userform that insert data into an Access table. while inserting data, I want to make sure that the ID inserted must exist in the Access table. I have used the DCOUNT function to do this but this is rendering a 'Type Mismatch' error. I have tried every solution found on the internet but nothing is working here. Please help!

I have modified the DCOUNT expression to put the form variable name into '', [], creating an external variable that refers to the DCOUNT function but nothing is working

Set conn = createobject("ADODB.connection")
set rs = createobject("ADODB.recordset")
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data source = C:\MyPathMyDB.accdb"
qry = "select * from employee"

with rs
.adnew
if isnumeric(ManagerID) = false then
msgbox "Invalid Manager ID"
exit sub
elseif application.worksheetfunction.dcount("Employee_ID","Employee","activ='Yes'  and Employee_ID='"  & [EmployeeForm.ManagerID] & "'") = 0 then
msgbox "Manager does not exist"
exit sub
else
. fields("Manager_ID").value = ManagerID
end if
end with

I expect the function to determine if the Employeeform.ManagerID exist in Employee_ID. If yes, then proceed, else display error message

Body:
Since you check for the ManagerID to be numeric, I guess its value isn't text, and active is probably a boolean, and as you can access ManagerID on its own, use it as is, and the criteria could read:

"activ=True and Employee_ID=" & ManagerID & ""


问:
How to tell heroku to use rails 3 and ruby 1.9.2 for a newly created app?
I created a new app on my machine using rvm ruby1.9.2p0 and rails 3.0.1, and did the following:

```<code>rails new -J -d mysql appname
git init
git add .
git commit
heroku create
</code>```

and the app is created. but when i do:

```<code>heroku rake db:create --trace
</code>```

I get:

```<code>Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Couldn't create database for {"reconnect"=>false, "encoding"=>"utf8", "username"=>"root", "adapter"=>"mysql2", "database"=>"app_production", "pool"=>5, "password"=>nil, "socket"=>"/var/run/mysqld/mysqld.sock"}, charset: utf8, collation: utf8_unicode_ci
(in /app)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create
</code>```

and when i do:
    heroku rake db:migrate --trace, then the trace has lines like:

```<code>/app/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:590:in
</code>```

which shows it is using ruby 1.8 instead of ruby 1.9.2

How can I create a database on my heroku app and make it use ruby 1.9.2p0?

答:
If you've already created the application on Heroku it will have defaulted to 1.8.7 as you've found. You can specify the stack to create the application on when you create your app;

```<code>heroku create myapp --stack bamboo-mri-1.9.2
</code>```

To migrate your app to 1.9.2 you will need to issue

```<code>heroku stack:migrate bamboo-mri-1.9.2
</code>```

Once migrated you will need to repush your application (if i remember correctly)

Body:
I created a new app on my machine using rvm ruby1.9.2p0 and rails 3.0.1, and did the following:

rails new -J -d mysql appname
git init
git add .
git commit
heroku create

and the app is created. but when i do:

heroku rake db:create --trace

I get:

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Couldn't create database for {"reconnect"=>false, "encoding"=>"utf8", "username"=>"root", "adapter"=>"mysql2", "database"=>"app_production", "pool"=>5, "password"=>nil, "socket"=>"/var/run/mysqld/mysqld.sock"}, charset: utf8, collation: utf8_unicode_ci
(in /app)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create

and when i do:
    heroku rake db:migrate --trace, then the trace has lines like:

/app/.bundle/gems/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:590:in

which shows it is using ruby 1.8 instead of ruby 1.9.2

How can I create a database on my heroku app and make it use ruby 1.9.2p0?

Body:
If you've already created the application on Heroku it will have defaulted to 1.8.7 as you've found. You can specify the stack to create the application on when you create your app;

heroku create myapp --stack bamboo-mri-1.9.2

To migrate your app to 1.9.2 you will need to issue

heroku stack:migrate bamboo-mri-1.9.2

Once migrated you will need to repush your application (if i remember correctly)