问:
POST Request working with / at the end of URL but not without /
I have a small script on my server to catch a POST request, like this:

```<code><?php

$jsonformat = json_encode($_POST);

$jsonFile = fopen("data.json", "w") or die("Unable to open file!");
fwrite($jsonFile, $jsonformat);
fclose($jsonFile);
echo "success";

?>
</code>```

Above script is named index.php and placed in http://example.com/data/report/

I have another script for sending the POST request like this:

```<code><?php

$url = 'http://example.com/data/report/';

$data = array('key1' => 'value1', 'key2' => 'value2');

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

?>
</code>```

The two script are working great. But in another situation the $url is like this: 'http://example.com/data/report' Notice no "/" at the end of the url. In the situation without "/" at the end the json-file on server is still generated but it is empty.

I have no possibility adding the "/" to the url. Its a device where I can not edit the code but I know it is missing "/" at the end so code above is just my example. I have reproduced the issue, I think.

So my question is:
- Why is it working with "/" but not without?
- Can I do anything on the server so http://example.com/data/report will be the same as http://example.com/data/report/

I have access to .htaccess on the server

答:
Have you got a .htaccess file or anything that is rewriting your URLs?

For example I have a line in mine like:

```<code>RewriteRule ^([^\.]+)$ $1.php [L,NC,QSA]
</code>```

This removes the file extension from the browser URL bar. So if I go to mywebsite.com/mydirectory/myfile it will automatically presume it means mywebsite.com/mydirectory/myfile.php.

If I went to mywebsite.com/mydirectory it would try to rewrite this as mywebsite.com/mydirectory.php unless I put the / at the end so it knows it's a directory.

Body:
I have a small script on my server to catch a POST request, like this:

<?php

$jsonformat = json_encode($_POST);

$jsonFile = fopen("data.json", "w") or die("Unable to open file!");
fwrite($jsonFile, $jsonformat);
fclose($jsonFile);
echo "success";

?>

Above script is named index.php and placed in http://example.com/data/report/

I have another script for sending the POST request like this:

<?php

$url = 'http://example.com/data/report/';

$data = array('key1' => 'value1', 'key2' => 'value2');

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

?>

The two script are working great. But in another situation the $url is like this: 'http://example.com/data/report' Notice no "/" at the end of the url. In the situation without "/" at the end the json-file on server is still generated but it is empty.

I have no possibility adding the "/" to the url. Its a device where I can not edit the code but I know it is missing "/" at the end so code above is just my example. I have reproduced the issue, I think.

So my question is:
- Why is it working with "/" but not without?
- Can I do anything on the server so http://example.com/data/report will be the same as http://example.com/data/report/

I have access to .htaccess on the server

Body:
Have you got a .htaccess file or anything that is rewriting your URLs?

For example I have a line in mine like:

RewriteRule ^([^\.]+)$ $1.php [L,NC,QSA]

This removes the file extension from the browser URL bar. So if I go to mywebsite.com/mydirectory/myfile it will automatically presume it means mywebsite.com/mydirectory/myfile.php.

If I went to mywebsite.com/mydirectory it would try to rewrite this as mywebsite.com/mydirectory.php unless I put the / at the end so it knows it's a directory.


来源: stackexchange

问:
Add a class to body when component is clicked?
I have a component in vue, I wish to toggle a class on the body on click.

How can I do this? Would I just have to use JS to target the body and add a class?

Or is there more of a vue way?

For context I need to add a no scroll class to the body to prevent scrolling for an overlay menu.

答:
i use a similar approach within a method (I call the setBodyClass() function from elsewhere as well, which is why it's wrapped in its own function:</p>

```<code>methods: {
  toggleMenu() {
    this.showMenu = !this.showMenu
    this.setBodyClass()
  },
  setBodyClass() {
    var body = document.body
    body.classList.toggle('open')
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i use a similar approach within a method (I call the setBodyClass() function from elsewhere as well, which is why it's wrapped in its own function:

methods: {
  toggleMenu() {
    this.showMenu = !this.showMenu
    this.setBodyClass()
  },
  setBodyClass() {
    var body = document.body
    body.classList.toggle('open')
  }
}

ContentLicense: CC BY-SA 4.0


问:
AWS - Send Message to an SQS from a Lambda function inside a VPC
I have hosted a Lambda function using AWS Chalice inside a VPC since I want it to access a Serverless Aurora DB Instance. Now I also want this function to send_message() to an SQS.

I followed Tutorial: Sending a Message to an Amazon SQS Queue from Amazon Virtual Private Cloud and was able to call the SQS from inside my EC2. But even then I could not use my Lambda function to call the SQS.

It would be very helpful if someone could actually tell me how to do the whole thing manually rather than using the CloudFormation stack, or at least tell me how to get the SQS Endpoint working.

答: You either need to add a VPC Endpoint for SQS to your VPC, or place the Lambda function in subnets with a route to a NAT Gateway.</p>


问:
How to import workspace into a workspace?
I have 2 xcode workspaces and I want to use both the workspace in a single project. Is there is any way to achieve this?</p>

答: Create and execute the two pod files as you are doing now, create another workspace, add the two projects and the two pods (separate them with folders). DONT ADD THE WORKSPACES, just the projects.</p>


问:
List prime numbers
I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

```<code>for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}
</code>```

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

```<code>for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}
</code>```

Can I get help in terminating the loop after a count of 100 primes ?

答:
You need to keep track of how many prime numbers you have printed, once it reaches 100 stop printing. I have explained the code below using comments in code.</p>

```<code>public class Main
{
    public static void main(String[] args) {
        int k = 0;  // to keep track of how many primes you have prited
        int i = 2;  // number to check for prime, increases every loop
        while (k < 100){  // while you have printed less than 100 primes
            boolean isPrime = true;  // next few lines are checking i for prime and store it in this variable
            for(int divisor = 2; divisor <= i / 2; divisor++) {  // you should go with divisor <= Math.sqrt(i) in condition, I couldn't be bothered in import stuff.
                if (i % divisor == 0) {
                    isPrime = false;
                    break; // i is not a prime, no reason to continue checking
                }
            }
            if (isPrime){
                System.out.println(i);  // if i is prime, print it
                k ++; // increase k by when a print number is found
            }
            i ++; // increase i to check next number
        }
    }
}
</code>```

Title: List prime numbers

Body:
I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}

Can I get help in terminating the loop after a count of 100 primes ?

Body:
You need to keep track of how many prime numbers you have printed, once it reaches 100 stop printing. I have explained the code below using comments in code.

public class Main
{
    public static void main(String[] args) {
        int k = 0;  // to keep track of how many primes you have prited
        int i = 2;  // number to check for prime, increases every loop
        while (k < 100){  // while you have printed less than 100 primes
            boolean isPrime = true;  // next few lines are checking i for prime and store it in this variable
            for(int divisor = 2; divisor <= i / 2; divisor++) {  // you should go with divisor <= Math.sqrt(i) in condition, I couldn't be bothered in import stuff.
                if (i % divisor == 0) {
                    isPrime = false;
                    break; // i is not a prime, no reason to continue checking
                }
            }
            if (isPrime){
                System.out.println(i);  // if i is prime, print it
                k ++; // increase k by when a print number is found
            }
            i ++; // increase i to check next number
        }
    }
}


问:
ClearDB on Heroku throws an error when running a migration to create a new table that has a `details` field of type `json`
I am running a Rails 5.2.2 and ruby 2.6.3 app on Heroku backed by ClearDB database.

NOTE: Locally this all works fine

my gem file has the mysql2 version as such:
gem 'mysql2', '>= 0.4.4', '< 0.6.0'

When I attempt to run a migration to create a new table that has a details field of type json it fails with a syntax error.

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json'

Removing the details field of type json and re-running the migration succeeeds.

Here is an example of the contents of the migration.

```<code>class InitTables < ActiveRecord::Migration[5.2]
  def change
    create_table :services do |t|
      t.string :public_id, null: false, index: { unique: true }
      t.json :details
    end
  end
end
</code>```

This is the error message:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json'

答:
According to the ClearDB support, 5.7 version of MySQL is required to be compatible with my migration to use a field of json type.

The Heroku Ignite, Punch, Drift and Scream plans shared resource plans are currently only available on clusters running 5.5 or 5.6 (5.6 in Europe) versions of MySQL and I AM ON the Heroku Ignite plan.

To solve this issue I'll need a dedicated resource(instance) plans that can be configured to use 5.5, 5.6, or 5.7 version of MySQL.

Body:
I am running a Rails 5.2.2 and ruby 2.6.3 app on Heroku backed by ClearDB database.

NOTE: Locally this all works fine

my gem file has the mysql2 version as such:
gem 'mysql2', '>= 0.4.4', '< 0.6.0'

When I attempt to run a migration to create a new table that has a details field of type json it fails with a syntax error.

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json'

Removing the details field of type json and re-running the migration succeeeds.

Here is an example of the contents of the migration.

class InitTables < ActiveRecord::Migration[5.2]
  def change
    create_table :services do |t|
      t.string :public_id, null: false, index: { unique: true }
      t.json :details
    end
  end
end

This is the error message:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json'


问:
Nested Scrollview scrolling to top in Error
I have an activity, please see the xml:

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            android:fitsSystemWindows="true">

            <android.support.v4.view.ViewPager
                android:id="@+id/property_image_viewpager"
                android:layout_width="match_parent"
                android:layout_height="@dimen/property_details_image_height">
            </android.support.v4.view.ViewPager>

            <TextView
                android:id="@+id/property_detail_num_photos"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/image_pager_pagination_1_image"
                android:textColor="@color/white"
                android:textSize="@dimen/property_detail_gallery_num_photos_text_size"
                android:background="@drawable/black_shape_rounded"
                android:layout_marginBottom="@dimen/property_detail_gallery_num_photos_margin_bottom"
                android:layout_marginStart="@dimen/property_detail_photo_label_margin_left"
                android:layout_alignBottom="@+id/image_pager"
                android:padding="@dimen/property_detail_gallery_num_photos_padding"
                android:drawablePadding="@dimen/property_detail_gallery_num_photos_height"
                android:drawableStart="@drawable/camera"
                android:layout_gravity="bottom"
                android:fontFamily="@string/roboto_reg" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin" />
        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nested_scroll_view"
        android:clipToPadding="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/property_details_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        style="@style/save_ad_button_style"
        app:backgroundTint="@color/daft_light_grey"
        app:layout_anchor="@id/app_bar_layout"
        app:layout_anchorGravity="bottom|right|end"/>

        <com.test.ie.ui.customviews.LoadingStateView
            android:id="@+id/loading_state_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="visible"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

In my recycler view I have an item that expands and collapses.  This works correctly, however if I launch an explicit intent.  When the user clicks on the viewpager they're brought to a gallery activity.  When the user returns to the previous screen and they click on the expandable layout, the nested scroll view scrolls to the top of the page.  This isn't expected behaviour.  I have tried lots of things to prevent the nested scrolling e.g. scrollBy(0,0) . I would appreciate if anyone has experienced this in the past they could give me a shout as I'm not sure how to solve this issue.

it might be worth noting that when I launch an implicit intent from this screen I don't experience the same issue.

答: Please add android:focusable="true" and android:focusableinTouchmode="true" in your parent CoordinatorLayout. Then it should work as per your expectation.

Body:
I have an activity, please see the xml:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            android:fitsSystemWindows="true">

            <android.support.v4.view.ViewPager
                android:id="@+id/property_image_viewpager"
                android:layout_width="match_parent"
                android:layout_height="@dimen/property_details_image_height">
            </android.support.v4.view.ViewPager>

            <TextView
                android:id="@+id/property_detail_num_photos"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/image_pager_pagination_1_image"
                android:textColor="@color/white"
                android:textSize="@dimen/property_detail_gallery_num_photos_text_size"
                android:background="@drawable/black_shape_rounded"
                android:layout_marginBottom="@dimen/property_detail_gallery_num_photos_margin_bottom"
                android:layout_marginStart="@dimen/property_detail_photo_label_margin_left"
                android:layout_alignBottom="@+id/image_pager"
                android:padding="@dimen/property_detail_gallery_num_photos_padding"
                android:drawablePadding="@dimen/property_detail_gallery_num_photos_height"
                android:drawableStart="@drawable/camera"
                android:layout_gravity="bottom"
                android:fontFamily="@string/roboto_reg" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin" />
        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nested_scroll_view"
        android:clipToPadding="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/property_details_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        style="@style/save_ad_button_style"
        app:backgroundTint="@color/daft_light_grey"
        app:layout_anchor="@id/app_bar_layout"
        app:layout_anchorGravity="bottom|right|end"/>

        <com.test.ie.ui.customviews.LoadingStateView
            android:id="@+id/loading_state_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="visible"/>

</android.support.design.widget.CoordinatorLayout>

In my recycler view I have an item that expands and collapses.  This works correctly, however if I launch an explicit intent.  When the user clicks on the viewpager they're brought to a gallery activity.  When the user returns to the previous screen and they click on the expandable layout, the nested scroll view scrolls to the top of the page.  This isn't expected behaviour.  I have tried lots of things to prevent the nested scrolling e.g. scrollBy(0,0) . I would appreciate if anyone has experienced this in the past they could give me a shout as I'm not sure how to solve this issue.

it might be worth noting that when I launch an implicit intent from this screen I don't experience the same issue.


问:
How can I remove text after a comma from a description field of Get-ADComputer?
I want to delete everything after the comma in the description field, so Text2 and Text3. Does anyone know how I can do this? I have heard something about regex but I don't know how to use it in this case.</p>

```<code>$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name,Description, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table

Name          Description                        LastLogonTimeStamp
----          -----------                        ------------------
SRV-TEST      Text1, Text2, Text3                10-1-2019 09:45:00
</code>```

答:
As per the suggestion of using -split in the comments this will return the 1st string in the array after splitting by ",".</p>

```<code>$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name, @{N='Description'; E={($_.Description -split ",")[0]}}, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table
</code>```

Body:
I want to delete everything after the comma in the description field, so Text2 and Text3. Does anyone know how I can do this? I have heard something about regex but I don't know how to use it in this case.

$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name,Description, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table

Name          Description                        LastLogonTimeStamp
----          -----------                        ------------------
SRV-TEST      Text1, Text2, Text3                10-1-2019 09:45:00

Body:
As per the suggestion of using -split in the comments this will return the 1st string in the array after splitting by ",".

$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name, @{N='Description'; E={($_.Description -split ",")[0]}}, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table


问:
How to rename a CSV file from a value in the CSV file
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

```<code>1234ABC, stuff, stuff
</code>```

Desired Output (filename 1234ABC.csv)

```<code>1234ABC, stuff, stuff
</code>```

I don't want to edit the content of the CSV itself, just change the filename

答:
starting with your original file before splitting

```<code>$ awk -F, '{print > ($1".csv")}' originalFile.csv
</code>```

and do all in one shot.

Body:
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

1234ABC, stuff, stuff

Desired Output (filename 1234ABC.csv)

1234ABC, stuff, stuff

I don't want to edit the content of the CSV itself, just change the filename

Body:
starting with your original file before splitting

$ awk -F, '{print > ($1".csv")}' originalFile.csv

and do all in one shot.


问:
Why is the assignment in a function ignored?
Consider following code:

```<code>zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz
</code>```

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

答:
Other answer is correctly pointed out that $() will create a subshell and you will have separate execution environment from parent shell.

```<code>zzz=2

function f()
{
   echo zzz=4
}

eval $(f)
echo $zzz
</code>```

You can overcome this problem by using eval . First print the desired assignment statement inside the function and then evaluate that statement in the caller code.

Note: Please note that, eval is having some caveats and should be avoided ,unless you know for sure the behavior of your code.

Body:
Consider following code:

zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

Body:
Other answer is correctly pointed out that $() will create a subshell and you will have separate execution environment from parent shell.

zzz=2

function f()
{
   echo zzz=4
}

eval $(f)
echo $zzz

You can overcome this problem by using eval . First print the desired assignment statement inside the function and then evaluate that statement in the caller code.

Note: Please note that, eval is having some caveats and should be avoided ,unless you know for sure the behavior of your code.


问:
Accessing attributes of an object stored in an array
Here is my condition: I have already known that I need fifteen objects to store event data, so I just declared fifteen variables:

```<code>var e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, 15;

function Event(title, content, logo, logo_in_black) {
    this.title = title;
    this.content = content;
    this.logo = logo;
    this.logo_in_black = logo_in_black;
}
</code>```

According to the user click, I dynamically assign data to the object according to the user click:

```<code>e1 = new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2);
</code>```

Then show the result on the view:

```<code>$('#e-1').css('background-image', "url('" + e1.logo + "')");
</code>```

I need to do the same thing fifteen times to put every event information to individual block looks like this:
! So I just tried the following method and I thought it must be the solution: I put fifteen objects in an array.

```<code>var e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15;
var events = [e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15];
</code>```

Assign the data and show on the view:

```<code>e1 = new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2);
e2 = ...
e3 = ...

for (var i = 0; i < 15; i ++) {
    $('#e-' + (i + 1)).css('background-image', "url('" + events[i].logo + "')");
}
</code>```

But the way I tried to access the attributes is wrong: events[i].logo
Can anyone please tell me why this can't work?
Thanks a lot!

答:
You have to assign the variables before you put them into the array. The array assignment uses the currentvalues of the variables, it doesn't make the array refer implicitly to the variables.

But there's no need for the variables in the first place, just assign directly to the array:

```<code>var events = [
    new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2),
    ...
];
</code>```

Any time you find yourself naming variables with numeric suffixes, you should almost always be using an array instead.

Body:
Here is my condition: I have already known that I need fifteen objects to store event data, so I just declared fifteen variables:

var e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, 15;

function Event(title, content, logo, logo_in_black) {
    this.title = title;
    this.content = content;
    this.logo = logo;
    this.logo_in_black = logo_in_black;
}

According to the user click, I dynamically assign data to the object according to the user click:

e1 = new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2);

Then show the result on the view:

$('#e-1').css('background-image', "url('" + e1.logo + "')");

I need to do the same thing fifteen times to put every event information to individual block looks like this:
! So I just tried the following method and I thought it must be the solution: I put fifteen objects in an array.

var e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15;
var events = [e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15];

Assign the data and show on the view:

e1 = new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2);
e2 = ...
e3 = ...

for (var i = 0; i < 15; i ++) {
    $('#e-' + (i + 1)).css('background-image', "url('" + events[i].logo + "')");
}

But the way I tried to access the attributes is wrong: events[i].logo
Can anyone please tell me why this can't work?
Thanks a lot!

Body:
You have to assign the variables before you put them into the array. The array assignment uses the currentvalues of the variables, it doesn't make the array refer implicitly to the variables.

But there's no need for the variables in the first place, just assign directly to the array:

var events = [
    new Event('Nike', 'BUY ONE GET ONE FOR FREE', logo_url, logo_url2),
    ...
];

Any time you find yourself naming variables with numeric suffixes, you should almost always be using an array instead.


问:
WebView GestureRecognition not working in Xamarin forms
I have a webview When this webview is tapped I need to make visible of a button the problem Is Gesture recognition is not working

my Xaml

```<code>   <customRenderer:CustomWebView Uri="{Binding SelectedJournal.Uri}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"  x:Name="CustomWebView" AbsoluteLayout.LayoutBounds="0,50,1,1" AbsoluteLayout.LayoutFlags="SizeProportional"  >
            <customRenderer:CustomWebView.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped2" NumberOfTapsRequired="1" ></TapGestureRecognizer>
            </customRenderer:CustomWebView.GestureRecognizers>
        </customRenderer:CustomWebView>

        <customRenderer:NavigationImageButton ItemTapped="FullScreenOnTapped" Source="full.jpg" AbsoluteLayout.LayoutBounds="0.5,1,-1,-1" AbsoluteLayout.LayoutFlags="PositionProportional"  HeightRequest="60" WidthRequest="60" x:Name="FullScreenBtn" IsVisible="False" >
</code>```

In the code behind i called like this

```<code>private void TapGestureRecognizer_OnTapped2(object sender, EventArgs e)
    {
        FullScreenBtn.IsVisible = true;
    }
</code>```

This should work but this is not working

also my custom rendering web view class

```<code>  public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}
</code>```

How to Achive this

答:
Instead of using the gesture recognizer on your webview, you can use the 'Focused' event of your view to display your button. You can do something like this:

```<code>var wb = new WebView
{
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
    Source = "https://stackoverflow.com/questions/56320611/webview-gesturerecognition-not-working-in-xamarin-forms",
};

wb.Focused += (s, e) =>
{
   //Handle your logic here!
   wb.Unfocus();
 };
</code>```

Here, Unfocus() is used if you wish to implement your logic everytime the webview is tapped.

Body:
I have a webview When this webview is tapped I need to make visible of a button the problem Is Gesture recognition is not working

my Xaml

   <customRenderer:CustomWebView Uri="{Binding SelectedJournal.Uri}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"  x:Name="CustomWebView" AbsoluteLayout.LayoutBounds="0,50,1,1" AbsoluteLayout.LayoutFlags="SizeProportional"  >
            <customRenderer:CustomWebView.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped2" NumberOfTapsRequired="1" ></TapGestureRecognizer>
            </customRenderer:CustomWebView.GestureRecognizers>
        </customRenderer:CustomWebView>

        <customRenderer:NavigationImageButton ItemTapped="FullScreenOnTapped" Source="full.jpg" AbsoluteLayout.LayoutBounds="0.5,1,-1,-1" AbsoluteLayout.LayoutFlags="PositionProportional"  HeightRequest="60" WidthRequest="60" x:Name="FullScreenBtn" IsVisible="False" >

In the code behind i called like this

private void TapGestureRecognizer_OnTapped2(object sender, EventArgs e)
    {
        FullScreenBtn.IsVisible = true;
    }

This should work but this is not working

also my custom rendering web view class

  public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}

How to Achive this

Body:
Instead of using the gesture recognizer on your webview, you can use the 'Focused' event of your view to display your button. You can do something like this:

var wb = new WebView
{
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
    Source = "https://stackoverflow.com/questions/56320611/webview-gesturerecognition-not-working-in-xamarin-forms",
};

wb.Focused += (s, e) =>
{
   //Handle your logic here!
   wb.Unfocus();
 };

Here, Unfocus() is used if you wish to implement your logic everytime the webview is tapped.


问:
Counting the max of elements based on stack operations c++
You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

```<code>#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}
</code>```

Input :

```<code>6 4
1 2 4 3 3 5
</code>```

Expected Output :

```<code>4
</code>```

Error:

```<code>Error Message : Debug Error ! Program :- Heap Corruption detected : after
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote
memory after end of heap buffer.
</code>```

答:
In an array of size n the valid index are from 0 up to n-1, not from 1 to n

Warning when you allocate an array with new you have to deallocate it with delete []

I also encourage you to check when you read a value that the reading success, else the current container is not set and all the next read will do nothing

For instance from your code :

```<code>#include <iostream>

using namespace std;

int main()
{
  int n, x, max;

  if ((! (cin >> n)) || (n < 1))
    cerr << "invalid size" << endl;
  else if ((! (cin >> x)) || (x < 0) || (x >= n))
    cerr << "invalid min index" << endl;
  else {
    int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
    for (int i = n-1; i >= 0; i--)
    {
      if (!(cin >> arr[i])) {
        cerr << "invalid value" << endl;
        return 0;
      }
    }
    max = arr[n-1];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
    for (int i = n-2; i >= x; i--)
    {
      if (arr[i] > max)
        {
          max = arr[i];
        }
    }
    cout << max << endl;
    delete arr; // must be delete [] arr;
  }
  return 0;
}
</code>```

Out of the fact I check an integer was enter I also check the size/min index are strictly positive and also check the validity of the min index

It is also useless to loop to find the max comparing thearr[n-1] with itself, so the first considered index is n-2

It seems strange to fill the array from the last index

You use an array but you can also use a vector<int> as well, std::vector are very practical

Compilation and executions :

```<code>pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
aze
invalid size
pi@raspberrypi:/tmp $ ./a.out
-1
invalid size
pi@raspberrypi:/tmp $ ./a.out
3 qsd
invalid min index
pi@raspberrypi:/tmp $ ./a.out
3 4
invalid min index
pi@raspberrypi:/tmp $ ./a.out
6 4
1 2 4 3 3 5
2
pi@raspberrypi:/tmp $
</code>```

Note the result is 2 rather than 4 because of the shift in the index, if you want the index starts by 1 for the user do

```<code>#include<iostream>

using namespace std;

int main()
{
  int n, x, max;

  if ((! (cin >> n)) || (n < 1))
    cerr << "invalid size" << endl;
  else if ((! (cin >> x)) || (x < 1) || (x > n))
    cerr << "invalid min index" << endl;
  else {
    x -= 1;

    int * arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
    for (int i = n-1; i >= 0; i--)
    {
      if (!(cin >> arr[i])) {
        cerr << "invalid value" << endl;
        return 0;
      }
    }
    max = arr[n-1];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
    for (int i = n-2; i >= x; i--)
    {
      if (arr[i] > max)
        {
          max = arr[i];
        }
    }
    cout << max << endl;
    delete arr; // must be delete [] arr;
  }
  return 0;
}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
6 4
1 2 4 3 3 5
4
pi@raspberrypi:/tmp $
</code>```

Execution under valgrind indicating the wrong free arr:

```<code>pi@raspberrypi:/tmp $ valgrind ./a.out
==3761== Memcheck, a memory error detector
==3761== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3761== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3761== Command: ./a.out
==3761==
6 4
1 2 4 3 3 5
4
==3761== Mismatched free() / delete / delete []
==3761==    at 0x48491EC: operator delete(void*) (vg_replace_malloc.c:576)
==3761==    by 0x10BE7: main (in /tmp/a.out)
==3761==  Address 0x4bcb388 is 0 bytes inside a block of size 24 alloc'd
==3761==    at 0x48485F0: operator new[](unsigned int) (vg_replace_malloc.c:417)
==3761==    by 0x10A9F: main (in /tmp/a.out)
==3761==
==3761==
==3761== HEAP SUMMARY:
==3761==     in use at exit: 0 bytes in 0 blocks
==3761==   total heap usage: 4 allocs, 4 frees, 22,296 bytes allocated
==3761==
==3761== All heap blocks were freed -- no leaks are possible
==3761==
==3761== For counts of detected and suppressed errors, rerun with: -v
==3761== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $
</code>```

Body:
You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}

Input :

6 4
1 2 4 3 3 5

Expected Output :

4

Error:

Error Message : Debug Error ! Program :- Heap Corruption detected : after
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote
memory after end of heap buffer.

Body:
In an array of size n the valid index are from 0 up to n-1, not from 1 to n

Warning when you allocate an array with new you have to deallocate it with delete []

I also encourage you to check when you read a value that the reading success, else the current container is not set and all the next read will do nothing

For instance from your code :

#include <iostream>

using namespace std;

int main()
{
  int n, x, max;

  if ((! (cin >> n)) || (n < 1))
    cerr << "invalid size" << endl;
  else if ((! (cin >> x)) || (x < 0) || (x >= n))
    cerr << "invalid min index" << endl;
  else {
    int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
    for (int i = n-1; i >= 0; i--)
    {
      if (!(cin >> arr[i])) {
        cerr << "invalid value" << endl;
        return 0;
      }
    }
    max = arr[n-1];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
    for (int i = n-2; i >= x; i--)
    {
      if (arr[i] > max)
        {
          max = arr[i];
        }
    }
    cout << max << endl;
    delete arr; // must be delete [] arr;
  }
  return 0;
}

Out of the fact I check an integer was enter I also check the size/min index are strictly positive and also check the validity of the min index

It is also useless to loop to find the max comparing thearr[n-1] with itself, so the first considered index is n-2

It seems strange to fill the array from the last index

You use an array but you can also use a vector<int> as well, std::vector are very practical

Compilation and executions :

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
aze
invalid size
pi@raspberrypi:/tmp $ ./a.out
-1
invalid size
pi@raspberrypi:/tmp $ ./a.out
3 qsd
invalid min index
pi@raspberrypi:/tmp $ ./a.out
3 4
invalid min index
pi@raspberrypi:/tmp $ ./a.out
6 4
1 2 4 3 3 5
2
pi@raspberrypi:/tmp $

Note the result is 2 rather than 4 because of the shift in the index, if you want the index starts by 1 for the user do

#include<iostream>

using namespace std;

int main()
{
  int n, x, max;

  if ((! (cin >> n)) || (n < 1))
    cerr << "invalid size" << endl;
  else if ((! (cin >> x)) || (x < 1) || (x > n))
    cerr << "invalid min index" << endl;
  else {
    x -= 1;

    int * arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
    for (int i = n-1; i >= 0; i--)
    {
      if (!(cin >> arr[i])) {
        cerr << "invalid value" << endl;
        return 0;
      }
    }
    max = arr[n-1];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
    for (int i = n-2; i >= x; i--)
    {
      if (arr[i] > max)
        {
          max = arr[i];
        }
    }
    cout << max << endl;
    delete arr; // must be delete [] arr;
  }
  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
6 4
1 2 4 3 3 5
4
pi@raspberrypi:/tmp $

Execution under valgrind indicating the wrong free arr:

pi@raspberrypi:/tmp $ valgrind ./a.out
==3761== Memcheck, a memory error detector
==3761== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3761== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3761== Command: ./a.out
==3761==
6 4
1 2 4 3 3 5
4
==3761== Mismatched free() / delete / delete []
==3761==    at 0x48491EC: operator delete(void*) (vg_replace_malloc.c:576)
==3761==    by 0x10BE7: main (in /tmp/a.out)
==3761==  Address 0x4bcb388 is 0 bytes inside a block of size 24 alloc'd
==3761==    at 0x48485F0: operator new[](unsigned int) (vg_replace_malloc.c:417)
==3761==    by 0x10A9F: main (in /tmp/a.out)
==3761==
==3761==
==3761== HEAP SUMMARY:
==3761==     in use at exit: 0 bytes in 0 blocks
==3761==   total heap usage: 4 allocs, 4 frees, 22,296 bytes allocated
==3761==
==3761== All heap blocks were freed -- no leaks are possible
==3761==
==3761== For counts of detected and suppressed errors, rerun with: -v
==3761== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $


问:
Is it expected behavior that Go allows overflow for arithmetic operations instead of throwing an exception?
I am porting some Go code to Rust and I realized that Rust panics when overflow occurs during multiplication while Go allows the overflow to happen.

Test code below, that does not cause overflow but print reduced value.
(tested via: https://play.golang.org/)

```<code>func main() {
    fmt.Println("test\n")
    var key uint64 = 15000;

    key = key*2862933555777941757 + 1

    fmt.Println(key)
}
</code>```

答:
Spec: Integer overflow:

For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on "wrap around".

For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. Overflow does not cause a run-time panic. A compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true.

As quoted above, overflow exists and it does not cause a run-time panic.

But care must be taken, as if you have a constant expressions, since they have arbitrary precision, if the result is to be converted to a fixed precision where it does not fit into the target type's valid range, it results in a compile time-error.

For example:

```<code>const maxuint64 = 0xffffffffffffffff
var key uint64 = maxuint64 * maxuint64

fmt.Println(key)
</code>```

The above yields:

```<code>constant 340282366920938463426481119284349108225 overflows uint64
</code>```

maxuint64 * maxuint64 is a constant expression which is properly calculated (its value is 340282366920938463426481119284349108225), but when this value is to be assigned to the key variable of type uint64, it results in a compile-time error because this value cannot be represented by a value of type uint64. But this is not a run-time panic.

See related questions:

Golang: on-purpose int overflow

Does Go compiler's evaluation differ for constant expression and other expression

How to store a big float64 in a string without overflow?

Proper way for casting uint16 to int16 in Go

Body:
I am porting some Go code to Rust and I realized that Rust panics when overflow occurs during multiplication while Go allows the overflow to happen.

Test code below, that does not cause overflow but print reduced value.
(tested via: https://play.golang.org/)

func main() {
    fmt.Println("test\n")
    var key uint64 = 15000;

    key = key*2862933555777941757 + 1

    fmt.Println(key)
}

Body:
Spec: Integer overflow:

For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on "wrap around".

For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. Overflow does not cause a run-time panic. A compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true.

As quoted above, overflow exists and it does not cause a run-time panic.

But care must be taken, as if you have a constant expressions, since they have arbitrary precision, if the result is to be converted to a fixed precision where it does not fit into the target type's valid range, it results in a compile time-error.

For example:

const maxuint64 = 0xffffffffffffffff
var key uint64 = maxuint64 * maxuint64

fmt.Println(key)

The above yields:

constant 340282366920938463426481119284349108225 overflows uint64

maxuint64 * maxuint64 is a constant expression which is properly calculated (its value is 340282366920938463426481119284349108225), but when this value is to be assigned to the key variable of type uint64, it results in a compile-time error because this value cannot be represented by a value of type uint64. But this is not a run-time panic.

See related questions:

Golang: on-purpose int overflow

Does Go compiler's evaluation differ for constant expression and other expression

How to store a big float64 in a string without overflow?

Proper way for casting uint16 to int16 in Go


问:
Spring-Boot-Maven-Plugin - Command to Copy Resources into WAR Main Directory
QUESTION

In a Spring Boot Java application built with Maven using the spring-boot-maven-plugin with WAR packaging through Eclipse IDE with M2 with the goal as clean package, I would like to know if there is a command which would allow me to copy the resource folders (css, images, etc) which currently end up in mywar.war/WEB-INF/classes/static/ into the root directory mywar.war, so that I have mywar.war/images/, etc?

I see that with other plugins, there is something like a targetPath, but I can't find anything like that in the documentation for spring-boot-maven-plugin.

EXAMPLE POM

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.myapp</groupId>
    <artifactId>MyApp</artifactId>
    <version>1.0.0</version>
    <name>${project.artifactId}</name>
    <description>My Application</description>

    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.test.skip>true</maven.test.skip>
        <tomcat.version>7.0.78</tomcat.version>
        <servlet-api.version>3.0.1</servlet-api.version>
        <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>

        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-tomcat</artifactId>
           <scope>provided</scope>
        </dependency>

         <dependency>
            <groupId>test</groupId>
            <artifactId>x</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/MyJar.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

答:
So, I ended up getting around this by moving all of my resources from the /src/main/resources/static directory into a /src/main/webapp directory. Then everything appeared right under the root of the resulting WAR file, and the Apache HTTP Server picked them up and allowed them through.

Thanks for your insight, everyone!

Body:
QUESTION

In a Spring Boot Java application built with Maven using the spring-boot-maven-plugin with WAR packaging through Eclipse IDE with M2 with the goal as clean package, I would like to know if there is a command which would allow me to copy the resource folders (css, images, etc) which currently end up in mywar.war/WEB-INF/classes/static/ into the root directory mywar.war, so that I have mywar.war/images/, etc?

I see that with other plugins, there is something like a targetPath, but I can't find anything like that in the documentation for spring-boot-maven-plugin.

EXAMPLE POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.myapp</groupId>
    <artifactId>MyApp</artifactId>
    <version>1.0.0</version>
    <name>${project.artifactId}</name>
    <description>My Application</description>

    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.test.skip>true</maven.test.skip>
        <tomcat.version>7.0.78</tomcat.version>
        <servlet-api.version>3.0.1</servlet-api.version>
        <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>

        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-tomcat</artifactId>
           <scope>provided</scope>
        </dependency>

         <dependency>
            <groupId>test</groupId>
            <artifactId>x</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/MyJar.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


问:
Webpack Unrecognized Input because of third party less file using \9
So, I am using Ant Design systems Menu component ( I am using other components from them, and all is good ), but this Menu component uses some css that has a IE9 fallback, "\9".. and its killing my build process.

error:

```<code>ERROR in ./node_modules/css-loader!./node_modules/postcss-loader/src??ref--3-3!./node_modules/less-loader/dist/cjs.js!./node_modules/antd/lib/menu/style/index.css
Module build failed:

  background: #fff;
  background: rgba(0, 0, 0, 0.65) \9;
                                ^
Unrecognised input
      in /Users/dd/BRANCHES/sandbox/code/ui/node_modules/antd/lib/menu/style/index.css (line 244, column 34)
</code>```

I am guessing this is a webpack issue, and this what I have:

```<code>{
        test: /\.(less|css)$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            { loader: 'css-loader' },
            {
              loader: 'postcss-loader',
              options: {
                plugins: function() {
                  return [autoprefixer];
                }
              }
            },
            { loader: 'less-loader' }
          ]
        })
</code>```

I am using: "webpack": "^3.7.1", (( can't upgrade at this time )).

Any ideas on how to fix?

答: You are using css-loader to handle less files, try less-loader in priority.

Body:
So, I am using Ant Design systems Menu component ( I am using other components from them, and all is good ), but this Menu component uses some css that has a IE9 fallback, "\9".. and its killing my build process.

error:

ERROR in ./node_modules/css-loader!./node_modules/postcss-loader/src??ref--3-3!./node_modules/less-loader/dist/cjs.js!./node_modules/antd/lib/menu/style/index.css
Module build failed:

  background: #fff;
  background: rgba(0, 0, 0, 0.65) \9;
                                ^
Unrecognised input
      in /Users/dd/BRANCHES/sandbox/code/ui/node_modules/antd/lib/menu/style/index.css (line 244, column 34)

I am guessing this is a webpack issue, and this what I have:

{
        test: /\.(less|css)$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            { loader: 'css-loader' },
            {
              loader: 'postcss-loader',
              options: {
                plugins: function() {
                  return [autoprefixer];
                }
              }
            },
            { loader: 'less-loader' }
          ]
        })

I am using: "webpack": "^3.7.1", (( can't upgrade at this time )).

Any ideas on how to fix?


问:
Create dictionary using cell values from two columns of excel
I have an excel sheet with columns ISIN and URL as header as shown below:

```<code>*ISIN   URL*

ISIN1   https://mylink3.pdf
ISIN2   https://mylink2.pdf
</code>```

I need to create a dictionary of the values of this sheet and have used the below code:

```<code>import pandas as pd

my_dic = pd.read_excel('PDFDwn.xlsx', index_col=0).to_dict()
print(my_dic)
</code>```

The output that I receive is as below.

```<code>{'URL': {'ISIN1': 'https://mylink3.pdf', 'ISIN2': 'https://mylink2.pdf'}}
</code>```

whereas expected output should be as below without URL piece.

```<code>{'ISIN1': 'https://mylink3.pdf', 'ISIN2': 'https://mylink2.pdf'}
</code>```

答:
Simple solution:

```<code>my_dic['URL']
</code>```

Output:

```<code>{'ISIN1': 'https://mylink3.pdf', 'ISIN2': 'https://mylink2.pdf'}
</code>```

Body:
I have an excel sheet with columns ISIN and URL as header as shown below:

*ISIN   URL*

ISIN1   https://mylink3.pdf
ISIN2   https://mylink2.pdf

I need to create a dictionary of the values of this sheet and have used the below code:

import pandas as pd

my_dic = pd.read_excel('PDFDwn.xlsx', index_col=0).to_dict()
print(my_dic)

The output that I receive is as below.

{'URL': {'ISIN1': 'https://mylink3.pdf', 'ISIN2': 'https://mylink2.pdf'}}

whereas expected output should be as below without URL piece.

{'ISIN1': 'https://mylink3.pdf', 'ISIN2': 'https://mylink2.pdf'}

Body:
Simple solution:

my_dic['URL']

Output:

{'ISIN1': 'https://mylink3.pdf', 'ISIN2': 'https://mylink2.pdf'}


问:
how to pass variable from php to sed?
I'm have a raspbian running on a raspberry pi3, I'm making a system that requires the person to choose the hostname by typing it into a field. And to swap the hostname, I need to change two files inside the /etc/ folder.

I have already managed to make these changes by the sed command, however since I want the person to choose the hostname, I made a form for PHP and wanted to take this variable by POST and pass it on to the sed command.

```<code><link rel="stylesheet" type="text/css" href="css/style.css">

<form method="POST">

<input  type="text" name="hostname">
<input type="submit" name="Comentar" value=" Salvar">

</form>

<?php

if(isset($_POST['Comentar'])){
        echo "botão foi clicado"."<br/>";
        $SEU_HOSTNAME = $_POST["hostname"];
        echo  "hostname digitado: ".$SEU_HOSTNAME;

    shell_exec ('

        cd /etc/
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hosts
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hostname
    ');

    }

?>
</code>```

Only {} appears in the file that is modified. Would anyone know what I could change?

答:
In PHP you need to use double quotes for a string if you want to pass a variables into it.

Additionally if you want to pass user input as a shell script argument, you need to sanitize it, otherwise user will be able to execute any shell script on your machine. In PHP you can use escapeshellarg for this.

Finally, your code should look like this:

$HOSTNAME=escapeshellarg("s/nome/$SEU_HOSTNAME/");
shell_exec ("
    cd /etc/
    sudo sed -i $HOSTNAME hosts
    sudo sed -i $HOSTNAME hostname
");
```

Title: how to pass variable from php to sed?

Body:
I'm have a raspbian running on a raspberry pi3, I'm making a system that requires the person to choose the hostname by typing it into a field. And to swap the hostname, I need to change two files inside the /etc/ folder.

I have already managed to make these changes by the sed command, however since I want the person to choose the hostname, I made a form for PHP and wanted to take this variable by POST and pass it on to the sed command.

<link rel="stylesheet" type="text/css" href="css/style.css">

<form method="POST">

<input  type="text" name="hostname">
<input type="submit" name="Comentar" value=" Salvar">

</form>

<?php

if(isset($_POST['Comentar'])){
        echo "botão foi clicado"."
";
        $SEU_HOSTNAME = $_POST["hostname"];
        echo  "hostname digitado: ".$SEU_HOSTNAME;

    shell_exec ('

        cd /etc/
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hosts
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hostname
    ');

    }

?>

Only {} appears in the file that is modified. Would anyone know what I could change?


问:
Calculate new column in pandas based on certain criteria
I am trying to multiple a two df based on certain values.

```<code>data = {'a':10,'b':20,'c':30} .
</code>```

df1:

```<code>id,tag,factor
1,a ,20
2,b ,22
3,c ,25
</code>```

my final result should look like something below:

```<code>id,factor,calc
1,20,200
2,22,440
3,24,750
</code>```

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

答:
You can use pandas.Series.map and pandas.DataFrame.drop

```<code>df['calc'] = df['factor'] * df['tag'].map(data)
df.drop('tag', axis=1, inplace=True)
</code>```

OUTPUT:

```<code>   id  factor  calc
0   1      20   200
1   2      22   440
2   3      25   750
</code>```

Body:
I am trying to multiple a two df based on certain values.

data = {'a':10,'b':20,'c':30} .

df1:

id,tag,factor
1,a ,20
2,b ,22
3,c ,25

my final result should look like something below:

id,factor,calc
1,20,200
2,22,440
3,24,750

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

Body:
You can use pandas.Series.map and pandas.DataFrame.drop

df['calc'] = df['factor'] * df['tag'].map(data)
df.drop('tag', axis=1, inplace=True)

OUTPUT:

   id  factor  calc
0   1      20   200
1   2      22   440
2   3      25   750


问:
Problem importing 3D Mesh by Gmsh in fipy
I am trying to import a 3D mesh produced with Gmsh in FiPy. A test with a 2D mesh worked fine. If the model then is extruded and imported with Gmsh3D I get an error message.

GmshException: Gmsh hasn't produced any cells! Check your Gmsh code.

I'm working on Win10 with Python 3.7.3, Fipy 3.1.3 and Gmsh 3.0.6 (as recommended).

The test2D.geo test file:

```<code>SetFactory("OpenCASCADE");
cl = 0.5;
bs = 2.;
Point(1) = {0, 0, 0, cl};
Point(2) = {0, bs, 0, cl};
Point(4) = { bs,  0, 0, cl};
Point(3) = {bs,  bs, 0, cl};
Line(5) = {1, 2};
Line(6) = {2, 3};
Line(7) = {3, 4};
Line(8) = {4, 1};

Line Loop(10) = {6, 7, 8, 5};
Plane Surface(1) = {10};
Extrude {0, 0, 1} {
  Surface{1};
}
</code>```

and:

from fipy import *
mesh = Gmsh3D("test2D.msh")
```

<p>The error message is:
GmshException: Gmsh hasn't produced any cells! Check your Gmsh code.</p>

<p>I don't see my mistake and hope someone can help me here.
Thanks in advance</p>

<p>Edited for the Gmsh output:</p>

```Gmsh output:
Info    : Running 'gmsh C:\Users\Tinka\AppData\Local\Temp\tmpj4zr8g_c.geo -3 -nopopup -format msh -o C:\Users\Tinka\AppData\Local\Temp\tmpnz1bp4vu.msh' [Gmsh 3.0.6, 1 node, max. 1 thread]
Info    : Started on Tue May 28 19:50:42 2019
Info    : Reading 'C:\Users\Tinka\AppData\Local\Temp\tmpj4zr8g_c.geo'...
Info    : Done reading 'C:\Users\Tinka\AppData\Local\Temp\tmpj4zr8g_c.geo'
Info    : Finalized high order topology of periodic connections
Info    : Meshing 1D...
Info    : Done meshing 1D (0 s)
Info    : Meshing 2D...
Info    : Done meshing 2D (0 s)
Info    : Meshing 3D...
Info    : Done meshing 3D (0 s)
Info    : 0 vertices 0 elements
Info    : Writing 'C:\Users\Tinka\AppData\Local\Temp\tmpnz1bp4vu.msh'...
Info    : Done writing 'C:\Users\Tinka\AppData\Local\Temp\tmpnz1bp4vu.msh'
Info    : Stopped on Tue May 28 19:50:42 2019
```

答:
I changed the name of the argument in Gmsh3D to test2D.geo and removed the first line from the geo file and things seem to be working.

```<code>>>> from fipy import Gmsh3D
>>> mesh = Gmsh("test2D.geo")
>>> print(mesh.cellCenters)
[[1.34821429 1.24404762 1.34821429 ...
...
</code>```

I'm not sure what the first line does, but I get Error   : Gmsh requires OpenCASCADE to add vertex and no vertices or cells are generated if it's included, but it isn't necessary for generating the mesh.

I think that FiPy Gmsh classes take both geo and msh formatted files, but the file name does need to refer to the actually file on disk.

I'm using FiPy version, 3.2+2.gccec299e, and Gmsh version, 3.0.6.

Body:
I am trying to import a 3D mesh produced with Gmsh in FiPy. A test with a 2D mesh worked fine. If the model then is extruded and imported with Gmsh3D I get an error message.

GmshException: Gmsh hasn't produced any cells! Check your Gmsh code.

I'm working on Win10 with Python 3.7.3, Fipy 3.1.3 and Gmsh 3.0.6 (as recommended).

The test2D.geo test file:

SetFactory("OpenCASCADE");
cl = 0.5;
bs = 2.;
Point(1) = {0, 0, 0, cl};
Point(2) = {0, bs, 0, cl};
Point(4) = { bs,  0, 0, cl};
Point(3) = {bs,  bs, 0, cl};
Line(5) = {1, 2};
Line(6) = {2, 3};
Line(7) = {3, 4};
Line(8) = {4, 1};

Line Loop(10) = {6, 7, 8, 5};
Plane Surface(1) = {10};
Extrude {0, 0, 1} {
  Surface{1};
}

and:

from fipy import *
mesh = Gmsh3D("test2D.msh")

The error message is:
GmshException: Gmsh hasn't produced any cells! Check your Gmsh code.

I don't see my mistake and hope someone can help me here.
Thanks in advance

Edited for the Gmsh output:

Gmsh output:
Info    : Running 'gmsh C:\Users\Tinka\AppData\Local\Temp\tmpj4zr8g_c.geo -3 -nopopup -format msh -o C:\Users\Tinka\AppData\Local\Temp\tmpnz1bp4vu.msh' [Gmsh 3.0.6, 1 node, max. 1 thread]
Info    : Started on Tue May 28 19:50:42 2019
Info    : Reading 'C:\Users\Tinka\AppData\Local\Temp\tmpj4zr8g_c.geo'...
Info    : Done reading 'C:\Users\Tinka\AppData\Local\Temp\tmpj4zr8g_c.geo'
Info    : Finalized high order topology of periodic connections
Info    : Meshing 1D...
Info    : Done meshing 1D (0 s)
Info    : Meshing 2D...
Info    : Done meshing 2D (0 s)
Info    : Meshing 3D...
Info    : Done meshing 3D (0 s)
Info    : 0 vertices 0 elements
Info    : Writing 'C:\Users\Tinka\AppData\Local\Temp\tmpnz1bp4vu.msh'...
Info    : Done writing 'C:\Users\Tinka\AppData\Local\Temp\tmpnz1bp4vu.msh'
Info    : Stopped on Tue May 28 19:50:42 2019

Body:
I changed the name of the argument in Gmsh3D to test2D.geo and removed the first line from the geo file and things seem to be working.

>>> from fipy import Gmsh3D
>>> mesh = Gmsh("test2D.geo")
>>> print(mesh.cellCenters)
[[1.34821429 1.24404762 1.34821429 ...
...

I'm not sure what the first line does, but I get Error   : Gmsh requires OpenCASCADE to add vertex and no vertices or cells are generated if it's included, but it isn't necessary for generating the mesh.

I think that FiPy Gmsh classes take both geo and msh formatted files, but the file name does need to refer to the actually file on disk.

I'm using FiPy version, 3.2+2.gccec299e, and Gmsh version, 3.0.6.


问:
Invalid column name when trying to insert alphanumeric value into database
Basically, I have a some code that takes either an (1) alphanumeric or (2) numeric serial number and increments them. Everything works for the numeric serial numbers, but when I try to insert the alphanumeric serial number, it gives me the "invalid column name" error.

I've looked at a lot of the "invalid column name" posts here and none of them seem to answer my question. I've put breakpoints in and ran the code for both cases (numeric and alphanumeric) and I'm getting the same datatypes. Basically everything seems to line up correctly, so I'm at a loss.

The following code shows how I increment for both cases. Note that for the alphanumeric increment, I am calling a method IncrementAlphaNumeric, which takes the variable 'Output', which is the result of a SQL query that sorts the table and gets the last serial number.

```<code>// Increment Numeric Serial Numbers
if (isNum)
{
    int lastNumber = Int32.Parse(Output);
    int[] ints = Enumerable.Range(lastNumber + 1, printQuantity).Select(i => (int)i / 1).ToArray();
    increments = ints.Select(x => x.ToString()).ToArray();
    output.AppendText("Serial numbers to print: " + string.Join(", ", increments));
}

// Increment AlphaNumeric Serial Numbers
if (!isNum)
{
    for (int i = 0; i < printQuantity; i++)
    {
         increments[i] = IncrementAlphaNumeric(Output);
         snList.Add(increments[i]);
         Output = increments[i];
    }
    output.AppendText("Serial numbers to print: " + string.Join(", ", increments));
 }
</code>```

Finally, I use Stringbuilder in order to insert the data into the database as follows:

```<code>// (5) Store new SNs in Database
StringBuilder sb = new StringBuilder();
foreach (string newSns in increments)
{
    sb.AppendLine("INSERT INTO [Manufacturing].[dbo].[Device.Devices]([SerialNumber],[DeviceTypeID]) VALUES(" + newSns + "," + dType +")");
}

using (SqlCommand insertCommand = new SqlCommand(sb.ToString(), cnn))
{
    var executeNonQuery = insertCommand.ExecuteNonQuery();
}
</code>```

Again, it works for numeric, but not for alphanumeric. When I put my breakpoints in and step through the code, the datatypes (Strings) are the same for each of the cases, numeric and alphanumeric.

The error message I'm getting is, again, "invalid column name". Basically, the expected results should be that the serial number, regardless of if it's numeric or alphanumeric, should be inserted into the correct table of the database, which is based on the device type (dType).

答:
As explained in comments, you should never concatenate strings to build your sql statement.

In your case I assume that you want to insert multiple records in your database using a single statement. This can be done also using parameters and manually building the VALUES part or your query (This syntax is available from Sql Server 2008)

```<code>// Sample values, replace them with your code that builds the increments array
string[] increments = new string[] {"VALUE1", "VALUE2","VALUE3", "VALUE4"};

// Invariant part of your query
string baseQuery = "INSERT INTO [Manufacturing].[dbo].[Device.Devices]([SerialNumber],[DeviceTypeID]) VALUES";

// Fixed value for the type
string dType = "42";

List<SqlParameter> prms = new List<SqlParameter>();
List<string> placeHolders = new List<String>();

// Build a list of parameter placeholders and a list of those parameter and their values
for(int x = 0; x < increments.Length; x++)
{
    placeHolders.Add($"(@p{x},{dType})");
    prms.Add(new SqlParameter { ParameterName = $"@p{x}", SqlDbType = SqlDbType.NVarChar, Value = increments[x]});
}

// Put the text together
string queryText = baseQuery + string.Join(",", placeHolders);
// This should be the final text
// INSERT INTO [Manufacturing].[dbo].[Device.Devices]([SerialNumber],[DeviceTypeID])
// VALUES(@p0,42),(@p1,42),(@p2,42),(@p3,42)

using (SqlCommand insertCommand = new SqlCommand(queryText, cnn))
{
    // Add all parameters to the command...
    insertCommand.Parameters.AddRange(prms.ToArray());
    var executeNonQuery = insertCommand.ExecuteNonQuery();
}
</code>```

Body:
Basically, I have a some code that takes either an (1) alphanumeric or (2) numeric serial number and increments them. Everything works for the numeric serial numbers, but when I try to insert the alphanumeric serial number, it gives me the "invalid column name" error.

I've looked at a lot of the "invalid column name" posts here and none of them seem to answer my question. I've put breakpoints in and ran the code for both cases (numeric and alphanumeric) and I'm getting the same datatypes. Basically everything seems to line up correctly, so I'm at a loss.

The following code shows how I increment for both cases. Note that for the alphanumeric increment, I am calling a method IncrementAlphaNumeric, which takes the variable 'Output', which is the result of a SQL query that sorts the table and gets the last serial number.

// Increment Numeric Serial Numbers
if (isNum)
{
    int lastNumber = Int32.Parse(Output);
    int[] ints = Enumerable.Range(lastNumber + 1, printQuantity).Select(i => (int)i / 1).ToArray();
    increments = ints.Select(x => x.ToString()).ToArray();
    output.AppendText("Serial numbers to print: " + string.Join(", ", increments));
}

// Increment AlphaNumeric Serial Numbers
if (!isNum)
{
    for (int i = 0; i < printQuantity; i++)
    {
         increments[i] = IncrementAlphaNumeric(Output);
         snList.Add(increments[i]);
         Output = increments[i];
    }
    output.AppendText("Serial numbers to print: " + string.Join(", ", increments));
 }

Finally, I use Stringbuilder in order to insert the data into the database as follows:

// (5) Store new SNs in Database
StringBuilder sb = new StringBuilder();
foreach (string newSns in increments)
{
    sb.AppendLine("INSERT INTO [Manufacturing].[dbo].[Device.Devices]([SerialNumber],[DeviceTypeID]) VALUES(" + newSns + "," + dType +")");
}

using (SqlCommand insertCommand = new SqlCommand(sb.ToString(), cnn))
{
    var executeNonQuery = insertCommand.ExecuteNonQuery();
}

Again, it works for numeric, but not for alphanumeric. When I put my breakpoints in and step through the code, the datatypes (Strings) are the same for each of the cases, numeric and alphanumeric.

The error message I'm getting is, again, "invalid column name". Basically, the expected results should be that the serial number, regardless of if it's numeric or alphanumeric, should be inserted into the correct table of the database, which is based on the device type (dType).

Body:
As explained in comments, you should never concatenate strings to build your sql statement.

In your case I assume that you want to insert multiple records in your database using a single statement. This can be done also using parameters and manually building the VALUES part or your query (This syntax is available from Sql Server 2008)

// Sample values, replace them with your code that builds the increments array
string[] increments = new string[] {"VALUE1", "VALUE2","VALUE3", "VALUE4"};

// Invariant part of your query
string baseQuery = "INSERT INTO [Manufacturing].[dbo].[Device.Devices]([SerialNumber],[DeviceTypeID]) VALUES";

// Fixed value for the type
string dType = "42";

List<SqlParameter> prms = new List<SqlParameter>();
List<string> placeHolders = new List<String>();

// Build a list of parameter placeholders and a list of those parameter and their values
for(int x = 0; x < increments.Length; x++)
{
    placeHolders.Add($"(@p{x},{dType})");
    prms.Add(new SqlParameter { ParameterName = $"@p{x}", SqlDbType = SqlDbType.NVarChar, Value = increments[x]});
}

// Put the text together
string queryText = baseQuery + string.Join(",", placeHolders);
// This should be the final text
// INSERT INTO [Manufacturing].[dbo].[Device.Devices]([SerialNumber],[DeviceTypeID])
// VALUES(@p0,42),(@p1,42),(@p2,42),(@p3,42)

using (SqlCommand insertCommand = new SqlCommand(queryText, cnn))
{
    // Add all parameters to the command...
    insertCommand.Parameters.AddRange(prms.ToArray());
    var executeNonQuery = insertCommand.ExecuteNonQuery();
}


问:
Execute BeforeEach Hook before Before Hook in Mocha
I want to create a beforeEach Hook that is executed before a before Hook.

Basically I want the following behaviour:

```<code>beforeEach(() => {
  console.log('beforeEach')
})

describe('tests', () => {
  before(() => {
    console.log('before')
  })

  it('test 1', () => {
    console.log('it')
  })
})
</code>```

And I get:

```<code>before
beforeEach
it
</code>```

But the output I want is:

```<code>beforeEach
before
it
</code>```

What would be the correct structure to get the desired behaviour?

Workaround

Currently I found a workaround using two nested beforeEach:

```<code>beforeEach(() => {
  console.log('beforeEach1')
})

describe('tests', () => {
  beforeEach(() => {
    console.log('beforeEach2')
  })

  it('test 1', () => {
    console.log('it')
  })
})
</code>```

Which output is:

```<code>beforeEach1
beforeEach2
it
</code>```

答:
I am not sure of this (I have not tested it) but from the doc it seems that your root-level beforeEach probably does not do what you may think.

```<code>...
run spec file/s
  |
  |--------------> per spec file
    suite callbacks (e.g., 'describe')
    |
    'before' root-level pre-hook
    |
    'before' pre-hook
    |
    |--------------> per test
      'beforeEach' root-level pre-hook
      |
      'beforeEach' pre-hook
      ...
</code>```

From the above picture, you can see that for each describe the before root-level pre-hook is called. Just turn your root-level beforeEach in a before and it should be solved.

The general rule is that before callback always come "before"(no pun intended) the beforeEach callback, independently from the level they are defined in.

Body:
I want to create a beforeEach Hook that is executed before a before Hook.

Basically I want the following behaviour:

beforeEach(() => {
  console.log('beforeEach')
})

describe('tests', () => {
  before(() => {
    console.log('before')
  })

  it('test 1', () => {
    console.log('it')
  })
})

And I get:

before
beforeEach
it

But the output I want is:

beforeEach
before
it

What would be the correct structure to get the desired behaviour?

Workaround

Currently I found a workaround using two nested beforeEach:

beforeEach(() => {
  console.log('beforeEach1')
})

describe('tests', () => {
  beforeEach(() => {
    console.log('beforeEach2')
  })

  it('test 1', () => {
    console.log('it')
  })
})

Which output is:

beforeEach1
beforeEach2
it

Body:
I am not sure of this (I have not tested it) but from the doc it seems that your root-level beforeEach probably does not do what you may think.

...
run spec file/s
  |
  |--------------> per spec file
    suite callbacks (e.g., 'describe')
    |
    'before' root-level pre-hook
    |
    'before' pre-hook
    |
    |--------------> per test
      'beforeEach' root-level pre-hook
      |
      'beforeEach' pre-hook
      ...

From the above picture, you can see that for each describe the before root-level pre-hook is called. Just turn your root-level beforeEach in a before and it should be solved.

The general rule is that before callback always come "before"(no pun intended) the beforeEach callback, independently from the level they are defined in.


问:
What dos the ranges means in the coverage json file?
After exporting the json file from the Coverage tool in DevChrome Tools I got this code (only a sample):

```<code>[
  {
    "url": "https://www.cfcarehospitalar.com.br/skin/frontend/codazon_fastest/default/css/styles.css",
    "ranges": [
      {
        "start": 153,
        "end": 237
      },
</code>```

Does this ranges means the line of the styles.css file?

This file is minified and when I unminified all green selectors scrapped by the coverage tool doesn't belong to the ranges json file is recording.

So I really do not understand what it means. I'll appreciate some explanation. thanks!

答:
The ranges represent the sections of used code.

url is the file that was analyzed, text is the full text of the file. ranges are the substrings of text that were used.

If you take all of the substrings and concatenate them together, you'll get the used code.

Here's some pseudocode to demonstrate how you extract the used code:

```<code>const file = json[0];
const text = file.text;
let usedCode = '';
for (let i = 0; i < ranges.length; i++) {
  const range = ranges[i];
  usedCode += text.substring(range.start, range.end);
}
</code>```

https://developers.google.com/web/updates/2019/01/devtools#coverage

Body:
After exporting the json file from the Coverage tool in DevChrome Tools I got this code (only a sample):

[
  {
    "url": "https://www.cfcarehospitalar.com.br/skin/frontend/codazon_fastest/default/css/styles.css",
    "ranges": [
      {
        "start": 153,
        "end": 237
      },

Does this ranges means the line of the styles.css file?

This file is minified and when I unminified all green selectors scrapped by the coverage tool doesn't belong to the ranges json file is recording.

So I really do not understand what it means. I'll appreciate some explanation. thanks!

Body:
The ranges represent the sections of used code.

url is the file that was analyzed, text is the full text of the file. ranges are the substrings of text that were used.

If you take all of the substrings and concatenate them together, you'll get the used code.

Here's some pseudocode to demonstrate how you extract the used code:

const file = json[0];
const text = file.text;
let usedCode = '';
for (let i = 0; i < ranges.length; i++) {
  const range = ranges[i];
  usedCode += text.substring(range.start, range.end);
}

https://developers.google.com/web/updates/2019/01/devtools#coverage


问:
How does aud claim value set in ROPC access token
I am generating Authorization token to run our API tests using below method.

```<code>    /// <summary>
    /// This method returns the Bearer token with User as a claim
    /// </summary>
    /// <param name="tenantId">Tenant Id for the environment in use</param>
    /// <param name="userName">Email Id of the user</param>
    /// <param name="password">Password of the user</param>
    /// <returns>string with the complete Bearer token</returns>
    public async Task<string> GetAccessTokenROPC(string tenantId, string userName, string password)
    {
        string tokenUrl = string.Concat("https://login.microsoftonline.com/", tenantId, "/oauth2/v2.0/token");
        var req = new HttpRequestMessage(HttpMethod.Post, tokenUrl)
        {
            Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["client_id"] = this.utils.GetClientId(),
                ["scope"] = "user.read openid profile email offline_access",
                ["client_secret"] = this.utils.GetClientSecret(),
                ["username"] = userName,
                ["password"] = password,
                ["grant_type"] = "password"
            })
        };
</code>```

The response generates successfully and has access token with below claims.
My query is which part of code in above method takes care of aud claim and how does it is set https://graph.microsoft.com?:

```<code>{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/fa774de7-cc34-4a2d-838f-b83fdexxxxxxx/",
  "iat": 1558960514,
  "nbf": 1558960514,
  "exp": 1558964414,
  "acct": 0,
  "acr": "1",
  "aio":
  .
  .
  .
}
</code>```

答:
You asked for user.read scope, which is the short form for https://graph.microsoft.com/user.read.

So you asked for a token to call MS Graph API. And you got a token to pass along in requests to there.
You'd specify scopes for another API if you want an access token with a different audience.

Body:
I am generating Authorization token to run our API tests using below method.

    ///
    /// This method returns the Bearer token with User as a claim
    ///
    /// <param name="tenantId">Tenant Id for the environment in use</param>
    /// <param name="userName">Email Id of the user</param>
    /// <param name="password">Password of the user</param>
    /// <returns>string with the complete Bearer token</returns>
    public async Task<string> GetAccessTokenROPC(string tenantId, string userName, string password)
    {
        string tokenUrl = string.Concat("https://login.microsoftonline.com/", tenantId, "/oauth2/v2.0/token");
        var req = new HttpRequestMessage(HttpMethod.Post, tokenUrl)
        {
            Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["client_id"] = this.utils.GetClientId(),
                ["scope"] = "user.read openid profile email offline_access",
                ["client_secret"] = this.utils.GetClientSecret(),
                ["username"] = userName,
                ["password"] = password,
                ["grant_type"] = "password"
            })
        };

The response generates successfully and has access token with below claims.
My query is which part of code in above method takes care of aud claim and how does it is set https://graph.microsoft.com?:

{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/fa774de7-cc34-4a2d-838f-b83fdexxxxxxx/",
  "iat": 1558960514,
  "nbf": 1558960514,
  "exp": 1558964414,
  "acct": 0,
  "acr": "1",
  "aio":
  .
  .
  .
}


问:
Grab every checked items from a custom listview
I need to grab every checked items from a ListView with custom items containing a checkbox each in a List<> variable. That ListView is filled dynamically using another List<>.

So far I'm at least trying to get every checked items in my list when clicking on a FAB. I have looked for several solutions, but nothing worked. Sticking to a SparseBooleanArray seems to avoid having any errors and crashes.

Here is the list activity class:

        listViewWithCheckBox.setChoiceMode(listViewWithCheckBox.CHOICE_MODE_MULTIPLE);
        listViewWithCheckBox.setAdapter(new CustomAdapter(this, listViewItems));

        FloatingActionButton confirmFAB = findViewById(R.id.inviter_liste_confirm_fab);
        confirmFAB.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SparseBooleanArray checked = listViewWithCheckBox.getCheckedItemPositions();
                System.out.println(listViewWithCheckBox.getCheckedItemPositions());
                System.out.println(listViewWithCheckBox.getCount());
                for (int i = 0; i < checked.size(); i++) {
                    if (checked.valueAt(i) == true) {
                        String tag = String.valueOf(listViewWithCheckBox.getItemAtPosition(checked.keyAt(i)));
                        Toast.makeText(getApplicationContext(), "" + tag, Toast.LENGTH_LONG).show();
                        Log.i("xxxx", i + " " + tag);
                    }
                }
            }
        });
```

<p>And here is my custom adapter which implements ListAdapter, excluding empty functions:</p>

<pre class="lang-java prettyprint-override"><code>    ArrayList<ItemObjet> arrayList;
    Context context;

    public CustomAdapter(Context context, ArrayList<ItemObjet> arrayList) {
        this.arrayList=arrayList;
        this.context=context;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        return true;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemObjet subjectData=arrayList.get(position);
        if(convertView==null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView=layoutInflater.inflate(R.layout.list_people_select_item, null);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            TextView tittle=convertView.findViewById(R.id.inviter_list_nom);
            tittle.setText(subjectData.getName());
        }
        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }
    @Override
    public int getViewTypeCount() {
        return arrayList.size();
    }
    @Override
    public boolean isEmpty() {
        return false;
    }
</code>```

答:
Add in a callback for your custom adapter like this.

And then in your activity class, add a global variable to maintain an ArrayList of checked items in the list. Now, override the interface callback when you set the adapter in your activity like this.

Body:
I need to grab every checked items from a ListView with custom items containing a checkbox each in a List<> variable. That ListView is filled dynamically using another List<>.

So far I'm at least trying to get every checked items in my list when clicking on a FAB. I have looked for several solutions, but nothing worked. Sticking to a SparseBooleanArray seems to avoid having any errors and crashes.

Here is the list activity class:

        listViewWithCheckBox.setChoiceMode(listViewWithCheckBox.CHOICE_MODE_MULTIPLE);
        listViewWithCheckBox.setAdapter(new CustomAdapter(this, listViewItems));

        FloatingActionButton confirmFAB = findViewById(R.id.inviter_liste_confirm_fab);
        confirmFAB.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SparseBooleanArray checked = listViewWithCheckBox.getCheckedItemPositions();
                System.out.println(listViewWithCheckBox.getCheckedItemPositions());
                System.out.println(listViewWithCheckBox.getCount());
                for (int i = 0; i < checked.size(); i++) {
                    if (checked.valueAt(i) == true) {
                        String tag = String.valueOf(listViewWithCheckBox.getItemAtPosition(checked.keyAt(i)));
                        Toast.makeText(getApplicationContext(), "" + tag, Toast.LENGTH_LONG).show();
                        Log.i("xxxx", i + " " + tag);
                    }
                }
            }
        });

And here is my custom adapter which implements ListAdapter, excluding empty functions:

    ArrayList<ItemObjet> arrayList;
    Context context;

    public CustomAdapter(Context context, ArrayList<ItemObjet> arrayList) {
        this.arrayList=arrayList;
        this.context=context;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        return true;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemObjet subjectData=arrayList.get(position);
        if(convertView==null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView=layoutInflater.inflate(R.layout.list_people_select_item, null);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            TextView tittle=convertView.findViewById(R.id.inviter_list_nom);
            tittle.setText(subjectData.getName());
        }
        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }
    @Override
    public int getViewTypeCount() {
        return arrayList.size();
    }
    @Override
    public boolean isEmpty() {
        return false;
    }