问:
OkHttp3 response is showing error in custom adapter class in android
I am using OkHttp3 to fetch data from server I have custom adapter class in which I have a button in recycler view item on the click of a button I am sending request to the server and getting response.

But at the time of getting response I am getting error:

```<code>2020-02-14 23:23:23.222 10597-12522/com.example.aamkuconnect E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.aamkuconnect, PID: 10597
java.lang.ClassCastException: androidx.multidex.MultiDexApplication cannot be cast to com.example.aamkuconnect.AdminNewOrders
</code>```

Below is my code:

AdminNewOrders.class

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

RecyclerView adminSeeOrder;
ProgressBar my_prog;
AdminSeeNewOrderAdapter adapter;
List<AdminSeeNewOrderModel> list = new ArrayList<>();

private static final String URL = "https://www.example.com";

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

    ActionBar ab = getSupportActionBar();
    assert ab!= null;
    ab.setTitle("New orders");
    ab.setDisplayHomeAsUpEnabled(true);

    my_prog = findViewById(R.id.my_prog);
    adminSeeOrder = findViewById(R.id.adminSeeOrder);
    adminSeeOrder.setHasFixedSize(true);
    adminSeeOrder.setLayoutManager(new LinearLayoutManager(this));

    newOrders();

}

private void newOrders(){

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    RequestBody formBody = new FormBody.Builder()
            .add("order_status","pending")
            .build();

    Request request = new Request.Builder().post(formBody).url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                        if(jsonArray.length() > 0){

                            my_prog.setVisibility(View.INVISIBLE);

                            for(int i = jsonArray.length()-1;i>-1;i--){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");

                                AdminSeeNewOrderModel model = new AdminSeeNewOrderModel(str1);
                                list.add(model);

                            }

                            adapter = new AdminSeeNewOrderAdapter(list,getApplicationContext());
                            adminSeeOrder.setAdapter(adapter);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    my_prog.setVisibility(View.INVISIBLE);
                   Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

    switch(item.getItemId()){

        case android.R.id.home:

            Intent i = new Intent(AdminNewOrders.this,Dashboard.class);
            startActivity(i);
            finish();
            break;
    }

    return super.onOptionsItemSelected(item);
  }
}
</code>```

AdminSeeNewOrderAdapter.class

```<code>public class AdminSeeNewOrderAdapter extends RecyclerView.Adapter<AdminSeeNewOrderAdapter.ViewHolder> {

List<AdminSeeNewOrderModel> list = new ArrayList<>();
Context context;

private static final String URL = "https://example.com";

public AdminSeeNewOrderAdapter(List<AdminSeeNewOrderModel> list, Context context) {
    this.list = list;
    this.context = context;
}

@NonNull
@Override
public AdminSeeNewOrderAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.admin_see_new_order_row,parent,false);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull final AdminSeeNewOrderAdapter.ViewHolder holder, final int position) {

    final AdminSeeNewOrderModel model = list.get(position);

     holder.adSeeName.setText(model.getName());

    holder.accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

               acceptOrders(position);

        }
    });

}

@Override
public int getItemCount() {
    return list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    TextView adSeeName,adSeeDate,adSeePhone,adSeeAdr,prodName,prodCost,viewDetails,accept,cancel;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

           TextView  adSeeName = itemView.findViewById(R.id.adSeeName);
          Textview  accept = itemView.findViewById(R.id.accept);

    }
}

private void acceptOrders(String mobile, String product, String date, final int position){

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    RequestBody formBody = new FormBody.Builder()
            .add("phone",mobile)
            .add("date",date)
            .add("product",product)
            .build();

    Request request = new Request.Builder().post(formBody).url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            ((AdminNewOrders)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        String resp = response.body().string();

                         if(resp.equals("Updated successfully")){

                             list.remove(position);
                             notifyItemRemoved(position);
                         }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            ((AdminNewOrders)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    });
  }
}
</code>```

build.gradle

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
    applicationId "com.example.aamkuconnect"
    minSdkVersion 16
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
  }
 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
      }
   }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'

implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.1.0'
implementation 'androidx.navigation:navigation-ui:2.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
testImplementation 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-analytics:17.2.0'
implementation 'com.google.firebase:firebase-auth:19.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.2.1'
implementation 'androidx.multidex:multidex:2.0.1'

}

apply plugin: 'com.google.gms.google-services'
</code>```

Someone please let me know how can I resolve this error.Any help would be appreciated.

THANKS

答:
I could tell you a bunch of things why it would happen:

The adapter should not be making http calls

The adapter should not be making ui calls (Toast.makeText...)

There are other ways to get back to the ui thread without invoking the runOnUiThread like

```<code>   new Handler(Looper.getMainLooper()).post(new Runnable {
       override void run(){
          Toast.makeText...
         }
   });
</code>```

But your main issue is, that the context you are providing is an application context, and is not attached to any UiThread, if you still want to do it this way, you need to pass the Activity context, and even there make sure the context is still valid.

Change this:

```<code>   adapter = new AdminSeeNewOrderAdapter(list,getApplicationContext());
</code>```

to this:

```<code>   adapter = new AdminSeeNewOrderAdapter(list, AdminNewOrders.this);
</code>```

and it would work.

Body:
I am using OkHttp3 to fetch data from server I have custom adapter class in which I have a button in recycler view item on the click of a button I am sending request to the server and getting response.

But at the time of getting response I am getting error:

2020-02-14 23:23:23.222 10597-12522/com.example.aamkuconnect E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.aamkuconnect, PID: 10597
java.lang.ClassCastException: androidx.multidex.MultiDexApplication cannot be cast to com.example.aamkuconnect.AdminNewOrders

Below is my code:

AdminNewOrders.class

public class AdminNewOrders extends AppCompatActivity {

RecyclerView adminSeeOrder;
ProgressBar my_prog;
AdminSeeNewOrderAdapter adapter;
List<AdminSeeNewOrderModel> list = new ArrayList<>();

private static final String URL = "https://www.example.com";

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

    ActionBar ab = getSupportActionBar();
    assert ab!= null;
    ab.setTitle("New orders");
    ab.setDisplayHomeAsUpEnabled(true);

    my_prog = findViewById(R.id.my_prog);
    adminSeeOrder = findViewById(R.id.adminSeeOrder);
    adminSeeOrder.setHasFixedSize(true);
    adminSeeOrder.setLayoutManager(new LinearLayoutManager(this));

    newOrders();

}

private void newOrders(){

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    RequestBody formBody = new FormBody.Builder()
            .add("order_status","pending")
            .build();

    Request request = new Request.Builder().post(formBody).url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                        if(jsonArray.length() > 0){

                            my_prog.setVisibility(View.INVISIBLE);

                            for(int i = jsonArray.length()-1;i>-1;i--){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");

                                AdminSeeNewOrderModel model = new AdminSeeNewOrderModel(str1);
                                list.add(model);

                            }

                            adapter = new AdminSeeNewOrderAdapter(list,getApplicationContext());
                            adminSeeOrder.setAdapter(adapter);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    my_prog.setVisibility(View.INVISIBLE);
                   Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

    switch(item.getItemId()){

        case android.R.id.home:

            Intent i = new Intent(AdminNewOrders.this,Dashboard.class);
            startActivity(i);
            finish();
            break;
    }

    return super.onOptionsItemSelected(item);
  }
}

AdminSeeNewOrderAdapter.class

public class AdminSeeNewOrderAdapter extends RecyclerView.Adapter<AdminSeeNewOrderAdapter.ViewHolder> {

List<AdminSeeNewOrderModel> list = new ArrayList<>();
Context context;

private static final String URL = "https://example.com";

public AdminSeeNewOrderAdapter(List<AdminSeeNewOrderModel> list, Context context) {
    this.list = list;
    this.context = context;
}

@NonNull
@Override
public AdminSeeNewOrderAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.admin_see_new_order_row,parent,false);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull final AdminSeeNewOrderAdapter.ViewHolder holder, final int position) {

    final AdminSeeNewOrderModel model = list.get(position);

     holder.adSeeName.setText(model.getName());

    holder.accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

               acceptOrders(position);

        }
    });

}

@Override
public int getItemCount() {
    return list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    TextView adSeeName,adSeeDate,adSeePhone,adSeeAdr,prodName,prodCost,viewDetails,accept,cancel;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

           TextView  adSeeName = itemView.findViewById(R.id.adSeeName);
          Textview  accept = itemView.findViewById(R.id.accept);

    }
}

private void acceptOrders(String mobile, String product, String date, final int position){

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    RequestBody formBody = new FormBody.Builder()
            .add("phone",mobile)
            .add("date",date)
            .add("product",product)
            .build();

    Request request = new Request.Builder().post(formBody).url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            ((AdminNewOrders)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        String resp = response.body().string();

                         if(resp.equals("Updated successfully")){

                             list.remove(position);
                             notifyItemRemoved(position);
                         }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            ((AdminNewOrders)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    });
  }
}

build.gradle

apply plugin: 'com.android.application'

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
    applicationId "com.example.aamkuconnect"
    minSdkVersion 16
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
  }
 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
      }
   }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'

implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.1.0'
implementation 'androidx.navigation:navigation-ui:2.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
testImplementation 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-analytics:17.2.0'
implementation 'com.google.firebase:firebase-auth:19.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.2.1'
implementation 'androidx.multidex:multidex:2.0.1'

}

apply plugin: 'com.google.gms.google-services'

Someone please let me know how can I resolve this error.Any help would be appreciated.

THANKS

Body:
I could tell you a bunch of things why it would happen:

The adapter should not be making http calls

The adapter should not be making ui calls (Toast.makeText...)

There are other ways to get back to the ui thread without invoking the runOnUiThread like

   new Handler(Looper.getMainLooper()).post(new Runnable {
       override void run(){
          Toast.makeText...
         }
   });

But your main issue is, that the context you are providing is an application context, and is not attached to any UiThread, if you still want to do it this way, you need to pass the Activity context, and even there make sure the context is still valid.

Change this:

   adapter = new AdminSeeNewOrderAdapter(list,getApplicationContext());

to this:

   adapter = new AdminSeeNewOrderAdapter(list, AdminNewOrders.this);

and it would work.


来源: stackexchange

问:
Python conditional using regex with multiline string
I need help with very simples question, a conditional using regex with multiline string. No make sense to me why this not work:

```<code>if(re.match(r"\w", " \n\n\n  aaaaaaaaaaaa\n\n", re.MULTILINE)):
    print('ok')
else:
    print('fail')

fail
</code>```

I expected that result be ok, but no match any data. I trying using https://regex101.com/r/BsdymE/1, but there works and in my code not works.

答:
re.match will only return a match if the search string is at the beginning.

https://docs.python.org/3/library/re.html#re.match

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Try using re.search(pattern, string, flags=0) instead

ContentLicense: CC BY-SA 4.0

Body:
I need help with very simples question, a conditional using regex with multiline string. No make sense to me why this not work:

if(re.match(r"\w", " \n\n\n  aaaaaaaaaaaa\n\n", re.MULTILINE)):
    print('ok')
else:
    print('fail')

fail

I expected that result be ok, but no match any data. I trying using https://regex101.com/r/BsdymE/1, but there works and in my code not works.


问:
How to separate HTML and Javascript
I am styding JS right now.
I need to get the HTML and JS as many as possible getting seperated.
So that everything is in a HTML and a loose JS file.
How do I seperate this:

   <!DOCTYPE html>

        <title>Inzendopgave 242S2 - F.W.J.C. de Graaff

        </title>

Inzendopgave 242S2 - F.W.J.C. de Graaff

Voer uw bedragen in:

    <input type="text" id="invoer1">

Uw ingevoerde totaal:

0

```

When I place everything that is inside the script-tags and save that to a seperate js-file, the event-listener doesn't work anymore... Well is it possible at all to separate it?

Greetings,
--Tech

答:
Place all your Javascript code in seperate myScriptFile.js file. Include the script at the end of your  tag in your HTML like so:

```

Title: How to separate HTML and Javascript

Body:
I am styding JS right now.
I need to get the HTML and JS as many as possible getting seperated.
So that everything is in a HTML and a loose JS file.
How do I seperate this:

   <!DOCTYPE html>

        <title>Inzendopgave 242S2 - F.W.J.C. de Graaff

        </title>

Inzendopgave 242S2 - F.W.J.C. de Graaff

Voer uw bedragen in:

    <input type="text" id="invoer1">

Uw ingevoerde totaal:

0

When I place everything that is inside the script-tags and save that to a seperate js-file, the event-listener doesn't work anymore... Well is it possible at all to separate it?

Greetings,
--Tech

Body:
Place all your Javascript code in seperate myScriptFile.js file. Include the script at the end of your <body> tag in your HTML like so:

<html>
  <head></head>
  <body>
    <script src='/path/to/myScriptFile.js'></script>
  </body>
</html>


问:
Save Base64 String as an Excel .xls file using JavaScript in IE 7
I have been trying to find a way to save a Base64 String in IE 7 using JavaScript as a Excel .xls file. The following works fine with FireFox:

```<code>window.open ("data:application/vnd.ms-excel;base64," + bytestring, "", "width=300,height=300,resizable=1");
</code>```

where bytestring is the Base64 string. This method however does not work for IE 7.

Having done some internet research, it seems that IE 7 can't seem to handle dealing with Base64 Strings. How would I be able to achieve this? Would I have to use convert Base64 to UTF to be able to do this?

What I am trying to achieve is when the user clicks a button, the 'save as' dialog appears, allowing the user to give a filename and select destination, and then saving the Excel file.

I am limited to using IE 7. Believe me, if I had a choice to use a different browser, I definitely would.

Thanks in advance for any help!

答: This isn't possible in IE7, without a server-side proxy. Either do that, or output an HTML table and ask the user to copy and paste it into Excel.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to find a way to save a Base64 String in IE 7 using JavaScript as a Excel .xls file. The following works fine with FireFox:

window.open ("data:application/vnd.ms-excel;base64," + bytestring, "", "width=300,height=300,resizable=1");

where bytestring is the Base64 string. This method however does not work for IE 7.

Having done some internet research, it seems that IE 7 can't seem to handle dealing with Base64 Strings. How would I be able to achieve this? Would I have to use convert Base64 to UTF to be able to do this?

What I am trying to achieve is when the user clicks a button, the 'save as' dialog appears, allowing the user to give a filename and select destination, and then saving the Excel file.

I am limited to using IE 7. Believe me, if I had a choice to use a different browser, I definitely would.

Thanks in advance for any help!


问:
Table Column width must be same for two tables
There are two tables with width 600px and 5 Columns each. But, width has not been set for each column. Here, I want to make columns width must be same in both the tables. You can use CSS or jQuery. And, I dont want to fix the column width manually.

HTML Example:

```<code><table width="600" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td>hdng 1</td>
        <td>hdng 2</td>
        <td>hdng 3</td>
        <td>hdng 4</td>
        <td>hdng 5</td>
    </tr>
</table>
<table width="600" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td>content content content</td>
        <td>con</td>
        <td>content content content</td>
        <td>content content content</td>
        <td>content content content</td>
    </tr>
</table>
</code>```

Any help would be highly appreciated.

答:
You can sync the column widths by combining the tables with a tbody for each (as suggested by @Relequestual), and using  for the headers:

table {
  border-collapse: collapse;
}

table thead,
table tbody {
  border-bottom: solid;
}

table tbody th {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr> <th> ID <th> Measurement <th> Average <th> Maximum
  <tbody>
    <tr> <td> <th scope=rowgroup> Cats <td> <td>
    <tr> <td> 93 <th scope=row> Legs <td> 3.5 <td> 4
    <tr> <td> 10 <th scope=row> Tails <td> 1 <td> 1
  <tbody>
    <tr> <td> <th scope=rowgroup> English speakers <td> <td>
    <tr> <td> 32 <th scope=row> Legs <td> 2.67 <td> 4
    <tr> <td> 35 <th scope=row> Tails <td> 0.33 <td> 1
</table></code>```

Source: Example in the HTML spec itself

Body:
There are two tables with width 600px and 5 Columns each. But, width has not been set for each column. Here, I want to make columns width must be same in both the tables. You can use CSS or jQuery. And, I dont want to fix the column width manually.

HTML Example:

        hdng 1
        hdng 2
        hdng 3
        hdng 4
        hdng 5

        content content content
        con
        content content content
        content content content
        content content content

Any help would be highly appreciated.

Body:
You can sync the column widths by combining the tables with a tbody for each (as suggested by @Relequestual), and using <th scope="rowgroup"> for the headers:

table {
  border-collapse: collapse;
}

table thead,
table tbody {
  border-bottom: solid;
}

table tbody th {
  text-align: left;
}

<table>
  <thead>
    <tr> <th> ID <th> Measurement <th> Average <th> Maximum
  <tbody>
    <tr> <td> <th scope=rowgroup> Cats <td> <td>
    <tr> <td> 93 <th scope=row> Legs <td> 3.5 <td> 4
    <tr> <td> 10 <th scope=row> Tails <td> 1 <td> 1
  <tbody>
    <tr> <td> <th scope=rowgroup> English speakers <td> <td>
    <tr> <td> 32 <th scope=row> Legs <td> 2.67 <td> 4
    <tr> <td> 35 <th scope=row> Tails <td> 0.33 <td> 1
</table>

Source: Example in the HTML spec itself


问:
DIV is generating 2 times on checkout page (WOO COMMERCE)?
The problem starts when user clicks on shipping details checkbox. The div with class order-detail-summary-outer automatically generates when user checks the box.On the checkout page when user checkbox for the shipping details the order summary doubles. I have done many modifications in the in past. So i think i made mistake.On clicking shipping information checkbox. the order summary becomes double. only subtotal, shipping and total.

I am providing review-order.php file code below

```<code><?php
/**
 * Review order table
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/checkout/review-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates
 * @version 3.8.0
 */

defined( 'ABSPATH' ) || exit;
?>
<table class="shop_table woocommerce-checkout-review-order-table">
    <thead>
        <tr>
            <th class="product-name"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th>
            <th class="product-total"><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></th>
        </tr>
    </thead>
    <tbody>
        <?php
        do_action( 'woocommerce_review_order_before_cart_contents' );

        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                ?>
                <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">
                    <td class="product-name">
                        <?php echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                        <?php echo apply_filters( 'woocommerce_checkout_cart_item_quantity', ' <strong class="product-quantity">' . sprintf( '× %s', $cart_item['quantity'] ) . '</strong>', $cart_item, $cart_item_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                        <?php echo wc_get_formatted_cart_item_data( $cart_item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                    </td>
                    <td class="product-total">
                        <?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                    </td>
                </tr>
                <?php
            }
        }

        do_action( 'woocommerce_review_order_after_cart_contents' );
        ?>
    </tbody>
</table>

<div class="order-detail-summary-outer">

        <div class="cart-subtotal">
            <h2><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></h2>
            <div class="order-detail-summary-item"><?php wc_cart_totals_subtotal_html(); ?></div>
        </div>

        <?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
            <div class="cart-discount coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
                <h2><?php wc_cart_totals_coupon_label( $coupon ); ?></h2>
                <div class="order-detail-summary-item"><?php wc_cart_totals_coupon_html( $coupon ); ?></div>
            </div>
        <?php endforeach; ?>
<h2>Shipping</h2>
        <?php if ( WC()->cart->needs_shipping() && WC()->cart->show_shipping() ) : ?>

            <?php do_action( 'woocommerce_review_order_before_shipping' ); ?>

            <?php wc_cart_totals_shipping_html(); ?>

            <?php do_action( 'woocommerce_review_order_after_shipping' ); ?>

        <?php endif; ?>

        <?php foreach ( WC()->cart->get_fees() as $fee ) : ?>
            <div class="fee">
                <h2><?php echo esc_html( $fee->name ); ?></h2>
                <div class="order-detail-summary-item"><?php wc_cart_totals_fee_html( $fee ); ?></div>
            </div>
        <?php endforeach; ?>

        <?php if ( wc_tax_enabled() && ! WC()->cart->display_prices_including_tax() ) : ?>
            <?php if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) : ?>
                <?php foreach ( WC()->cart->get_tax_totals() as $code => $tax ) : // phpcs:ignore WordPress.WP.GlobalVariablesOverride.OverrideProhibited ?>
                    <div class="tax-rate tax-rate-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
                        <h2><?php echo esc_html( $tax->label ); ?></h2>
                        <div class="order-detail-summary-item"><?php echo wp_kses_post( $tax->formatted_amount ); ?></div>
                    </div>
                <?php endforeach; ?>
            <?php else : ?>
                <div class="tax-total">
                    <h2><?php echo esc_html( WC()->countries->tax_or_vat() ); ?></h2>
                    <div class="order-detail-summary-item"><?php wc_cart_totals_taxes_total_html(); ?></div>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <?php do_action( 'woocommerce_review_order_before_order_total' ); ?>

        <div class="order-total">
            <h2><?php esc_html_e( 'Total', 'woocommerce' ); ?></h2>
            <div class="order-detail-summary-item"><?php wc_cart_totals_order_total_html(); ?></div>
        </div>

        <?php do_action( 'woocommerce_review_order_after_order_total' ); ?>

</div>
</code>```

答:
At a quick glance. It looks to be how you modified the existing HTML structure. WooCommerce uses a lot of ajax calls to update that information (cart totals, checkout totals). If you have modified that structure and it doesn't know where to send it back/replace it, it will inject a new section.

As LsKIT stated, its a JS issue but more so because of the modified HTML.

Body:
The problem starts when user clicks on shipping details checkbox. The div with class order-detail-summary-outer automatically generates when user checks the box.On the checkout page when user checkbox for the shipping details the order summary doubles. I have done many modifications in the in past. So i think i made mistake.On clicking shipping information checkbox. the order summary becomes double. only subtotal, shipping and total.

I am providing review-order.php file code below

<?php
/**
 * Review order table
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/checkout/review-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates
 * @version 3.8.0
 */

defined( 'ABSPATH' ) || exit;
?>

            <?php esc_html_e( 'Product', 'woocommerce' ); ?>
            <?php esc_html_e( 'Subtotal', 'woocommerce' ); ?>

        <?php
        do_action( 'woocommerce_review_order_before_cart_contents' );

        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                ?>
                <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">

                        <?php echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                        <?php echo apply_filters( 'woocommerce_checkout_cart_item_quantity', ' ' . sprintf( '× %s', $cart_item['quantity'] ) . '', $cart_item, $cart_item_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                        <?php echo wc_get_formatted_cart_item_data( $cart_item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

                        <?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

                <?php
            }
        }

        do_action( 'woocommerce_review_order_after_cart_contents' );
        ?>

<?php esc_html_e( 'Subtotal', 'woocommerce' ); ?>

<?php wc_cart_totals_subtotal_html(); ?>

        <?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
            <div class="cart-discount coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">

<?php wc_cart_totals_coupon_label( $coupon ); ?>

<?php wc_cart_totals_coupon_html( $coupon ); ?>

        <?php endforeach; ?>

Shipping

        <?php if ( WC()->cart->needs_shipping() && WC()->cart->show_shipping() ) : ?>

            <?php do_action( 'woocommerce_review_order_before_shipping' ); ?>

            <?php wc_cart_totals_shipping_html(); ?>

            <?php do_action( 'woocommerce_review_order_after_shipping' ); ?>

        <?php endif; ?>

        <?php foreach ( WC()->cart->get_fees() as $fee ) : ?>

<?php echo esc_html( $fee->name ); ?>

<?php wc_cart_totals_fee_html( $fee ); ?>

        <?php endforeach; ?>

        <?php if ( wc_tax_enabled() && ! WC()->cart->display_prices_including_tax() ) : ?>
            <?php if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) : ?>
                <?php foreach ( WC()->cart->get_tax_totals() as $code => $tax ) : // phpcs:ignore WordPress.WP.GlobalVariablesOverride.OverrideProhibited ?>
                    <div class="tax-rate tax-rate-<?php echo esc_attr( sanitize_title( $code ) ); ?>">

<?php echo esc_html( $tax->label ); ?>

<?php echo wp_kses_post( $tax->formatted_amount ); ?>

                <?php endforeach; ?>
            <?php else : ?>

<?php echo esc_html( WC()->countries->tax_or_vat() ); ?>

<?php wc_cart_totals_taxes_total_html(); ?>

            <?php endif; ?>
        <?php endif; ?>

        <?php do_action( 'woocommerce_review_order_before_order_total' ); ?>

<?php esc_html_e( 'Total', 'woocommerce' ); ?>

<?php wc_cart_totals_order_total_html(); ?>

        <?php do_action( 'woocommerce_review_order_after_order_total' ); ?>


问:
How to detect dynamically changed input
I am working on the below snippet. Why am I not able to detect the input change using this?

```<code>$("#fname").on("change", function () {
   console.log("The text has been changed.");
});
</code>```

$("button").on("click", function () {
    $("#fname").text('Alex');
    $("#fname").val('Alex');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" id="fname" name="fname"><br><br>
<button type="button">Click Me!</button></code>```

答:
This only gets triggered if the user sets the value. You can trigger it manually.</p>

```<code>$("#fname").val('Alex').change();
</code>```

Title: How to detect dynamically changed input

Body:
I am working on the below snippet. Why am I not able to detect the input change using this?

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});

$("button").on("click", function () {
    $("#fname").text('Alex');
    $("#fname").val('Alex');
});

$("#fname").on("change", function () {
   console.log("The text has been changed.");
});

 <input type="text" id="fname" name="fname">

<button type="button">Click Me!</button>

Body:
This only gets triggered if the user sets the value. You can trigger it manually.

$("#fname").val('Alex').change();


问:
How i can do a *ngFor in a array of objects that i don't know the name property?
I have this array called dadosRelatorio that i need to iterate in my template, this array i get in a http request:

```<code>[{"id": 1,
  "name": "a",
  "class":[{
     "Inglês":[{
        "id": 1,
        "code": "teste"
     },
     {
        "id": 2,
        "code": "teste 2"
     }],
     "Espanhol":[{
        "id": 1,
        "code": "a"
     }]
   }]
}]
</code>```

How i can iterate the objects inside class if they have different names property? Sometimes the name can be "Inglês" and sometimes can be "Espanhol" and other names...

When i know the name of the property i do this way:

```<code><div *ngFor="let aluno of dadosRelatorio" class="div-aluno">
       <span>Aluno: {{ aluno.name }}</span>
       <div *ngFor="let classe of aluno.class">
          <div *ngFor="let idioma of classe. ???>

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

But how i can iterate the object inside class?

答:
You may iterate using the keyvalue pipe as shown below:

```<code><div *ngFor="let aluno of dadosRelatorio" class="div-aluno">
    <span>Aluno: {{ aluno.name }}</span>
    <div *ngFor="let classe of aluno.class | keyvalue">
        <div> {{classe.key}}</div>
        <div *ngFor="let type of classe.value | keyvalue">
            {{type.key}}
            <div *ngFor="let data of type.value | keyvalue">
                {{data.value.id }}
                {{data.value.code }}
            </div>
        </div>
    </div>
</div>
</code>```

Body:
I have this array called dadosRelatorio that i need to iterate in my template, this array i get in a http request:

[{"id": 1,
  "name": "a",
  "class":[{
     "Inglês":[{
        "id": 1,
        "code": "teste"
     },
     {
        "id": 2,
        "code": "teste 2"
     }],
     "Espanhol":[{
        "id": 1,
        "code": "a"
     }]
   }]
}]

How i can iterate the objects inside class if they have different names property? Sometimes the name can be "Inglês" and sometimes can be "Espanhol" and other names...

When i know the name of the property i do this way:

       Aluno: {{ aluno.name }}

But how i can iterate the object inside class?

Body:
You may iterate using the keyvalue pipe as shown below:

<div *ngFor="let aluno of dadosRelatorio" class="div-aluno">
    <span>Aluno: {{ aluno.name }}</span>
    <div *ngFor="let classe of aluno.class | keyvalue">
        <div> {{classe.key}}</div>
        <div *ngFor="let type of classe.value | keyvalue">
            {{type.key}}
            <div *ngFor="let data of type.value | keyvalue">
                {{data.value.id }}
                {{data.value.code }}
            </div>
        </div>
    </div>
</div>


问:
Correct use of fun.data with stat_summary in ggplot2?
From ?stat_summary.

fun.data : Complete summary function. Should take data frame as input
  and return data frame as output

I'm having trouble understanding this.  It doesn't seem like my summary function so.summary is being passed a data frame at all!

Code:

```<code>set.seed(0)
so.example <- data.frame(
  sampleID=rep(1:15)
  , sales=runif(15, 0, 1)*1000
  , revenue=runif(15, 0, 1)*10000
)

so.summary <- function(z) {
  print(z)
  data.frame(sales=median(z$sales), revenue=median(z$revenue))
}

ggplot(
  so.example
  , aes(x=sales, y=revenue)
  ) + geom_point() + stat_summary(fun.data=so.summary, geom='point', color='red')
</code>```

Output:

```<code>[1] 2672.207
Error in z$sales : $ operator is invalid for atomic vectors
</code>```

答:
Let's say you really want to use stat summary to plot that summary point. As logworthy noted, fun.data will receive a y vector for every unique x value. More broadly, it splits up the aesthetics data.frame for each unique x value (we'll use this fact later).But, if you move around your aesthetics, you can let stat_summary see the entire revenue vector.

```<code>ggplot(so.example) +
  geom_point(aes(x=sales, y=revenue)) +
  stat_summary(aes(x= median(sales), y= revenue), fun.y= median, geom= 'point', color= 'red')
</code>```

Now, stat_summary can 'see' only 1 x aesthetic and the entire y vector in the fun.y input.

If that's not fun enough, you can trick fun.data into seeing other vectors of your frame, for example, let's say you needed a weighted mean instead of a median.

```<code>set.seed(0)
so.example <- data.frame(
  sampleID=rep(1:15)
  , sales=runif(15, 0, 1)*1000
  , revenue=runif(15, 0, 1)*10000
  , weight= runif(15, 0, 1)
)

so.mean.weight <- function(x, wt){ sum(x*wt)/sum(wt) }
</code>```

I created a simple weight function, but, could easily grab weighted.mean from stats (more importantly, the function is clearly arbitrary as long as it returns 1 value for the inputs).

The trick for fun.data to see other vectors in the data.frame is to grab extra aesthetics from the parent.frame() while in the function. This is pretty hacky as you'll get warning messages. Let's take a look at the new stat_summary call:

```<code>stat_summary(
    aes(x= so.mean.weight(sales, weight), y= revenue, wt= weight)
    , fun.data= so.summary
    , geom= 'point'
    , color= 'darkgreen'
    , size= 2
    )
</code>```

Notice the input in the aes, wt= weight. In geom_point, there is no wt aesthetic (you want to choose something that you know is not an aesthetic name (foo/bar would have done just as well), so, you'll get a nice warning message telling you it will be ignored. It will be ignored, but not removed/deleted.

With that in mind, let's take a look inside the new so.summary function:

```<code>so.summary <- function(z) {
  # Grab aesthetic DF
  aesDF <- parent.frame()$df
  print(names(aesDF)) # returns input aesthetic vectors: "x", "y", "group", and "wt"
  pnt <- data.frame(y= so.mean.weight(z, aesDF$wt ) )
  print(pnt)
  pnt
}
</code>```

You can see the call to the parent.frame()$df grants you access to the aesthetic vectors to use in your calculations.

Body:
From ?stat_summary.

fun.data : Complete summary function. Should take data frame as input
  and return data frame as output

I'm having trouble understanding this.  It doesn't seem like my summary function so.summary is being passed a data frame at all!

Code:

set.seed(0)
so.example <- data.frame(
  sampleID=rep(1:15)
  , sales=runif(15, 0, 1)*1000
  , revenue=runif(15, 0, 1)*10000
)

so.summary <- function(z) {
  print(z)
  data.frame(sales=median(z$sales), revenue=median(z$revenue))
}

ggplot(
  so.example
  , aes(x=sales, y=revenue)
  ) + geom_point() + stat_summary(fun.data=so.summary, geom='point', color='red')

Output:

[1] 2672.207
Error in z$sales : $ operator is invalid for atomic vectors

Body:
Let's say you really want to use stat summary to plot that summary point. As logworthy noted, fun.data will receive a y vector for every unique x value. More broadly, it splits up the aesthetics data.frame for each unique x value (we'll use this fact later).But, if you move around your aesthetics, you can let stat_summary see the entire revenue vector.

ggplot(so.example) +
  geom_point(aes(x=sales, y=revenue)) +
  stat_summary(aes(x= median(sales), y= revenue), fun.y= median, geom= 'point', color= 'red')

Now, stat_summary can 'see' only 1 x aesthetic and the entire y vector in the fun.y input.

If that's not fun enough, you can trick fun.data into seeing other vectors of your frame, for example, let's say you needed a weighted mean instead of a median.

set.seed(0)
so.example <- data.frame(
  sampleID=rep(1:15)
  , sales=runif(15, 0, 1)*1000
  , revenue=runif(15, 0, 1)*10000
  , weight= runif(15, 0, 1)
)

so.mean.weight <- function(x, wt){ sum(x*wt)/sum(wt) }

I created a simple weight function, but, could easily grab weighted.mean from stats (more importantly, the function is clearly arbitrary as long as it returns 1 value for the inputs).

The trick for fun.data to see other vectors in the data.frame is to grab extra aesthetics from the parent.frame() while in the function. This is pretty hacky as you'll get warning messages. Let's take a look at the new stat_summary call:

stat_summary(
    aes(x= so.mean.weight(sales, weight), y= revenue, wt= weight)
    , fun.data= so.summary
    , geom= 'point'
    , color= 'darkgreen'
    , size= 2
    )

Notice the input in the aes, wt= weight. In geom_point, there is no wt aesthetic (you want to choose something that you know is not an aesthetic name (foo/bar would have done just as well), so, you'll get a nice warning message telling you it will be ignored. It will be ignored, but not removed/deleted.

With that in mind, let's take a look inside the new so.summary function:

so.summary <- function(z) {
  # Grab aesthetic DF
  aesDF <- parent.frame()$df
  print(names(aesDF)) # returns input aesthetic vectors: "x", "y", "group", and "wt"
  pnt <- data.frame(y= so.mean.weight(z, aesDF$wt ) )
  print(pnt)
  pnt
}

You can see the call to the parent.frame()$df grants you access to the aesthetic vectors to use in your calculations.


问:
Is there a way to convert list of string formatted dictionary to a dataframe in Python?
I am practicing how to use beautifulsoup and currently in a pickle as I can't convert the results to a dataframe. Hope to get your help.

In this example, the page I want to scrape can be obtained using the following:

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd

page = requests.get("https://store.moncler.com/en-ca/women/autumn-winter/view-all-outerwear?tp=72010&ds_rl=1243188&gclid=EAIaIQobChMIpfDj9bjP5wIVlJOzCh0-9ghJEAAYASAAEgLuSfD_BwE&gclsrc=aw.ds", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')
</code>```

I have managed to isolate to the product section using the following code

```<code>test_class = []

for section_tag in soup.find_all('section', class_='search__products__shelf search__products__shelf--moncler'):
    for test in section_tag.find_all('article'):
        test_class.append(test.get('data-ytos-track-product-data'))
</code>```

The result of this is a list of string-formatted dictionary which looks like the following:

['{"product_position":0,"product_title":"TREPORT","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676843","product_micro_category":"Outerwear","product_micro_category_id":"3074457345616676843","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2530.0,"product_price_tf":"0","product_discountedPrice_tf":"2126.05","product_id":"1890828705323513","product_variant_id":"1890828705323514","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"1446","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',
  '{"product_position":1,"product_title":"RIMAC","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676854","product_micro_category":"Bomber
  Jacket","product_micro_category_id":"3074457345616676854","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2340.0,"product_price_tf":"0","product_discountedPrice_tf":"1966.39","product_id":"5549023491788128","product_variant_id":"5549023491788129","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"4715","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',

My question is how to convert the result to a pandas dataframe from a list of string formatted dictionary like that?

I have tried to use the code below to start with

```<code>import ast
ast.literal_eval(test_class[1])
</code>```

but to no avail (it gives me below error code).

ValueError: malformed node or string: <_ast.Name object at
  0x000001985A976748>

The end result should store each key of the dictionary into columns in a Dataframe (ie. 'product_position','product_title','product_brand',etc)

Any help / guidance would be much appreciated.

Thanks.

答:
Looks like the question really is about how to parse a string, not how to do something with pandas.

The list you have seem to contain simply valid json strings. You can convert them to python dict's using json.loads() from the standard lib. Of course if some strings are malformed that's another story, you'll have to google how to parse malformed jsons.

After getting a list of python dicts turning them into a DataFrame is trivial.

Body:
I am practicing how to use beautifulsoup and currently in a pickle as I can't convert the results to a dataframe. Hope to get your help.

In this example, the page I want to scrape can be obtained using the following:

from bs4 import BeautifulSoup
import requests
import pandas as pd

page = requests.get("https://store.moncler.com/en-ca/women/autumn-winter/view-all-outerwear?tp=72010&ds_rl=1243188&gclid=EAIaIQobChMIpfDj9bjP5wIVlJOzCh0-9ghJEAAYASAAEgLuSfD_BwE&gclsrc=aw.ds", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

I have managed to isolate to the product section using the following code

test_class = []

for section_tag in soup.find_all('section', class_='search__products__shelf search__products__shelf--moncler'):
    for test in section_tag.find_all('article'):
        test_class.append(test.get('data-ytos-track-product-data'))

The result of this is a list of string-formatted dictionary which looks like the following:

['{"product_position":0,"product_title":"TREPORT","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676843","product_micro_category":"Outerwear","product_micro_category_id":"3074457345616676843","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2530.0,"product_price_tf":"0","product_discountedPrice_tf":"2126.05","product_id":"1890828705323513","product_variant_id":"1890828705323514","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"1446","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',
  '{"product_position":1,"product_title":"RIMAC","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676854","product_micro_category":"Bomber
  Jacket","product_micro_category_id":"3074457345616676854","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2340.0,"product_price_tf":"0","product_discountedPrice_tf":"1966.39","product_id":"5549023491788128","product_variant_id":"5549023491788129","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"4715","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',

My question is how to convert the result to a pandas dataframe from a list of string formatted dictionary like that?

I have tried to use the code below to start with

import ast
ast.literal_eval(test_class[1])

but to no avail (it gives me below error code).

ValueError: malformed node or string: <_ast.Name object at
  0x000001985A976748>

The end result should store each key of the dictionary into columns in a Dataframe (ie. 'product_position','product_title','product_brand',etc)

Any help / guidance would be much appreciated.

Thanks.


问:
UIApplicationDelegate question
In my AppDelegate I have a reference to an NSObject like this:

```<code>@interface MyAppDelegate : NSObject <UIApplicationDelegate>
{
    MyObjectManager * myObjectManager;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) MyObjectManager * myObjectManager;
</code>```

I want to access this from my UIViewController, so I do this:

```<code>MyAppDelegate * appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
MyObjectManager * myObjectManager = appDelegate.myObjectManager;
maMyArray = [[NSMutableArray alloc] init];

[[appDelegate myObjectManager] findMyStuff:5 foundArray:maMyArray];
//[myObjectManager findMyStuff:5 foundArray:maMyArray];
</code>```

However, I think I am not understanding the syntax in Objective C correctly because I throw an exception, EXC_BAD_ACCESS.   When I look at the values, they seem correct.

Can someone please explain what I am doing wrong?

Thanks

答:
You have to initialize myObjectManager somwhere:

```<code>myObjectManager = [[MyObjectManager alloc] init];
</code>```

The best place is probably in the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method.

Don't forget to release it in the dealloc.

Title: UIApplicationDelegate question

Body:
In my AppDelegate I have a reference to an NSObject like this:

@interface MyAppDelegate : NSObject <UIApplicationDelegate>
{
    MyObjectManager * myObjectManager;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) MyObjectManager * myObjectManager;

I want to access this from my UIViewController, so I do this:

MyAppDelegate * appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
MyObjectManager * myObjectManager = appDelegate.myObjectManager;
maMyArray = [[NSMutableArray alloc] init];

[[appDelegate myObjectManager] findMyStuff:5 foundArray:maMyArray];
//[myObjectManager findMyStuff:5 foundArray:maMyArray];

However, I think I am not understanding the syntax in Objective C correctly because I throw an exception, EXC_BAD_ACCESS.   When I look at the values, they seem correct.

Can someone please explain what I am doing wrong?

Thanks

Body:
You have to initialize myObjectManager somwhere:

myObjectManager = [[MyObjectManager alloc] init];

The best place is probably in the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method.

Don't forget to release it in the dealloc.


问:
.py to .exe file conversion issue
I'm trying to convert a simple python code (any sample code) into an executable file but on opening the application all I can see is a blank black screen.

I am using:

Python 3.7

PyInstaller 3.6

One file output

I am able to convert the file to .exe using auto-py-to-exe but I don't see any output when I try to run the application.

答:
Pyinstaller is much easier than other things, you need to install with pip:

pip install pyinstaller

And then go to the path of your Python file and then:

pyinstaller -w -F my_file.py

Title: .py to .exe file conversion issue


问:
"Scrollable content size is ambiguous to "ScrollView"
I am a little stuck with the ScrollView in Swift and Xcode 11.

My goal is a simple ScrollView with Labels and Textfields. Each label describes what the textfields are used for. For example there is a Label "Name", so you have to enter your name in the textfield under the label. For this I need a ScrollView because the App I am coding requires a few more information. When I am trying to put this in a ScrollView I am constantly  getting the following error:
"Scrollable content size is ambiguous to ScrollView".

In order to find help I searched the internet and for example found this question: UIScrollView Scrollable Content Size Ambiguity.
Unfortunatly it didn't solve my problem. So I decided to create a small test project with the following:
- I created a project as a Single View Application
- I added a ScrollView to the ViewController
- I clicked on the constrains-Button at the canvas
- I selected 0,0,0,0 for leading/top/trailing/bottom.
- I clicked on "add 4 Constrains
- Now the warning appeared. Also the ScrollView was not resized to the ViewController... I don't know why.
- I added a UIView inside the ScrollView and set the same constrains, this time according to the ScrollView.
- The UIView (Content view) got an extra constrain: Equal width with the root view
- Now I added two Buttons, one with the text "Hello" and the other one with "world" on it.
- The "hello"-Button received the following constrains: 16 to leading, trailing and top, as well as a fixed height of 30.
- The "world"-Button got the following constrains: 16 to bottom, leading, trailing and over a 1000 so you can scroll through the ScrollView.

After all these steps the error is still there and if I run the app the "hello"-Button is at the top of the screen and the "world"-Button is at the bottom and I can't scroll.

Can maybe anyone help me fixing this issue. I am looking forward to every answer! Thank you for your help in advance!

答:
Here is the trick that worked for me:

Add a ScrollView to your wished ViewController.

Select it in the Outline and open its size inspector.

Uncheck there the option "Content Layout Guides".

Now set leading/top/trailing and bottom constrains to 0 of the ScrollView.

Add in a UIView and constrain its leading/top/trailing and bottom also to 0.

Add an equal width constrain to the UIView. (The width needs to be equal the width of the view from the ViewController, with this way you are disabeling horizontal scrolling).

The warning will disappear if every element inside the UIView is chained vertically. This means, that the top element has a constrain to the top of the view and to the element under it and so on. The last element needs a constrain to the bottom of the view.

If you followed this steps you should be fine with ScrollViews. This way you also can add as many content as you want to the bottom and the ScrollView will extend dynamically.

I hope I explained it well enough.


答:
Assuming that a space character is the column separator, you can load them into a list of lists:

data = []
with open(datafile,'r') as file:
    for line in file:
       # splits into list based on white space separator
       data.append(line.split)
```

<p>Taking part of your example: to compare the values in column 2 with column 5 you could do:</p>

<pre class="lang-py prettyprint-override"><code>for line in data:
    if line[1] == line[4]:
       print("it's a match!")
</code>```

If you have a header you want to ignore, just skip the first line when you open the file:

with open(datafile,'r') as file:
    # do nothing with this line
    header = f.readline()
   ...
```

Title: How do I plot data from multiple CSVs each with different column numbers

Body:
The file has no header but I would need to select say columns, 5,9, 13, 17 etc against column 2 (time). How can this be achieved in the case where the headers are present as well. Edit : Each file contains data for one day, the time format is GPS time which is the YR,Day of YR and Sec since midnight. How can i plot for say 1=30 January 2019?
Here is one code i tried

    import numpy as np
    import glob,os
    import matplotlib.pyplot as plt

    files = glob.glob('*.s4')
    #print(files)
    for file in files:
        f=np.loadtxt(file,skiprows=3)
        #print(file[0:9].upper())
        for i in range (5,50,4):
            t=f[:,2]/3600.;s4=f[:,i]
            pos= np.where (t)[0]
            pos1=np.where(s4[pos]<0.15)[0];s4[pos1]='nan'
            plt.scatter(t,s4)
            #print(len(s4))
            plt.xticks(np.arange(0, 26, 2))
            #plt.title(str(i))
    plt.show()

The problem is that particular code only plots for one day at a time.
Here is a sample of the data.

19 001    45 11  1 0.07 214.9 37.5  8 0.08 314.5 34.2 10 0.14 102.6 14.3 11 0.07 241.2 49.6 14 0.07 152.0 50.0 18 0.05 212.7 68.0 22 0.08 226.1 33.7 27 0.06 346.0 22.0 31 0.04  63.5 47.7 32 0.06 144.3 30.4 138 0.09 282.0 17.8
19 001   105 11  1 0.05 214.9 37.9  8 0.07 314.9 33.8 10 0.24 102.2 14.1 11 0.07 241.7 49.9 14 0.06 151.9 49.6 18 0.06 213.0 68.4 22 0.12 225.7 34.0 27 0.06 346.2 21.7 31 0.04  64.1 47.9 32 0.06 144.2 30.0 138 0.09 282.0 17.8
19 001   165 11  1 0.06 214.9 38.4  8 0.11 315.3 33.5 10 0.12 101.8 13.9 11 0.06 242.3 50.1 14 0.06 151.8 49.1 18 0.05 213.4 68.9 22 0.07 225.2 34.2 27 0.11 346.5 21.3 31 0.04  64.8 48.2 32 0.10 144.0 29.6 138 0.09 282.0 17.8
19 001   225 11  1 0.06 214.9 38.8  8 0.06 315.8 33.2 10 0.10 101.4 13.7 11 0.06 242.8 50.4 14 0.05 151.7 48.6 18 0.04 213.7 69.4 22 0.06 224.8 34.4 27 0.08 346.8 20.9 31 0.05  65.5 48.4 32 0.09 143.9 29.2 138 0.09 282.0 17.8
19 001   285 11  1 0.06 215.0 39.2  8 0.11 316.2 32.9 10 0.14 100.9 13.6 11 0.05 243.4 50.6 14 0.06 151.6 48.2 18 0.06 214.1 69.8 22 0.08 224.4 34.7 27 0.07 347.0 20.5 31 0.06  66.1 48.6 32 0.09 143.7 28.8 138 0.09 282.0 17.8
19 001   345 11  1 0.06 215.0 39.7  8 0.08 316.6 32.5 10 0.10 100.5 13.4 11 0.04 244.0 50.9 14 0.06 151.5 47.7 18 0.04 214.6 70.3 22 0.07 223.9 34.9 27 0.08 347.3 20.2 31 0.07  66.8 48.9 32 0.08 143.6 28.4 138 0.09 282.0 17.8
19 001   405 11  1 0.06 215.1 40.1  8 0.07 317.0 32.2 10 0.13 100.1 13.2 11 0.05 244.6 51.1 14 0.08 151.4 47.3 18 0.05 215.0 70.8 22 0.07 223.5 35.1 27 0.12 347.5 19.8 31 0.08  67.5 49.1 32 0.12 143.4 28.0 138 0.09 282.0 17.8
19 001   465 11  1 0.06 215.1 40.5  8 0.12 317.4 31.9 10 0.10  99.7 13.0 11 0.08 245.2 51.4 14 0.05 151.3 46.8 18 0.06 215.5 71.2 22 0.06 223.0 35.4 27 0.12 347.8 19.4 31 0.03  68.2 49.3 32 0.18 143.3 27.7 138 0.09 282.0 17.8
19 001   525 11  1 0.09 215.2 40.9  8 0.12 317.9 31.5 10 0.11  99.3 12.8 11 0.04 245.8 51.6 14 0.15 151.2 46.4 18 0.06 216.0 71.7 22 0.06 222.6 35.6 27 0.08 348.0 19.1 31 0.05  68.9 49.5 32 0.08 143.1 27.3 138 0.09 282.0 17.8
19 001   585 11  1 0.07 215.2 41.4  8 0.09 318.3 31.2 10 0.12  98.9 12.6 11 0.04 246.5 51.8 14 0.06 151.1 45.9 18 0.05 216.5 72.2 22 0.06 222.1 35.8 27 0.08 348.3 18.7 31 0.07  69.6 49.7 32 0.11 143.0 26.9 138 0.09 282.0 17.8

Body:
Assuming that a space character is the column separator, you can load them into a list of lists:

data = []
with open(datafile,'r') as file:
    for line in file:
       # splits into list based on white space separator
       data.append(line.split)

Taking part of your example: to compare the values in column 2 with column 5 you could do:

for line in data:
    if line[1] == line[4]:
       print("it's a match!")

If you have a header you want to ignore, just skip the first line when you open the file:

with open(datafile,'r') as file:
    # do nothing with this line
    header = f.readline()
   ...


问:
How to toggle div's on and of on a daily basis?
I am currently working on a project, my employer wants to change his daily offer every day in a week, now I have tried to get my 7 div's in js and turn them on and off whit if statements ex:

```<code>var day = new Date().get Day()
if(day == 5){
div.style.display = "block";
//all the other div's would be display none//
</code>```

I tried searching for a similar problem online but there is no solution.
I hope I clearly explained the problem. keep in mind that I am currently a beginner in js and i would love to hear out a more simpler solution.

答:
I would give all your divs unique IDs and the same class name.

```<code><div id="offer0" class="offer">Content</div>
<div id="offer1" class="offer">Content</div>
<div id="offer2" class="offer">Content</div>
<div id="offer3" class="offer">Content</div>
<div id="offer4" class="offer">Content</div>
<div id="offer5" class="offer">Content</div>
<div id="offer6" class="offer">Content</div>
</code>```

When you do you check for what day it is, set display of every div with that class name to be 'none', then get the div you want by ID and change it back to block.

```<code>// gets day of the week, Sunday = 0
var day = new Date().getDay()

// gets a collection of divs with the class name "offer"
var divs = document.getElementsByClassName('offer')
var len = divs.len

// loop through the divs we grabbed above and set their display to "none"
for (i = 0; i < len; i++) {
    divs[i].style.display = 'none';
}

// get the element by it's ID using the day var we stored above
document.getElementById('offer' + day).style.display = 'block'
</code>```

Body:
I am currently working on a project, my employer wants to change his daily offer every day in a week, now I have tried to get my 7 div's in js and turn them on and off whit if statements ex:

var day = new Date().get Day()
if(day == 5){
div.style.display = "block";
//all the other div's would be display none//

I tried searching for a similar problem online but there is no solution.
I hope I clearly explained the problem. keep in mind that I am currently a beginner in js and i would love to hear out a more simpler solution.

Body:
I would give all your divs unique IDs and the same class name.

<div id="offer0" class="offer">Content</div>
<div id="offer1" class="offer">Content</div>
<div id="offer2" class="offer">Content</div>
<div id="offer3" class="offer">Content</div>
<div id="offer4" class="offer">Content</div>
<div id="offer5" class="offer">Content</div>
<div id="offer6" class="offer">Content</div>

When you do you check for what day it is, set display of every div with that class name to be 'none', then get the div you want by ID and change it back to block.

// gets day of the week, Sunday = 0
var day = new Date().getDay()

// gets a collection of divs with the class name "offer"
var divs = document.getElementsByClassName('offer')
var len = divs.len

// loop through the divs we grabbed above and set their display to "none"
for (i = 0; i < len; i++) {
    divs[i].style.display = 'none';
}

// get the element by it's ID using the day var we stored above
document.getElementById('offer' + day).style.display = 'block'


问:
Adding repackage goal leads to "Error creating bean with name 'entityManagerFactory'"
I'm working on dockerizing a Spring Boot app and I'm running into some issues:

Running mvn spring-boot:run works just fine.

Before adding the repackage goal, I get no main manifest attribute, in target/app.war when running java -jar target/app.war

After adding the repackage goal, I get an error with creating entityManagerFactory when running java -jar target/app.war

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
...
***************************
APPLICATION FAILED TO START
***************************

Description:

Field profileRepository in com.bnlucas.app.util.PostTransactionUtil required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.
</code>```

I don't know much about the inner workings of Maven, and can't figure out what could be happening. I had an issue with javassist dependency issues, and tried excluding it and got a little further with what all was happening.

```<code><plugin>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-maven-plugin</artifactId>
  <version>${liquibase.version}</version>
  <dependencies>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.21.0-GA</version>
    </dependency>
    <dependency>
      <groupId>org.liquibase.ext</groupId>
      <artifactId>liquibase-hibernate4</artifactId>
      <version>${liquibase-hibernate4.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>${spring.boot.version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.javassist</groupId>
          <artifactId>javassist</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  ...
</plugin>
</code>```

Trying things I've found across the site, I've changed the the entity manager ref:

```<code>@EnableJpaRepositories(
  basePackages = {"com.bnlucas.app.repository"},
  entityManagerFactoryRef = "entityManagerF"
)
</code>```

and just got

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field profileRepository in com.bnlucas.app.util.PostTransactionUtil required a bean named 'entityManagerF' that could not be found.

Action:

Consider defining a bean named 'entityManagerF' in your configuration.
</code>```

I've also tried defining the bean with LocalContainerEntityManagerFactoryBean and still nothing.

```<code>@Bean
public EntityManagerFactory entityManagerFactory(DataSourceProperties dataSourceProperties) {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.bnlucas.app.repository");
    factory.setDataSource(dataSource(dataSourceProperties));
    factory.afterPropertiesSet();
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
    return factory.getObject();
}
</code>```

What is mvn spring-boot:run doing that's different than running mvn package spring-boot:repackage? How is the entity manager defined with the first and fails with the latter?

DatabaseConfiguration: https://gist.github.com/bnlucas/3e9db7d67aa52e43e8013a0cb81b40b3#file-databaseconfiguration-java

pom: https://gist.github.com/bnlucas/3e9db7d67aa52e43e8013a0cb81b40b3#file-pom-xml

答:
After troubleshooting and narrowing things down, I found the issue. It was a filtering flag in the maven war plugin.

Removing the <filtering /> here got everything up and running

<resource>
  <directory>.</directory>
  <targetPath>META-INF</targetPath>
  <filtering>true</filtering>
</resource>
```

<pre class="lang-xml prettyprint-override"><code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.4</version>
  <configuration>
    <webResources>
      <resource>
        <!-- this is relative to the pom.xml directory -->
        <directory>config</directory>
        <includes>
          <include>build-${project.artifactId}.properties</include>
        </includes>
        <!-- override the destination directory for this resource -->
        <targetPath>META-INF</targetPath>
        <!-- enable filtering -->
        <filtering>true</filtering>
      </resource>
      <resource>
        <!-- this is relative to the pom.xml directory -->
        <directory>config</directory>
        <includes>
          <include>build-${project.artifactId}.properties</include>
        </includes>
        <!-- override the destination directory for this resource -->
        <targetPath>WEB-INF/classes</targetPath>
        <!-- enable filtering -->
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>.</directory>
        <targetPath>META-INF</targetPath>
      </resource>
    </webResources>
  </configuration>
</plugin>
</code>```

Body:
I'm working on dockerizing a Spring Boot app and I'm running into some issues:

Running mvn spring-boot:run works just fine.

Before adding the repackage goal, I get no main manifest attribute, in target/app.war when running java -jar target/app.war

After adding the repackage goal, I get an error with creating entityManagerFactory when running java -jar target/app.war

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.archive.spi.ArchiveException: Could not build ClassFile
...
***************************
APPLICATION FAILED TO START
***************************

Description:

Field profileRepository in com.bnlucas.app.util.PostTransactionUtil required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

I don't know much about the inner workings of Maven, and can't figure out what could be happening. I had an issue with javassist dependency issues, and tried excluding it and got a little further with what all was happening.

<plugin>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-maven-plugin</artifactId>
  <version>${liquibase.version}</version>
  <dependencies>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.21.0-GA</version>
    </dependency>
    <dependency>
      <groupId>org.liquibase.ext</groupId>
      <artifactId>liquibase-hibernate4</artifactId>
      <version>${liquibase-hibernate4.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>${spring.boot.version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.javassist</groupId>
          <artifactId>javassist</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  ...
</plugin>

Trying things I've found across the site, I've changed the the entity manager ref:

@EnableJpaRepositories(
  basePackages = {"com.bnlucas.app.repository"},
  entityManagerFactoryRef = "entityManagerF"
)

and just got

***************************
APPLICATION FAILED TO START
***************************

Description:

Field profileRepository in com.bnlucas.app.util.PostTransactionUtil required a bean named 'entityManagerF' that could not be found.

Action:

Consider defining a bean named 'entityManagerF' in your configuration.

I've also tried defining the bean with LocalContainerEntityManagerFactoryBean and still nothing.

@Bean
public EntityManagerFactory entityManagerFactory(DataSourceProperties dataSourceProperties) {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.bnlucas.app.repository");
    factory.setDataSource(dataSource(dataSourceProperties));
    factory.afterPropertiesSet();
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
    return factory.getObject();
}

What is mvn spring-boot:run doing that's different than running mvn package spring-boot:repackage? How is the entity manager defined with the first and fails with the latter?

DatabaseConfiguration: https://gist.github.com/bnlucas/3e9db7d67aa52e43e8013a0cb81b40b3#file-databaseconfiguration-java

pom: https://gist.github.com/bnlucas/3e9db7d67aa52e43e8013a0cb81b40b3#file-pom-xml

Body:
After troubleshooting and narrowing things down, I found the issue. It was a filtering flag in the maven war plugin.

Removing the <filtering /> here got everything up and running

<resource>
  <directory>.</directory>
  <targetPath>META-INF</targetPath>
  <filtering>true</filtering>
</resource>

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.4</version>
  <configuration>
    <webResources>
      <resource>
        <!-- this is relative to the pom.xml directory -->
        <directory>config</directory>
        <includes>
          <include>build-${project.artifactId}.properties</include>
        </includes>
        <!-- override the destination directory for this resource -->
        <targetPath>META-INF</targetPath>
        <!-- enable filtering -->
        <filtering>true</filtering>
      </resource>
      <resource>
        <!-- this is relative to the pom.xml directory -->
        <directory>config</directory>
        <includes>
          <include>build-${project.artifactId}.properties</include>
        </includes>
        <!-- override the destination directory for this resource -->
        <targetPath>WEB-INF/classes</targetPath>
        <!-- enable filtering -->
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>.</directory>
        <targetPath>META-INF</targetPath>
      </resource>
    </webResources>
  </configuration>
</plugin>


问:
Pattern matching using regex for messy file names
I do not have very much experience with REs, but need to parse 100s of file names to generate a 'metadata' data set. I have been able to generate text files that include the file paths and the file name. It is simple for me to parse out the complete file name, but I need to be able to parse out the "sample ID" from the file name.

The issue is that the syntax of the "sample IDs" is all over the place (See attached csv for example data: The goal is to go from the 'sample' column to the 'ID' column). I have tried a series of strsplit() commands, but this is very cumbersome, and is not functional in nature. I have also tried writing a function with a number of IF statements based on syntax structure. I feel like this is still not a good solution because it is still dependent on me manually identifying the different syntax before hand, and I could easily miss something since I have to do this by eye.

It seems to me that this is a regex problem, but I could use some resources to help me get started. I would like to be able to do this in either R or Python if possible. Thank you for any resources, or packages/modules that may be useful.

```<code>dput(head(brain_ref, 25))
structure(list(file = c("/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_2_brain_total_RNA_cDNA_CAGATC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_1_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_2_brain_total_RNA_cDNA_GTGAAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_1_brain_total_RNA_cDNA_CCGTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_2_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_2_brain_total_RNA_cDNA_CTTGTA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_1_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_1_brain_total_RNA_cDNA_CGATGT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_2_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_1_brain_total_RNA_cDNA_ACAGTG.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_1_brain_total_RNA_cDNA_GCCAAT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_2_brain_total_RNA_cDNA_TGACCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/ACI-SegHsd-2-brain-total-RNA_S17.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH2-3-brain-total-RNA_S4.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH5-3-brain-total-RNA_S3.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH8-3-brain-total-RNA_S5.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Cop-CrCrl-2-brain-total-RNA_S10.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-1-brain-total-RNA_S16.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-2-brain-total-RNA_S13.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-1-brain-total-RNA_S18.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-2-brain-total-RNA_S15.genes.results"
), sample = c("BXH12_1_brain_total_RNA_cDNA_GTCCGC", "BXH12_2_brain_total_RNA_cDNA_CAGATC",
"HXB13_1_brain_total_RNA_cDNA_ATGTCA", "HXB13_2_brain_total_RNA_cDNA_GTGAAA",
"HXB17_1_brain_total_RNA_cDNA_CCGTCC", "HXB17_2_brain_total_RNA_cDNA_ATGTCA",
"HXB2_1_brain_total_RNA_cDNA_GTCCGC", "HXB2_2_brain_total_RNA_cDNA_CTTGTA",
"HXB25_1_brain_total_RNA_cDNA_AGTTCC", "HXB25_2_brain_total_RNA_cDNA_AGTCAA",
"HXB27_1_brain_total_RNA_cDNA_CGATGT", "HXB27_2_brain_total_RNA_cDNA_AGTTCC",
"HXB7_1_brain_total_RNA_cDNA_ACAGTG", "HXB7_2_brain_total_RNA_cDNA_AGTCAA",
"SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR_2_brain_total_RNA_cDNA_TGACCA",
"ACI-SegHsd-2-brain-total-RNA_S17", "BXH2-3-brain-total-RNA_S4",
"BXH5-3-brain-total-RNA_S3", "BXH8-3-brain-total-RNA_S5", "Cop-CrCrl-2-brain-total-RNA_S10",
"Dark-Agouti-1-brain-total-RNA_S16", "Dark-Agouti-2-brain-total-RNA_S13",
"F344-NCI-1-brain-total-RNA_S18", "F344-NCI-2-brain-total-RNA_S15"
), batch = c("batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch10", "batch10",
"batch10", "batch10", "batch10", "batch10", "batch10", "batch10",
"batch10"), ID = c("BXH12_1", "BXH12_2", "HXB13_1", "HXB13_2",
"HXB17_1", "HXB17_2", "HXB2_1", "HXB2_2", "HXB25_1", "HXB25_2",
"HXB27_1", "HXB27_2", "HXB7_1", "HXB7_2", "SHR_1", "SHR_2", "ACI-SegHsd_2",
"BXH2_3", "BXH5_3", "BXH8_3", "Cop-CrCrl_2", "Dark-Agouti_1",
"Dark-Agouti_2", "F344-NCI_1", "F344-NCI_2")), row.names = c(NA,
25L), class = "data.frame")
</code>```

答:
If all samples contain _brain or -brain and you want to keep the stuff before that you could do:

names=c("ABBA-1_2-brain-total2", "BABBA-2_2_brain-total2", "ARA_1-1_2-brain-total2")
gsub("(.*).brain.*", "\\1", names)
#> [1] "ABBA-1_2"  "BABBA-2_2" "ARA_1-1_2"
```

Body:
I do not have very much experience with REs, but need to parse 100s of file names to generate a 'metadata' data set. I have been able to generate text files that include the file paths and the file name. It is simple for me to parse out the complete file name, but I need to be able to parse out the "sample ID" from the file name.

The issue is that the syntax of the "sample IDs" is all over the place (See attached csv for example data: The goal is to go from the 'sample' column to the 'ID' column). I have tried a series of strsplit() commands, but this is very cumbersome, and is not functional in nature. I have also tried writing a function with a number of IF statements based on syntax structure. I feel like this is still not a good solution because it is still dependent on me manually identifying the different syntax before hand, and I could easily miss something since I have to do this by eye.

It seems to me that this is a regex problem, but I could use some resources to help me get started. I would like to be able to do this in either R or Python if possible. Thank you for any resources, or packages/modules that may be useful.

dput(head(brain_ref, 25))
structure(list(file = c("/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_2_brain_total_RNA_cDNA_CAGATC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_1_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_2_brain_total_RNA_cDNA_GTGAAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_1_brain_total_RNA_cDNA_CCGTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_2_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_2_brain_total_RNA_cDNA_CTTGTA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_1_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_1_brain_total_RNA_cDNA_CGATGT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_2_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_1_brain_total_RNA_cDNA_ACAGTG.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_1_brain_total_RNA_cDNA_GCCAAT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_2_brain_total_RNA_cDNA_TGACCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/ACI-SegHsd-2-brain-total-RNA_S17.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH2-3-brain-total-RNA_S4.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH5-3-brain-total-RNA_S3.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH8-3-brain-total-RNA_S5.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Cop-CrCrl-2-brain-total-RNA_S10.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-1-brain-total-RNA_S16.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-2-brain-total-RNA_S13.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-1-brain-total-RNA_S18.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-2-brain-total-RNA_S15.genes.results"
), sample = c("BXH12_1_brain_total_RNA_cDNA_GTCCGC", "BXH12_2_brain_total_RNA_cDNA_CAGATC",
"HXB13_1_brain_total_RNA_cDNA_ATGTCA", "HXB13_2_brain_total_RNA_cDNA_GTGAAA",
"HXB17_1_brain_total_RNA_cDNA_CCGTCC", "HXB17_2_brain_total_RNA_cDNA_ATGTCA",
"HXB2_1_brain_total_RNA_cDNA_GTCCGC", "HXB2_2_brain_total_RNA_cDNA_CTTGTA",
"HXB25_1_brain_total_RNA_cDNA_AGTTCC", "HXB25_2_brain_total_RNA_cDNA_AGTCAA",
"HXB27_1_brain_total_RNA_cDNA_CGATGT", "HXB27_2_brain_total_RNA_cDNA_AGTTCC",
"HXB7_1_brain_total_RNA_cDNA_ACAGTG", "HXB7_2_brain_total_RNA_cDNA_AGTCAA",
"SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR_2_brain_total_RNA_cDNA_TGACCA",
"ACI-SegHsd-2-brain-total-RNA_S17", "BXH2-3-brain-total-RNA_S4",
"BXH5-3-brain-total-RNA_S3", "BXH8-3-brain-total-RNA_S5", "Cop-CrCrl-2-brain-total-RNA_S10",
"Dark-Agouti-1-brain-total-RNA_S16", "Dark-Agouti-2-brain-total-RNA_S13",
"F344-NCI-1-brain-total-RNA_S18", "F344-NCI-2-brain-total-RNA_S15"
), batch = c("batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch10", "batch10",
"batch10", "batch10", "batch10", "batch10", "batch10", "batch10",
"batch10"), ID = c("BXH12_1", "BXH12_2", "HXB13_1", "HXB13_2",
"HXB17_1", "HXB17_2", "HXB2_1", "HXB2_2", "HXB25_1", "HXB25_2",
"HXB27_1", "HXB27_2", "HXB7_1", "HXB7_2", "SHR_1", "SHR_2", "ACI-SegHsd_2",
"BXH2_3", "BXH5_3", "BXH8_3", "Cop-CrCrl_2", "Dark-Agouti_1",
"Dark-Agouti_2", "F344-NCI_1", "F344-NCI_2")), row.names = c(NA,
25L), class = "data.frame")


问:
URL getting blocked at security level after Windows 10 upgrade
We recently had a windows upgrade 10 to patch version 10.0.18362. Before this we were able to connect to any URLs.

Aftermath is now we are not able to connect to a website which is hosted after a security device (WAF - web application firewall). CI_session (cookie value is now in different format value like - session_id%22%3Bs%3A32%3A%2)

Just wondering does an operating system changes the HTTPs request format after a client sends it to the server.

Will need help on this. Not sure how to put this up and look for answers.

答:
There seem to be two separate paths going on here:

Windows 10 patches

A WAF implemented on your web app (is it F5's ASM, Advanced WAF or NGINX WAF, F5 was tagged).

That version of Windows by itself doesn't have issues related to connecting to URLs. If you have a VPN in the mix, then that does pose some changes that could affect your browsing sessions (split-dns versus full tunnel and such).

If the WAF is our potential culprit (using F5 as example since it was tagged) and there are blocking events by default the WAF will give you a message stating it was blocked along with an error code.

When rolling out a WAF policy in front of an application, the standard process is to run in transparent mode while learning the application. The WAF then understands the default behavior of that application (if going beyond default attack signatures). If the application is changed, it's standard practice to rerun learning and update the WAF policy as needed (usually done during test/stg processes).

Regardless, the WAF would generate warning or blocking events and this would be visible in analytics, logging, and a blocking page would present itself to the user being blocked (unless disabled - bad experience though).

Moving beyond the WAF aspect of this, if the application is indeed behind a BIG-IP, there may be load balancing methods involved using cookie persistence for the session.  The F5 BIG-IP will use a cookie insert or rewrite which clients use until the cookie/session expires (expiration based on persistence within the BIG-IP - more on that here: AskF5 K6917).

Depending on what system is responsible for the session, you should A) not see two separate ci_sessions and B) the BIG-IP would be responsible for the session state to the back end node.

Your client COULD be connecting to two back end nodes and receiving two separate sessions independent of each other. If that's possibly the case, then investigating how the F5 BIG-IP is determining persistence is needed.

If another persistence method was used you'll need to find out and resolve with the BIG-IP admin/app owners.  Example of persistence methods on BIG-IP v15. Either way, you'll need to find out how the application is deployed behind BIG-IP and if that changed. If the answer cannot be found within F5's DevCentral community  or at AskF5, then a ticket should be created. Cookie persistence on BIG-IP isn't difficult to implement but it's all dependent on how the application behaves.

If not, gather some more details and I can update this answer. Hope this helped at least understand the WAF and BIG-IP LB methonds.