问:
Deleting N matching patterns using sed, awk, perl etc
I have this situation, the file contains

```<code>abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5
</code>```

I would like to delete whenever I find matching 2 lines of

```<code>abcd
vwxyz
</code>```

to be deleted so that it becomes

```<code>abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

答:
This might work for you (GNU sed):

```<code>sed 'N;/^abcd\nvwxyz$/d;P;D' file
</code>```

Create a 2 line window  throughout the length of the file and delete that window if the current window matches the required strings. Otherwise print/delete the first line of the window and append another line, repeat.

This can be extended to match n lines:

```<code>sed ':a;N;s/[^\n]\+/&/2;Ta;/^abcd\nvwxyz$/d;P;D' file
</code>```

generalised for 2 lines:

Or:

```<code>sed ':a;N;s/[^\n]\+/&/3;Ta;/^line1\nline2\nline3$/d;P;D' file
</code>```

for 3 lines, etc.

An alternative:

```<code>sed -z 's/^abcd\nvwxyz\n//mg' file
</code>```

Body:
I have this situation, the file contains

abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5

I would like to delete whenever I find matching 2 lines of

abcd
vwxyz

to be deleted so that it becomes

abcd
line1
line2
line3
vwxyz
line4
line5

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

Body:
This might work for you (GNU sed):

sed 'N;/^abcd\nvwxyz$/d;P;D' file

Create a 2 line window  throughout the length of the file and delete that window if the current window matches the required strings. Otherwise print/delete the first line of the window and append another line, repeat.

This can be extended to match n lines:

sed ':a;N;s/[^\n]\+/&/2;Ta;/^abcd\nvwxyz$/d;P;D' file

generalised for 2 lines:

Or:

sed ':a;N;s/[^\n]\+/&/3;Ta;/^line1\nline2\nline3$/d;P;D' file

for 3 lines, etc.

An alternative:

sed -z 's/^abcd\nvwxyz\n//mg' file


来源: stackexchange

问:
Validating brackets presence when some math logic found in String
At the moment I work with some logical and mathematical expressions given as a String. Unfortunately, there is a need to use brackets on expressions when using chars: '&' and '|' (used instead of '||').

Valid expressions:

(x + 2) & (y * 4) | (i - 4)
(5 > 4) | (6y + 4)

Invalid expressions:

x + 2 & y * 4 | i - 4
5 > 4 | 6y + 4

I have tried to check String with RegEx, something like:

[)][ \t\n\r]*[&][ \t\n\r]*[(] makes sense.

The problem is: how to find all '&' and '|' chars and find presence of near brackets?

Edit: I have a solution based on searching for index of those characters, then going in both ways and looking for brackets. Maybe I can make it in more simple way with RegEx?

答:
Relatively simple solution:

split on & and |;

trim all sub-expressions;

check whether they all start with ( and end with ).

Snippet:

```<code>String s = "(x + 2) & (y * 4) | (i - 4)";

boolean valid = Arrays.stream(s.split("[&|]"))
                      .map(String::trim)
                      .allMatch(p -> p.startsWith("(") && p.endsWith(")"));
</code>```

If you need to address more complex scenarios than the ones presented in your question (nested expressions etc.), you'll need to write a parser.

ContentLicense: CC BY-SA 4.0

Body:
Relatively simple solution:

split on & and |;

trim all sub-expressions;

check whether they all start with ( and end with ).

Snippet:

String s = "(x + 2) & (y * 4) | (i - 4)";

boolean valid = Arrays.stream(s.split("[&|]"))
                      .map(String::trim)
                      .allMatch(p -> p.startsWith("(") && p.endsWith(")"));

If you need to address more complex scenarios than the ones presented in your question (nested expressions etc.), you'll need to write a parser.


问:
alert box in asp.net web application
how can i use an alert box in asp.net web application without using javascript with Yes/NO option, much like messagebox in desktop (windows) application.

Thanks

答: You can't create one - although you could make it look like one by using an overlay div and "message box" div. The additional content would need to be controlled on the server so it would require a POST request to the server when displaying and another for submitting the Yes/No click.

ContentLicense: CC BY-SA 3.0

Title: alert box in asp.net web application


问:
Android app internal test track open/launch button is not available
I am trying test my first android application using Internal test track. As you can see on screenshot, I was able to install it on my device but somehow it doesn't show me Open button. Any suggestions?
P.S. During the development I was able to run my application on same device(Samsung Galaxy S7)

Device Android version: 8.0.0

```<code>buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 26
        supportLibVersion = "28.0.0"
    }
    ...
</code>```

答:
My issue was connected with the AndroidManifest.xml file.
In past the <data android:scheme="@string/fb_login_protocol_scheme" /> tag was inside of the <activity android:name=".MainActivity" tag

```<code><application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    </application>
</code>```

while now I created two more activity tags and moved the <data android:scheme="@string/fb_login_protocol_scheme" /> tag under the <activity android:name="com.facebook.CustomTabActivity" tag

```<code><application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

      <activity android:name="com.facebook.FacebookActivity"
                android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
                android:label="@string/app_name" />
      <activity android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
      </activity>
    </application>
</code>```

The interesting thing was that generated APK with first version of the AndroidManifest.xml worked fine on real device(without installing it from Play Store) and I was able to login with facebook through the app. But Play Store doesn't let me open the app and didn't show any warning or error messages.
With second version of the AndroidManifest.xml it works fine in both cases.

Body:
I am trying test my first android application using Internal test track. As you can see on screenshot, I was able to install it on my device but somehow it doesn't show me Open button. Any suggestions?
P.S. During the development I was able to run my application on same device(Samsung Galaxy S7)

Device Android version: 8.0.0

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 26
        supportLibVersion = "28.0.0"
    }
    ...

Body:
My issue was connected with the AndroidManifest.xml file.
In past the <data android:scheme="@string/fb_login_protocol_scheme" /> tag was inside of the <activity android:name=".MainActivity" tag

<application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    </application>

while now I created two more activity tags and moved the <data android:scheme="@string/fb_login_protocol_scheme" /> tag under the <activity android:name="com.facebook.CustomTabActivity" tag

<application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

      <activity android:name="com.facebook.FacebookActivity"
                android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
                android:label="@string/app_name" />
      <activity android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
      </activity>
    </application>

The interesting thing was that generated APK with first version of the AndroidManifest.xml worked fine on real device(without installing it from Play Store) and I was able to login with facebook through the app. But Play Store doesn't let me open the app and didn't show any warning or error messages.
With second version of the AndroidManifest.xml it works fine in both cases.


问:
Solr highlighting breaks when qf and hl.fl are different
I am searching a query say "nurses" on some copy fields a_cpy,b_cpy,c_cpy which are copies of field a,b,c respectively.

The values indexed in filed a,b,c are stemmed while values in a_cpy,b_cpy,c_cpy are not stemmed.

My hl.fl value is a,b,c while qf is a_cpy,b_cpy,c_cpy and hl.q is "nurses".

The response from solr does not highlight "nurses" but highlights correct when search term is "nurse".

Is this expected behavior or is there something wrong with my method?

答:
As you have already mentioned that one field is having stemming filter and other field is not having the stemming.

To answer your question this is the correct behavior and nothing is wrong with it.
We will see with below example why this happens bu using the solr analysis.

For the field named text, will use the below field type which does not have the stemming filter factory.

```<code><field name="text" type="text_general"/>

<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.SynonymGraphFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
  </fieldType>
</code>```

When you analyse the data for the above text field in solr analysis page, you will find that it does not match the data.

It does not match because the indexed data(tokens created at the end of filter factory) is different than the query value.

For the field named text_copy_stemmed, will use the below field type which is has stemming filter factory.
We have used <filter class="solr.KStemFilterFactory"/> while indexing.

```<code><field name="text_copy_stemmed" type="text_general_stemmed"/>

<copyField source="text" dest="text_copy_stemmed" indexed="true" stored="true"/>

<fieldType name="text_general_stemmed" class="solr.TextField" positionIncrementGap="100" multiValued="true">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.KStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.SynonymGraphFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
  </fieldType>
</code>```

When you analyse the data for the above text_copy_stemmed field in solr analysis page, you will find that it does match the data.

The queried data is matched as it finds the token in solr. Verify the tokens created at the end of the filter factory and the one passed through the query.

I have indexed the below JSON and queried the same data with highlighting.

```<code>{
"id":"gb18030-example.xml",
"text":"jump jumping jumped organizational organizations",
"text_copy_stemmed":"jump jumping jumped organizational organizations"
}
</code>```

Body:
As you have already mentioned that one field is having stemming filter and other field is not having the stemming.

To answer your question this is the correct behavior and nothing is wrong with it.
We will see with below example why this happens bu using the solr analysis.

For the field named text, will use the below field type which does not have the stemming filter factory.

<field name="text" type="text_general"/>

<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.SynonymGraphFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
  </fieldType>

When you analyse the data for the above text field in solr analysis page, you will find that it does not match the data.

It does not match because the indexed data(tokens created at the end of filter factory) is different than the query value.

For the field named text_copy_stemmed, will use the below field type which is has stemming filter factory.
We have used <filter class="solr.KStemFilterFactory"/> while indexing.

<field name="text_copy_stemmed" type="text_general_stemmed"/>

<copyField source="text" dest="text_copy_stemmed" indexed="true" stored="true"/>

<fieldType name="text_general_stemmed" class="solr.TextField" positionIncrementGap="100" multiValued="true">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.KStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.SynonymGraphFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
  </fieldType>

When you analyse the data for the above text_copy_stemmed field in solr analysis page, you will find that it does match the data.

The queried data is matched as it finds the token in solr. Verify the tokens created at the end of the filter factory and the one passed through the query.

I have indexed the below JSON and queried the same data with highlighting.

{
"id":"gb18030-example.xml",
"text":"jump jumping jumped organizational organizations",
"text_copy_stemmed":"jump jumping jumped organizational organizations"
}


问:
DOM element to corresponding vue.js component
How can I find the vue.js component corresponding to a DOM element?

If I have

```<code>element = document.getElementById(id);
</code>```

Is there a vue method equivalent to the jQuery

```<code>$(element)
</code>```

答:
I found this snippet here. The idea is to go up the DOM node hierarchy until a __vue__ property is found.

```<code>function getVueFromElement(el) {
  while (el) {
    if (el.__vue__) {
      return el.__vue__
    } else {
      el = el.parentNode
    }
  }
}
</code>```

In Chrome:

Body:
How can I find the vue.js component corresponding to a DOM element?

If I have

element = document.getElementById(id);

Is there a vue method equivalent to the jQuery

$(element)

Body:
I found this snippet here. The idea is to go up the DOM node hierarchy until a __vue__ property is found.

function getVueFromElement(el) {
  while (el) {
    if (el.__vue__) {
      return el.__vue__
    } else {
      el = el.parentNode
    }
  }
}

In Chrome:


问:
How to Apply filter to list without resetting control values after search button click?
I have a List of Persons and  filtration controls in a form with search button. When search button is clicked list populated with filtered data but search controls also loose their selected values. I'm not sure this is the best way to do this.

I have tried splitting view into partial and main view i.e. List of Persons is in Partial view and Filtration Controls are in main view.

List should be filtered without loosing search controls values. What should be the best practice to accomplish this task? Sample Image >> list with filtration controls

答:
I would suggest to use ViewBag to store the data in the controller first, like this:

```<code>    public ActionResult YourSearchPage()
    {
        //Bind the data to a list here
        List<YourResultType> result = //Get from DB
        return View(result);
    }

    //When the user clicks the "Search" button
    [HttpPost]
    public ActionResult YourSearchPage(string keyword, int listingType...)
    {
        //Bind the data to a list here
        List<YourResultType> result = //Get from DB
        ViewBag.keyword = keyword;
        ViewBag.listingType = listingType;
        //Filter the list
        return View(result);
    }
</code>```

And on the view, bind the value to the controls like below:

```<code><input type="text" id="keyword" class="keyword" value="@ViewBag.keyword" style="width: 80%;"/>
</code>```

Body:
I would suggest to use ViewBag to store the data in the controller first, like this:

    public ActionResult YourSearchPage()
    {
        //Bind the data to a list here
        List<YourResultType> result = //Get from DB
        return View(result);
    }

    //When the user clicks the "Search" button
    [HttpPost]
    public ActionResult YourSearchPage(string keyword, int listingType...)
    {
        //Bind the data to a list here
        List<YourResultType> result = //Get from DB
        ViewBag.keyword = keyword;
        ViewBag.listingType = listingType;
        //Filter the list
        return View(result);
    }

And on the view, bind the value to the controls like below:

<input type="text" id="keyword" class="keyword" value="@ViewBag.keyword" style="width: 80%;"/>


问:
How to add a null value in the group_concat if the record does not exist?
I have this SQL query with substring_index and group_concat but the results I get does not give the right location of the values because the values does not exist.

I need to add a null or zero value in order to have the right location of the values in the sql result.

In the table there are three lid (1, 2, 3). The lid should be the basis count of the P's (P1, P2, P3) for the substring_index.

This is the table:

```<code>lid   class_id   class          total
-----  -------    -----        -----
  1     73       Leader         10000
  1     77       Consultant     8000
  1     83       Coordinator    6000
  2     73       Leader         20000
  2     76       Staff          8000
  2     77       Consultant     10000
  3     73       Leader         30000
  3     78       Team Leader    8000
</code>```

This is the SQL query I used to group_concat for the totals and substring_index to separate the grouped values with their each column (P1, P2, P3)

```<code>SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id
</code>```

This is the result of the above query:

```<code>class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          2       8000
   77      Consultant     1,2     8000    10000
   78      Team Leader    3       8000
   83      Coordinator    1       6000
</code>```

The lids should always have three count even though the record does not exists, a zero or null value should be added. How to do the adding of null value?

This is the expected result I need.

```<code> class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          0,2,0     0     8000      0
   77      Consultant     1,2,0    8000   10000     0
   78      Team Leader    0,0,3     0       0      8000
   83      Coordinator    1,0,0    6000     0       0
</code>```

答:
Use else 0 in case expression

```<code>SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) else 0 END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) else 0 END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) else 0 END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id
</code>```

Body:
I have this SQL query with substring_index and group_concat but the results I get does not give the right location of the values because the values does not exist.

I need to add a null or zero value in order to have the right location of the values in the sql result.

In the table there are three lid (1, 2, 3). The lid should be the basis count of the P's (P1, P2, P3) for the substring_index.

This is the table:

lid   class_id   class          total
-----  -------    -----        -----
  1     73       Leader         10000
  1     77       Consultant     8000
  1     83       Coordinator    6000
  2     73       Leader         20000
  2     76       Staff          8000
  2     77       Consultant     10000
  3     73       Leader         30000
  3     78       Team Leader    8000

This is the SQL query I used to group_concat for the totals and substring_index to separate the grouped values with their each column (P1, P2, P3)

SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id

This is the result of the above query:

class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          2       8000
   77      Consultant     1,2     8000    10000
   78      Team Leader    3       8000
   83      Coordinator    1       6000

The lids should always have three count even though the record does not exists, a zero or null value should be added. How to do the adding of null value?

This is the expected result I need.

 class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          0,2,0     0     8000      0
   77      Consultant     1,2,0    8000   10000     0
   78      Team Leader    0,0,3     0       0      8000
   83      Coordinator    1,0,0    6000     0       0

Body:
Use else 0 in case expression

SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) else 0 END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) else 0 END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) else 0 END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id


问:
Performing database opeation On Model propeties in Mvc ViewModel
```<code> public class CityViewModel
    {
        public List<City> GetCities { get; set; }
        public City CityDetail { get; set; }
    }
</code>```

This is my ViewModel and i want suggestions about if its a good way to use datbase operation directly on Model property .For example

```<code>public List<City> GetCities
{
         get{
            return {some method for getting list from database};
            }
         set
            {
            }
</code>```

}

The only requirement is am gonna need that list multiple times and i don't want to keep calling same line to access that list from database everywhere.And just want whenever i create new instance of this viewmodel i can get that list automatically.So is it a good way for that?

答:
ViewModels are pocos, they should not to be able to access the database themselves, they should not be able to access models themselves either, also its not a viewmodel's responsibility to populate itself. Ideally your data access layer should map your models into viewmodels and viewmodels in models

A CityViewModel should be a copy of the City model with some changes and the GetCities should be a method in your data access layer something like:-

```<code>public List<CityViewModel> GetCities()
{
    var cities = cityRepository.GetAll();

    List<CityViewModel> cityViewModelList = new List<CityViewModel>();

    foreach(var city in cities)
    {
        CityViewModel cityViewModel = new CityViewModel
        {
            //map your properties
        }
        cityViewModelList.Add(cityViewModel);
    }
    return cityViewModelList;
}
</code>```

then whenever you need a list of cities you just call the GetCities hence no repetition of code

Body:
 public class CityViewModel
    {
        public List<City> GetCities { get; set; }
        public City CityDetail { get; set; }
    }

This is my ViewModel and i want suggestions about if its a good way to use datbase operation directly on Model property .For example

public List<City> GetCities
{
         get{
            return {some method for getting list from database};
            }
         set
            {
            }

}

The only requirement is am gonna need that list multiple times and i don't want to keep calling same line to access that list from database everywhere.And just want whenever i create new instance of this viewmodel i can get that list automatically.So is it a good way for that?

Body:
ViewModels are pocos, they should not to be able to access the database themselves, they should not be able to access models themselves either, also its not a viewmodel's responsibility to populate itself. Ideally your data access layer should map your models into viewmodels and viewmodels in models

A CityViewModel should be a copy of the City model with some changes and the GetCities should be a method in your data access layer something like:-

public List<CityViewModel> GetCities()
{
    var cities = cityRepository.GetAll();

    List<CityViewModel> cityViewModelList = new List<CityViewModel>();

    foreach(var city in cities)
    {
        CityViewModel cityViewModel = new CityViewModel
        {
            //map your properties
        }
        cityViewModelList.Add(cityViewModel);
    }
    return cityViewModelList;
}

then whenever you need a list of cities you just call the GetCities hence no repetition of code


问:
How to trigger an event when any jQuery UI dialog is closed?
I would like to make it so that when a jQuery UI dialog is closed, the document's focus event is fired. This would preferably not be tied to each dialog but to the page itself whenever any dialog closes.

How can I do this?

答:
```<code>$( ".selector" ).dialog({
   close: function(event, ui) { $('#txt').focus(); }
});
</code>```


问:
Google Analytics Measurement Protocol not working
I want to track an application that runs in different environments:

phonegap build

node-webkit app

website

In order to use one tracking mechanism for all I thought it would be a good idea to use  the  "Measurement Protocol"

I set up a new tracking property (type Website) and performed multiple requests to the www.google-analytics.com/collect site as described in their devguide. I always get the Status 200 (OK) from my POST request, but unfortunately I can´t see any tracking information coming in to my GA account.

Here is what the request looks like (Build with Postman plugin for Chrome):

```<code>POST /collect?v=1&tid=UA-29xxxxxx-2&cid=35009a79-1a05-49d7-b876-2b884d0f825b&t=pageview&dh=mysite.com&dp=%2Fhome&dt=Homepage&an=myapp HTTP/1.1
Host: www.google-analytics.com
Cache-Control: no-cache
</code>```

Basically I´m sending these parameters:

```<code>v=1
&tid=UA-29xxxxxx-2
&cid=35009a79-1a05-49d7-b876-2b884d0f825b
&t=pageview
&dh=mysite.com
&dp=%2Fhome
&dt=Homepage
&an=myapp
</code>```

I also tried to create a "Mobile Application" in Google Analytics and use that tracking id instead. Same result here - no tracking information in Google Analytics.

Does anyone know, how to perform this tracking requests successfully or if there is a debug-option so that I can at least see, why the tracking call is not saved? Thanks!

答: Had the same problem: whatever I POSTed, it did not show up in GA. Debug API successfully validated my hits. Finally, I found out what was missing: you must send a user agent string (parameter ua), too.</p>

Body:
I want to track an application that runs in different environments:

phonegap build

node-webkit app

website

In order to use one tracking mechanism for all I thought it would be a good idea to use  the  "Measurement Protocol"

I set up a new tracking property (type Website) and performed multiple requests to the www.google-analytics.com/collect site as described in their devguide. I always get the Status 200 (OK) from my POST request, but unfortunately I can´t see any tracking information coming in to my GA account.

Here is what the request looks like (Build with Postman plugin for Chrome):

POST /collect?v=1&tid=UA-29xxxxxx-2&cid=35009a79-1a05-49d7-b876-2b884d0f825b&t=pageview&dh=mysite.com&dp=%2Fhome&dt=Homepage&an=myapp HTTP/1.1
Host: www.google-analytics.com
Cache-Control: no-cache

Basically I´m sending these parameters:

v=1
&tid=UA-29xxxxxx-2
&cid=35009a79-1a05-49d7-b876-2b884d0f825b
&t=pageview
&dh=mysite.com
&dp=%2Fhome
&dt=Homepage
&an=myapp

I also tried to create a "Mobile Application" in Google Analytics and use that tracking id instead. Same result here - no tracking information in Google Analytics.

Does anyone know, how to perform this tracking requests successfully or if there is a debug-option so that I can at least see, why the tracking call is not saved? Thanks!


问:
How to split a string while ignoring the case of the delimiter?
I need to split a string let's say "asdf aA asdfget aa uoiu AA" split using "aa" ignoring the case.
to</p>

```<code>"asdf "
"asdfget "
"uoiu "
</code>```

答:
```<code>Dim arr As String() = Strings.Split("asdf aA asdfget aa uoiu AA",
                                    "aa" ,, CompareMethod.Text)
</code>```

CompareMethod.Text ignores case.

ContentLicense: CC BY-SA 2.5

Body:
I need to split a string let's say "asdf aA asdfget aa uoiu AA" split using "aa" ignoring the case.
to

"asdf "
"asdfget "
"uoiu "

Body:
Dim arr As String() = Strings.Split("asdf aA asdfget aa uoiu AA",
                                    "aa" ,, CompareMethod.Text)

CompareMethod.Text ignores case.


问:
Trying to update posgres database in docker resulting in machine refusing connection
While doing first database update i get an error

System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
     at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
     at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
     at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
     at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<g__OpenLong|0>d.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at Npgsql.NpgsqlConnection.Open()
     at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
     at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
     at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
     at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
  No connection could be made because the target machine actively refused it.

I'm using Docker Toolbox for low end pc. And I ran postgres container with command:

docker run --name pg -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres;

For connecting EF Core to pgsql I used Npgsql nuget package and connectionString

"Server=127.0.0.1;Port=5432;Database=postgres;Username=postgres;Password=password"

Next, I created in MyDbContext file

```<code>public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
}

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
    public MyDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseNpgsql("Server=127.0.0.1;Port=5432;Database=postgres;Username=postgres;Password=password");

        return new MyDbContext(optionsBuilder.Options);
    }
}
</code>```

After which i added dbContext in Startup class

```<code>public void ConfigureServices(IServiceCollection services, IConfiguration config)
{
    services.AddDbContext<Models.MyDbContext>();
</code>```

Can anyone help me, or suggest what could I have missed?

答:
For your scenario, Server=127.0.0.1 will work when you start your .net core project from host.

I assume you start your .net core project from docker, if so, you need to follow steps belwo which connect the two container.

Change your connectionstring with postgres container name pg like

```<code>"Server=pg;Port=5432;Database=postgres;Username=postgres;Password=password"
</code>```

Specify the --link=pg while running the .net core like

```<code>docker run -it -p 8585:80 --link=pg dockerpostgres
</code>```

Body:
While doing first database update i get an error

System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
     at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
     at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
     at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
     at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<g__OpenLong|0>d.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at Npgsql.NpgsqlConnection.Open()
     at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
     at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
     at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
     at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
  No connection could be made because the target machine actively refused it.

I'm using Docker Toolbox for low end pc. And I ran postgres container with command:

docker run --name pg -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres;

For connecting EF Core to pgsql I used Npgsql nuget package and connectionString

"Server=127.0.0.1;Port=5432;Database=postgres;Username=postgres;Password=password"

Next, I created in MyDbContext file

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
}

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
    public MyDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseNpgsql("Server=127.0.0.1;Port=5432;Database=postgres;Username=postgres;Password=password");

        return new MyDbContext(optionsBuilder.Options);
    }
}

After which i added dbContext in Startup class

public void ConfigureServices(IServiceCollection services, IConfiguration config)
{
    services.AddDbContext<Models.MyDbContext>();

Can anyone help me, or suggest what could I have missed?

Body:
For your scenario, Server=127.0.0.1 will work when you start your .net core project from host.

I assume you start your .net core project from docker, if so, you need to follow steps belwo which connect the two container.

Change your connectionstring with postgres container name pg like

"Server=pg;Port=5432;Database=postgres;Username=postgres;Password=password"

Specify the --link=pg while running the .net core like

docker run -it -p 8585:80 --link=pg dockerpostgres


问:
How to read a resource file in C#
I have added a resource file to my project (C#, windows service - TopShelp):

I have added a text file to the resource:

Now I want to read the test file, this is what I have tried:

```<code>ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());
</code>```

It does not find anything, ResourceSets count = 0.

Update

As suggested in the comments, I also tried adding the resource under:

Project > Properties > Resources

And tried the following code, which did not find anything:

```<code>ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());
</code>```

答:
Check your Resources.Designer.cs file. You should have there static string property named stop_words_utf8 (or whatever name for the file you choose). You use it like this:

```<code>Resources.stop_words_utf8
</code>```

It is static string property

Title: How to read a resource file in C#

Body:
I have added a resource file to my project (C#, windows service - TopShelp):

I have added a text file to the resource:

Now I want to read the test file, this is what I have tried:

ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());

It does not find anything, ResourceSets count = 0.

Update

As suggested in the comments, I also tried adding the resource under:

Project > Properties > Resources

And tried the following code, which did not find anything:

ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());

Body:
Check your Resources.Designer.cs file. You should have there static string property named stop_words_utf8 (or whatever name for the file you choose). You use it like this:

Resources.stop_words_utf8

It is static string property


问:
humans_21909=1 error in codeigniter project
Some controller functions in codeigniter is setting up humans_21909 cookie. And the page source appears to be as follows

```<code><script>document.cookie = "humans_21909=1"; document.location.reload(true)</script>
</code>```

The same project worls perfectly on local server. but on live server it shows this stuff.

答:
I have found that issue is coming from cookie.
Please set a cookie in header.php file with project path
in this after set of cookies page will reload without changing web URL

e.g

```<code><script type="text/javascript">
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
var accept = getCookie("humans_21909");
if (accept !="1") {
document.cookie = "humans_21909=1; path=/insert here project root path/";
    console.log("ok");
    (function()
    {
      if( window.localStorage )
      {
        if( !localStorage.getItem('firstLoad') )
        {
            console.log("refresh");
            localStorage['firstLoad'] = true;
            window.location.reload();
        }
        else
          localStorage.removeItem('firstLoad');
      }
    })();
}
</code>```

I think your issue with resolve with this

Body:
Some controller functions in codeigniter is setting up humans_21909 cookie. And the page source appears to be as follows

The same project worls perfectly on local server. but on live server it shows this stuff.

Body:
I have found that issue is coming from cookie.
Please set a cookie in header.php file with project path
in this after set of cookies page will reload without changing web URL

e.g

<script type="text/javascript">
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
var accept = getCookie("humans_21909");
if (accept !="1") {
document.cookie = "humans_21909=1; path=/insert here project root path/";
    console.log("ok");
    (function()
    {
      if( window.localStorage )
      {
        if( !localStorage.getItem('firstLoad') )
        {
            console.log("refresh");
            localStorage['firstLoad'] = true;
            window.location.reload();
        }
        else
          localStorage.removeItem('firstLoad');
      }
    })();
}

I think your issue with resolve with this


问:
Securely encrypting credit card data
I came to a situation where I am required to store credit card holder data in my database and I'm looking for the most secure way of dealing with this. Note that I am fully aware of PCI-DSS so my question is purely about the encryption aspect.

Now I have decided to use Curve25519 public key encryption (using libsodium) and the private key is stored securely, offline. Let's assume I implemented this correctly. I figured that when I only encrypt the credit card number and the expiry date this would be easy to brute force as the first 6 and last 4 digits of the card number are known as well as the expiry date, because they are already plain text in the database somewhere.

Let's say I'm encrypting this

```<code>1234561111118762|10|21|VISA
</code>```

Now the only secret in this string is 111111 (6 digits). It would cost someone 10^6 tries to find out this number.

But what if I am encrypting like this

```<code>1234561111118762|10|21|VISA|aVeryLongPsuedoRandomStringGeneratedUniquelyForEachEncryptedString
</code>```

Would this prevent a brute force 10^6 scenario? Or am I missing something?

答:
Speaking just about encryption...

I'm assuming by "brute-force" you mean take the public key, encrypt and compare to the ciphertext you have stored.  If this is what you mean, then the answer depends on the implementation.

You need to determine if the implementation is deterministic - if it is, then yes, it will be possible to brute-force and compare.  If it is not (which you would expect), then this won't be a problem.

I expect libsodium has this problem covered.

Title: Securely encrypting credit card data

Body:
I came to a situation where I am required to store credit card holder data in my database and I'm looking for the most secure way of dealing with this. Note that I am fully aware of PCI-DSS so my question is purely about the encryption aspect.

Now I have decided to use Curve25519 public key encryption (using libsodium) and the private key is stored securely, offline. Let's assume I implemented this correctly. I figured that when I only encrypt the credit card number and the expiry date this would be easy to brute force as the first 6 and last 4 digits of the card number are known as well as the expiry date, because they are already plain text in the database somewhere.

Let's say I'm encrypting this

1234561111118762|10|21|VISA

Now the only secret in this string is 111111 (6 digits). It would cost someone 10^6 tries to find out this number.

But what if I am encrypting like this

1234561111118762|10|21|VISA|aVeryLongPsuedoRandomStringGeneratedUniquelyForEachEncryptedString

Would this prevent a brute force 10^6 scenario? Or am I missing something?


问:
Proper steps to migrate PHP 5.6 code into PHP 7.3
we have developed previously in house system based on PHP 5.6 now we want to upgrade same code into PHP 7.3, we have not used any PHP framework we are using core way to write code means we are not using ANY PHP framework. what are the proper steps to migrate PHP 5.6 code into PHP 7.3  </p>

答:
Apart from reading all the documentation guides at php.net

Set up a development/testing server using the PHP version you want
to migrate to (7.3)

copy your app/code to the testing server

fix all the issues and bugs that spring up using php 7.3

upgrade production to 7.3

copy fixed code to production


问:
How do I capture a single image from webcam and process it further in OpenCV?
I want my code to capture a single image from webcam and process it further, like later detect colours and sobel edges and a lot more.
In short, I want to do image acquisition.</p>

答:
To use your webcam, you can use VideoCapture:

```<code>import cv2
cap = cv2.VideoCapture(0) # use 0 if you only have front facing camera
ret, frame = cap.read() #read one frame
print(frame.shape)
cap.release() # release the VideoCapture object.
</code>```

You start the webcam, read one image and immediately release it. The frame is the image and you can preprocess it however you want. You can view the image using imshow:

```<code>cv2.imshow('image', frame)
if cv2.waitKey(0) & 0xff == ord('q'): # press q to exit
    cv2.destroyAllWindows()
</code>```

Body:
To use your webcam, you can use VideoCapture:

import cv2
cap = cv2.VideoCapture(0) # use 0 if you only have front facing camera
ret, frame = cap.read() #read one frame
print(frame.shape)
cap.release() # release the VideoCapture object.

You start the webcam, read one image and immediately release it. The frame is the image and you can preprocess it however you want. You can view the image using imshow:

cv2.imshow('image', frame)
if cv2.waitKey(0) & 0xff == ord('q'): # press q to exit
    cv2.destroyAllWindows()


问:
Check if child data exists before deleting parent
I have news_Category and news table, here every news comes under one category,so before deleting new_category I want to display user a msg that child news exists in this category so u are not allowed to delete, If there are no child news than a confirm alert to user that "do u really want to delete".If he confirms the news category gets deleted.

HTML STUFF

```<code><?php  echo "<a style='color:red;''
  href='delete.php?delete=$values[category_id]&
   img=$values[category_image]'><i class='fas fa-trash-alt'></i></a>"; ?>

if ($_GET['msgError'])   {
echo "<script>alert('First Delete The News Than Category');</script>";
}
if ($_GET['msg'])   {
?>
<?php
   }
   ?>
</code>```

DELETE.PHP

```<code>if (isset($_GET['delete'])) {
 $id= $_GET['delete'];
 $img=$_GET['img'];
 $obj=new commands();
 $obj->delete_category($id,$img);
 }
</code>```

Delete Function

```<code>   function delete_category($id,$img)
   {
       $stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
       $stmt->execute();
       $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
       if ($result) {
           header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
       } else {
           $sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
           $sql->bindParam(':id', $id);
           $sql->execute();
           unlink("uploads/" . $img);
           header('Location: news_category.php?msg="confirm"');
           $this->con = null;
       }
   }
</code>```

I am not able to make to logic here, how can I check whether the child news exists so i can display error msg and if there is no child news how to show confirm alert to allow delte

答:
You need to check to see if the result is empty.

Something like this:

```<code>function delete_category($id,$img)
   {
       $stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
       $stmt->execute();
       $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
       if (empty($result)) {
           header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
       } else {
           $sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
           $sql->bindParam(':id', $id);
           $sql->execute();
           unlink("uploads/" . $img);
           header('Location: news_category.php?msg="confirm"');
           $this->con = null;
       }
   }
</code>```

Edit due to extra details request

On the front end you just need to display the GET msgError like this:

```<code><?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>
</code>```

Where you want to show the message text.

Body:
I have news_Category and news table, here every news comes under one category,so before deleting new_category I want to display user a msg that child news exists in this category so u are not allowed to delete, If there are no child news than a confirm alert to user that "do u really want to delete".If he confirms the news category gets deleted.

HTML STUFF

<?php  echo ""; ?>

if ($_GET['msgError'])   {
echo "";
}
if ($_GET['msg'])   {
?>
<?php
   }
   ?>

DELETE.PHP

if (isset($_GET['delete'])) {
 $id= $_GET['delete'];
 $img=$_GET['img'];
 $obj=new commands();
 $obj->delete_category($id,$img);
 }

Delete Function

   function delete_category($id,$img)
   {
       $stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
       $stmt->execute();
       $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
       if ($result) {
           header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
       } else {
           $sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
           $sql->bindParam(':id', $id);
           $sql->execute();
           unlink("uploads/" . $img);
           header('Location: news_category.php?msg="confirm"');
           $this->con = null;
       }
   }

I am not able to make to logic here, how can I check whether the child news exists so i can display error msg and if there is no child news how to show confirm alert to allow delte

Body:
You need to check to see if the result is empty.

Something like this:

function delete_category($id,$img)
   {
       $stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
       $stmt->execute();
       $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
       if (empty($result)) {
           header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
       } else {
           $sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
           $sql->bindParam(':id', $id);
           $sql->execute();
           unlink("uploads/" . $img);
           header('Location: news_category.php?msg="confirm"');
           $this->con = null;
       }
   }

Edit due to extra details request

On the front end you just need to display the GET msgError like this:

<?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>

Where you want to show the message text.


问:
What is the meaning of (/^\s+|\s+$/gm) in JavaScript?
I came across this JavaScript function:

```<code>function myTrim(x) {
  return x.replace(/^\s+|\s+$/gm,'');
}
</code>```

I know that this function(mytrim()) replaces some characters in the string(x), but what does /^\s+|\s+$/gm do in the replace method?

Where can I learn more about these things?

Note- This function returns the string with removed spaces at both sides.

答:
^\s+|\s+$gm

1st Alternative (^\s+)

^   asserts position at start of a line

\s+  matches any whitespace character (equal to [\r\n\t\f\v ])

+Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Alternative (\s+$)

\s+ matches any whitespace character (equal to [\r\n\t\f\v ])

+Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of a line

Global pattern flags:

g modifier: global. All matches (don't return after first match)

m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Body:
I came across this JavaScript function:

function myTrim(x) {
  return x.replace(/^\s+|\s+$/gm,'');
}

I know that this function(mytrim()) replaces some characters in the string(x), but what does /^\s+|\s+$/gm do in the replace method?

Where can I learn more about these things?

Note- This function returns the string with removed spaces at both sides.


问:
Why does Visual Studio 2019 run tests in dotnet core 1.0 even though my projects target dotnet core 2.2?
I have a solution with 2 projects, one of which is a test project. Both projects target dotnet core 2.2:

```<code><TargetFramework>netcoreapp2.2</TargetFramework>
</code>```

I am using Visual Studio 2019 (version 16.1.1). When I click "Run all" in test explorer, it outputs this warning in output window:

```<code>[5/28/2019 10:25:40 PM Informational] ------ Run test started ------
[5/28/2019 10:25:40 PM Warning] Test run will use DLL(s) built for framework .NETCoreApp,Version=v1.0 and platform X64. Following DLL(s) do not match framework/platform settings.
MyApp.UnitTests.dll is built for Framework 2.2 and Platform AnyCPU.
Go to http://go.microsoft.com/fwlink/?LinkID=236877&clcid=0x409 for more details on managing these settings.

[5/28/2019 10:25:41 PM Informational] ========== Run test finished: 3 run (0:00:01.167997) ==========
</code>```

The tests do run, and finish successfully. But I am wondering about how to get rid of this warning.

I added a .runsettings file with following settings, but I still see the same warning.

```<code><?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <TargetFrameworkVersion>FrameworkCore10</TargetFrameworkVersion>
  </RunConfiguration>
</RunSettings>
</code>```

Changing FrameworkCore10 to FrameworkCore22 (or netcoreapp2.2) throws a huge exception. Top few lines of the exception:

```<code>[5/28/2019 10:41:30 PM Error] System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.VisualStudio.TestWindow.Controller.RequestConfiguration.GroupTestContainersConfigByFrameworkAndArchitecture(IEnumerable`1 testContainersConfig, IXPathNavigable runSetting)
   at Microsoft.VisualStudio.TestWindow.Controller.TestRunConfiguration.<GetAllCriteriaQueues>d__64.MoveNext()
   at Microsoft.VisualStudio.TestWindow.Controller.TestRunRequest.<CreateRequests>d__23.MoveNext()
   at Microsoft.VisualStudio.TestWindow.Controller.Request.<RunRequests>d__95.MoveNext()
   --- End of inner exception stack trace ---
</code>```

Note that the same projects work fine in Visual Studio 2017, without the need of any runsettings file whatsoever.

答:
It might be 2.2 dot net framework doesn't install in that machine.

Here is Link, you can download the framework.

Body:
I have a solution with 2 projects, one of which is a test project. Both projects target dotnet core 2.2:

<TargetFramework>netcoreapp2.2</TargetFramework>

I am using Visual Studio 2019 (version 16.1.1). When I click "Run all" in test explorer, it outputs this warning in output window:

[5/28/2019 10:25:40 PM Informational] ------ Run test started ------
[5/28/2019 10:25:40 PM Warning] Test run will use DLL(s) built for framework .NETCoreApp,Version=v1.0 and platform X64. Following DLL(s) do not match framework/platform settings.
MyApp.UnitTests.dll is built for Framework 2.2 and Platform AnyCPU.
Go to http://go.microsoft.com/fwlink/?LinkID=236877&clcid=0x409 for more details on managing these settings.

[5/28/2019 10:25:41 PM Informational] ========== Run test finished: 3 run (0:00:01.167997) ==========

The tests do run, and finish successfully. But I am wondering about how to get rid of this warning.

I added a .runsettings file with following settings, but I still see the same warning.

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <TargetFrameworkVersion>FrameworkCore10</TargetFrameworkVersion>
  </RunConfiguration>
</RunSettings>

Changing FrameworkCore10 to FrameworkCore22 (or netcoreapp2.2) throws a huge exception. Top few lines of the exception:

[5/28/2019 10:41:30 PM Error] System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.VisualStudio.TestWindow.Controller.RequestConfiguration.GroupTestContainersConfigByFrameworkAndArchitecture(IEnumerable`1 testContainersConfig, IXPathNavigable runSetting)
   at Microsoft.VisualStudio.TestWindow.Controller.TestRunConfiguration.<GetAllCriteriaQueues>d__64.MoveNext()
   at Microsoft.VisualStudio.TestWindow.Controller.TestRunRequest.<CreateRequests>d__23.MoveNext()
   at Microsoft.VisualStudio.TestWindow.Controller.Request.<RunRequests>d__95.MoveNext()
   --- End of inner exception stack trace ---

Note that the same projects work fine in Visual Studio 2017, without the need of any runsettings file whatsoever.


问:
How to select MAX id and convert Result to int
I would like to get the MAX id from my table and add a number to it. When the result is stored after executing the query, I save it into another variable and add 1. I get an error: "Object of class mysqli_result could not be converted to int"

I have tried:

```<code>$row = mysqli_fetch_assoc($result);
$uniqueCode = $row+1;
</code>```

This is the current code I have to get the maximum reference number:

```<code>    $sql = "SELECT MAX(referenceNo) FROM taxibookings LIMIT 1";
        $result = mysqli_query($conn, $sql);
</code>```

答:
If you are using auto increment and want to find the max id then it is simple that find the last entry of the table if there is no deletion of the row because if you are deleting row then its bad way to handle database never delete manage it with status column if its required to delete.See the below code.</p>

```<code>// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// find last id which will be the max
if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
</code>```

Body:
I would like to get the MAX id from my table and add a number to it. When the result is stored after executing the query, I save it into another variable and add 1. I get an error: "Object of class mysqli_result could not be converted to int"

I have tried:

$row = mysqli_fetch_assoc($result);
$uniqueCode = $row+1;

This is the current code I have to get the maximum reference number:

    $sql = "SELECT MAX(referenceNo) FROM taxibookings LIMIT 1";
        $result = mysqli_query($conn, $sql);

Body:
If you are using auto increment and want to find the max id then it is simple that find the last entry of the table if there is no deletion of the row because if you are deleting row then its bad way to handle database never delete manage it with status column if its required to delete.See the below code.

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// find last id which will be the max
if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();


问:
Junit spring boot unit tests for busienss logic and DB Connections
In my spring boot application, we have service, controller and model.

The controller has:

```<code>  @RequestMapping(value = "/v1/abc/def", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Map<String, List<ClicksReply>>> getAbcCall(@RequestParam(value = "Id") String Id,
                                                                                @RequestParam(value = "Tag") List<String> Tag) throws SQLException {
        Map<String, List<ClicksReply>> clicks = mysqlService.getReplyCount(pageId, notificationTag);
        return new ServiceResponse<>(HttpStatus.OK, clicks);
    }
</code>```

mysqlService.getReplyCount looks like this:

```<code>    public Map<String, List<ClicksReply>> getReplyCount(String pageId, List<String> notificationTag) {
            String notificationIds = getStringForInQuery(notificationTag);
            try (PreparedStatement preparedStatement = connection.prepareStatement(String.format(GET_CLICK_COUNT, notificationIds))) {
                Map<String, List<Clicks
Reply>> mapNotifsButtonCount = new HashMap<>();
                preparedStatement.setString(1, pageId);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {

                    ClicksReply reply = new ClicksReply();

                    Integer buttonId = resultSet.getInt(2);
                    Integer clickCount = resultSet.getInt(3);

                    reply.setButtonId(buttonId);
                    reply.setCount(clickCount);
                    String tag = resultSet.getString(1);

                    if (!mapNotifsButtonCount.containsKey(tag)) {
                        List<ClicksReply> clicksReplies = new LinkedList<>();
                        mapNotifsButtonCount.put(tag, clicksReplies);
                    }
                    List<ClicksReply> existinglist = mapNotifsButtonCount.get(tag);
                    existinglist.add(reply);
                }
                resultSet.close();
                preparedStatement.close();
                return mapNotifsButtonCount;
            } catch (SQLException exception) {
                return null;
            }
        }
</code>```

I am new to Java Stack and I tried writing unit test after following some basics, this is how far I got:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(value = StatsController.class, secure = false)
public class StatsTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MysqlService mysqlService;

    @Test
    public void getReplyCount() throws Exception {
        Map<String, List<ClicksReply>> mapClicksReply = new HashMap();
        Mockito.when(
                mysqlService.getQuickReplyCount(
                        Mockito.any(String.class), Mockito.anyListOf(String.class)
                )
        ).thenReturn(mapClicksQuickReply);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/v1/abc/def")
                .param("Id", Mockito.anyString())
                .param("Tag", Mockito.anyString())
                .accept(
                MediaType.APPLICATION_JSON);

        mockMvc.perform(requestBuilder).
                andExpect(jsonPath("$.httpStatusCode").value(200))
                .andExpect(jsonPath("$.errorMessage").value(IsNull.nullValue()))
                .andDo(print());

    }

}
</code>```

What should the next step be to actually "unit test" the business logic, DB connection and query results? What I have done so far is more like high level API test that checks the status.

I am not sure of the direction so as to check the business logic now.

答:
I think there is not a 'right' answer, but I would first split up the getReplyCount method because it is hard to test at the moment. This method does currently multiple things:

prepares the query

fetch the data with the prepared statement

maps the data to the ClicksReply class

groups the items by tags

With the much smaller scope you can much easier test different scenarios like:

valid / invalid input parameters

constructing the query

failing query execution

different issues with the mapping

correct grouping of the items

Also on you API test you can add more scenarios like error, invalid input etc.

What me personally helped in the past was a book about testing / tdd in Java it gave me much more insights what to consider on testing because there are a lot of pitfalls especially on maintaining a good test suite over time.

I hope that helped.

regards, wipu

Body:
In my spring boot application, we have service, controller and model.

The controller has:

  @RequestMapping(value = "/v1/abc/def", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Map<String, List<ClicksReply>>> getAbcCall(@RequestParam(value = "Id") String Id,
                                                                                @RequestParam(value = "Tag") List<String> Tag) throws SQLException {
        Map<String, List<ClicksReply>> clicks = mysqlService.getReplyCount(pageId, notificationTag);
        return new ServiceResponse<>(HttpStatus.OK, clicks);
    }

mysqlService.getReplyCount looks like this:

    public Map<String, List<ClicksReply>> getReplyCount(String pageId, List<String> notificationTag) {
            String notificationIds = getStringForInQuery(notificationTag);
            try (PreparedStatement preparedStatement = connection.prepareStatement(String.format(GET_CLICK_COUNT, notificationIds))) {
                Map<String, List<Clicks
Reply>> mapNotifsButtonCount = new HashMap<>();
                preparedStatement.setString(1, pageId);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {

                    ClicksReply reply = new ClicksReply();

                    Integer buttonId = resultSet.getInt(2);
                    Integer clickCount = resultSet.getInt(3);

                    reply.setButtonId(buttonId);
                    reply.setCount(clickCount);
                    String tag = resultSet.getString(1);

                    if (!mapNotifsButtonCount.containsKey(tag)) {
                        List<ClicksReply> clicksReplies = new LinkedList<>();
                        mapNotifsButtonCount.put(tag, clicksReplies);
                    }
                    List<ClicksReply> existinglist = mapNotifsButtonCount.get(tag);
                    existinglist.add(reply);
                }
                resultSet.close();
                preparedStatement.close();
                return mapNotifsButtonCount;
            } catch (SQLException exception) {
                return null;
            }
        }

I am new to Java Stack and I tried writing unit test after following some basics, this is how far I got:

@RunWith(SpringRunner.class)
@WebMvcTest(value = StatsController.class, secure = false)
public class StatsTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MysqlService mysqlService;

    @Test
    public void getReplyCount() throws Exception {
        Map<String, List<ClicksReply>> mapClicksReply = new HashMap();
        Mockito.when(
                mysqlService.getQuickReplyCount(
                        Mockito.any(String.class), Mockito.anyListOf(String.class)
                )
        ).thenReturn(mapClicksQuickReply);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/v1/abc/def")
                .param("Id", Mockito.anyString())
                .param("Tag", Mockito.anyString())
                .accept(
                MediaType.APPLICATION_JSON);

        mockMvc.perform(requestBuilder).
                andExpect(jsonPath("$.httpStatusCode").value(200))
                .andExpect(jsonPath("$.errorMessage").value(IsNull.nullValue()))
                .andDo(print());

    }

}

What should the next step be to actually "unit test" the business logic, DB connection and query results? What I have done so far is more like high level API test that checks the status.

I am not sure of the direction so as to check the business logic now.


问:
Maven Unable to Find AEM Archetype
I've been starting at this problem for way to long... Im working through the Adobe wknd project and I can't get pass this command and most of the work is built off of it

```<code>mvn archetype:generate \
  -DarchetypeGroupId=com.adobe.granite.archetypes \
  -DarchetypeArtifactId=aem-project-archetype \
  -DarchetypeVersion=18
</code>```

I've tried it on the VPN and off, with all possible proxy configs and still getting the same error of

```<code>Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)
</code>```

Deleting and reinstalling multiple times. Different networks and proxy configs as well Mac OS.

mvn -v returns

```<code>Maven home: /Users/dmills/Applications/apache-maven-3.6.1
Java version: 1.8.0_212, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "mac"
</code>```

Get this error

```<code>Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)
</code>```

Build is failing and I don't know where to go now

答:
Just update the settings.xml file in the m2 folder. Please look into the below link if you are using archtype 13 and 6.4

https://helpx.adobe.com/experience-manager/using/maven_arch13.html

Also in the profile tag please update the adobe repo url to 'https' instead of http.

Title: Maven Unable to Find AEM Archetype

Body:
I've been starting at this problem for way to long... Im working through the Adobe wknd project and I can't get pass this command and most of the work is built off of it

mvn archetype:generate \
  -DarchetypeGroupId=com.adobe.granite.archetypes \
  -DarchetypeArtifactId=aem-project-archetype \
  -DarchetypeVersion=18

I've tried it on the VPN and off, with all possible proxy configs and still getting the same error of

Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)

Deleting and reinstalling multiple times. Different networks and proxy configs as well Mac OS.

mvn -v returns

Maven home: /Users/dmills/Applications/apache-maven-3.6.1
Java version: 1.8.0_212, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "mac"

Get this error

Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)

Build is failing and I don't know where to go now


问:
Deleting N matching patterns using sed, awk, perl etc
I have this situation, the file contains

```<code>abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5
</code>```

I would like to delete whenever I find matching 2 lines of

```<code>abcd
vwxyz
</code>```

to be deleted so that it becomes

```<code>abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

答:
you mean something like this?

```<code>sed '/abcd/{N;/vwxyz/d}' yourdata.file
</code>```

explanation

```<code>/abcd/    # search first Pattern
{
N;        # if match read next line
/vwxyz/d  # if second pattern match then delete line
}
</code>```

Body:
I have this situation, the file contains

abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5

I would like to delete whenever I find matching 2 lines of

abcd
vwxyz

to be deleted so that it becomes

abcd
line1
line2
line3
vwxyz
line4
line5

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

Body:
you mean something like this?

sed '/abcd/{N;/vwxyz/d}' yourdata.file

explanation

/abcd/    # search first Pattern
{
N;        # if match read next line
/vwxyz/d  # if second pattern match then delete line
}


问:
How to disable Browser back button in Angular 2
I'm developing a web site using Angular 2.
Is there any way to disable or trigger Browser back button using Angular 2?

Thanks

答:
```<code>import { LocationStrategy } from '@angular/common';
constructor( private location: LocationStrategy){
// preventing back button in browser implemented by "Samba Siva"
 history.pushState(null, null, window.location.href);
this.location.onPopState(() => {
  history.pushState(null, null, window.location.href);
});
}
</code>```

its working fine to me 100% in angular2/4/5

Body:
import { LocationStrategy } from '@angular/common';
constructor( private location: LocationStrategy){
// preventing back button in browser implemented by "Samba Siva"
 history.pushState(null, null, window.location.href);
this.location.onPopState(() => {
  history.pushState(null, null, window.location.href);
});
}

its working fine to me 100% in angular2/4/5


问:
A loop to iteratively arrive at rowsums = colsums for i = j
I do apologize my question is going to be wordy because i'm just at a loss on how to even start coding this. Pseudo-code answers are highly appreciated if only to allow me to understand how to solve this (then I can write some actual code and come back for help if necessary).

My problem isn't so much the code as it is understanding the logic I need (which is arguably the harder part of programming).

An informal explanation of my problem is that  want to change a matrix A (which happens to be sparse) such that the row sums are equal to the column sums. I can do this by adding to A a matrix AS where S is a matrix of scales.

Formally, I want to find an S matrix such that (A + AS)ONESn = T and (t(A) + T(A)S)ONESn = T where ONESn is a vector of ones that creates T, the vector of row sums.

The vector T is set in stone as it were, it is the current column sums and is the target for the row sums.

I think the way I want to solve this is for each row i and column j where i = j I want to find the row sum and compute how far it is from the target. Then I want to change each element of that row such that the row sum equals the target (or is at least "close enough" where I can set the "close enough").

However, this is subject to the condition that the sum of column j must equal the target as well.

How can I design the logic so that I can start with say column 1 and row 1, figure out the values in row 1 and then figure out the values of column 1 subject to the first entry of column 1 being "fixed" by the earlier procedure.

Following that, row 2 should have its first value "fixed" by the above, and similarly the programme needs to figure out column 2 with fixed values for the first two entries now.

And so on until you get to the final column and row

I have tried programming a gradient descent but got stick on how to make the gradient descent for the columns depend on the gradient descent for the rows iteratively.

I've also worked this out by hand (for a 2x2 matrix), I can figure out the answer but I'm not sure how I managed to do so which is why I'm struggling to code it.

Suppose A is a 2x2 matrix of [1, 2, 3, 4]. Row sums are are [4, 6]. Column sums are [3, 7].

```<code>1 3  | 4
2 4  | 6
___
3 7
</code>```

if I add the matrix S = [1, 0, -1, 0]

```<code>1 -1
0  0
</code>```

I get A + S = [2, 2, 2, 4] which has row sums [4, 6].

```<code>2 2  | 4
2 4  | 6
___
4 6
</code>```

Expected results are a matrix (A + AS) such that the row sums equal the column sums.

Or an error message saying "does not converge"

答:
You have some matrix A and you need to add another matrix S so that the resulting matrix M has same row sums as column sums. This means:

A + S = M # For M row sums = column sums

So what you need to do is to find S. You can simply change the equotion to

S = M - S

Now you can set any matrix with same row sum and column sum for M and you get S. Once you have S you can do

A + S = M.

This means that you can add to every matrix A another matrix S so that the resulting matrix M has row sums= column sums. Hence, you will not get the messege "matrix does not converge".

Here is a R code

```<code>A <- matrix(rnorm(4), ncol= 2)
M <- matrix(c(2,2,2,4), ncol= 2)
S <- M - A
rowSums(A+S) == colSums(A+S)
TRUE TRUE
</code>```

Or, more general:

```<code>row_col_num <- 5 # number of columns and rows
A <- matrix(rnorm(row_col_num *row_col_num ), ncol= row_col_num )
M <- matrix(rep(1, row_col_num *row_col_num ), ncol= row_col_num )
S <- M - A
rowSums(A+S) == colSums(A+S)
TRUE TRUE TRUE TRUE TRUE
</code>```

The resulting matrix A+S is always as you set M. So I am not sure what this is for. If you need to know how to find S, where A+S gives you a matrix M with row sums= column sums, this is how you can do it.

Body:
I do apologize my question is going to be wordy because i'm just at a loss on how to even start coding this. Pseudo-code answers are highly appreciated if only to allow me to understand how to solve this (then I can write some actual code and come back for help if necessary).

My problem isn't so much the code as it is understanding the logic I need (which is arguably the harder part of programming).

An informal explanation of my problem is that  want to change a matrix A (which happens to be sparse) such that the row sums are equal to the column sums. I can do this by adding to A a matrix AS where S is a matrix of scales.

Formally, I want to find an S matrix such that (A + AS)ONESn = T and (t(A) + T(A)S)ONESn = T where ONESn is a vector of ones that creates T, the vector of row sums.

The vector T is set in stone as it were, it is the current column sums and is the target for the row sums.

I think the way I want to solve this is for each row i and column j where i = j I want to find the row sum and compute how far it is from the target. Then I want to change each element of that row such that the row sum equals the target (or is at least "close enough" where I can set the "close enough").

However, this is subject to the condition that the sum of column j must equal the target as well.

How can I design the logic so that I can start with say column 1 and row 1, figure out the values in row 1 and then figure out the values of column 1 subject to the first entry of column 1 being "fixed" by the earlier procedure.

Following that, row 2 should have its first value "fixed" by the above, and similarly the programme needs to figure out column 2 with fixed values for the first two entries now.

And so on until you get to the final column and row

I have tried programming a gradient descent but got stick on how to make the gradient descent for the columns depend on the gradient descent for the rows iteratively.

I've also worked this out by hand (for a 2x2 matrix), I can figure out the answer but I'm not sure how I managed to do so which is why I'm struggling to code it.

Suppose A is a 2x2 matrix of [1, 2, 3, 4]. Row sums are are [4, 6]. Column sums are [3, 7].

1 3  | 4
2 4  | 6
___
3 7

if I add the matrix S = [1, 0, -1, 0]

1 -1
0  0

I get A + S = [2, 2, 2, 4] which has row sums [4, 6].

2 2  | 4
2 4  | 6
___
4 6

Expected results are a matrix (A + AS) such that the row sums equal the column sums.

Or an error message saying "does not converge"

Body:
You have some matrix A and you need to add another matrix S so that the resulting matrix M has same row sums as column sums. This means:

A + S = M # For M row sums = column sums

So what you need to do is to find S. You can simply change the equotion to

S = M - S

Now you can set any matrix with same row sum and column sum for M and you get S. Once you have S you can do

A + S = M.

This means that you can add to every matrix A another matrix S so that the resulting matrix M has row sums= column sums. Hence, you will not get the messege "matrix does not converge".

Here is a R code

A <- matrix(rnorm(4), ncol= 2)
M <- matrix(c(2,2,2,4), ncol= 2)
S <- M - A
rowSums(A+S) == colSums(A+S)
TRUE TRUE

Or, more general:

row_col_num <- 5 # number of columns and rows
A <- matrix(rnorm(row_col_num *row_col_num ), ncol= row_col_num )
M <- matrix(rep(1, row_col_num *row_col_num ), ncol= row_col_num )
S <- M - A
rowSums(A+S) == colSums(A+S)
TRUE TRUE TRUE TRUE TRUE

The resulting matrix A+S is always as you set M. So I am not sure what this is for. If you need to know how to find S, where A+S gives you a matrix M with row sums= column sums, this is how you can do it.


问:
How to join absolute and relative urls?
I have two urls:

```<code>url1 = "http://127.0.0.1/test1/test2/test3/test5.xml"
url2 = "../../test4/test6.xml"
</code>```

How can I get an absolute url for url2?

答:
For python 3.0+ the correct way to join urls is:</p>

```<code>from urllib.parse import urljoin
urljoin('https://10.66.0.200/', '/api/org')
# output : 'https://10.66.0.200/api/org'
</code>```

Title: How to join absolute and relative urls?

Body:
I have two urls:

url1 = "http://127.0.0.1/test1/test2/test3/test5.xml"
url2 = "../../test4/test6.xml"

How can I get an absolute url for url2?

Body:
For python 3.0+ the correct way to join urls is:

from urllib.parse import urljoin
urljoin('https://10.66.0.200/', '/api/org')
# output : 'https://10.66.0.200/api/org'


问:
Values vanishing after leaving function
I'm writing a function to insert into a tree and the data can be seen (printed) after insertion within the function but when trying to see it in main nothing happens.

node *tree = NULL;
insert(tree, 4321);
printf("outer: %d\n", tree->data);

void insert(node* tree, int data) {
  if (tree == NULL) {
    tree = new_node(data);
    printf("inner: %d\n", tree->data);
  }
}
```

<p>This gives:</p>

```inner: 4321
```

<p>It should be:</p>

```inner: 4321
outer: 4321
```

答:
The problem is, tree is passed as an argument to the function, and by-status which is a pass-by-value in C. Any change made to tree itself inside the function will not be reflected back to the caller.

You need to pass a pointer to tree, if you want to modify tree from the called function.

Something like

```<code>void insert(node** tree, int data) {
  if (*tree == NULL) {
    *tree = new_node(data);
    printf("inner: %d\n", (*tree)->data);
  }
}
</code>```

and call it like

```<code>insert(&tree, 4321);
</code>```

Title: Values vanishing after leaving function

Body:
I'm writing a function to insert into a tree and the data can be seen (printed) after insertion within the function but when trying to see it in main nothing happens.

node *tree = NULL;
insert(tree, 4321);
printf("outer: %d\n", tree->data);

void insert(node* tree, int data) {
  if (tree == NULL) {
    tree = new_node(data);
    printf("inner: %d\n", tree->data);
  }
}

This gives:

inner: 4321

It should be:

inner: 4321
outer: 4321

Body:
The problem is, tree is passed as an argument to the function, and by-status which is a pass-by-value in C. Any change made to tree itself inside the function will not be reflected back to the caller.

You need to pass a pointer to tree, if you want to modify tree from the called function.

Something like

void insert(node** tree, int data) {
  if (*tree == NULL) {
    *tree = new_node(data);
    printf("inner: %d\n", (*tree)->data);
  }
}

and call it like

insert(&tree, 4321);


问:
What is the alt.topo_feature parameter for country India
I am learning visualization using Altair python library. In the example section, I see codes for states of the USA.

```<code>states = alt.topo_feature(data.us_10m.url, feature='states')
</code>```

I was wondering if the same can be applied to other countries like India, Brazil or China.

Where should I look to get the states for other countries? I want to plot visualization using Altair Python's library for visualization

```<code>import altair as alt
states = alt.topo_feature(data.us_10m.url, feature='states')
</code>```

答: The data.us_10m dataset contains borders of US states and counties at 10-meter-resolution. If you search the internet for "India topojson", you should be able to find a suitable dataset that covers India.

Body:
I am learning visualization using Altair python library. In the example section, I see codes for states of the USA.

states = alt.topo_feature(data.us_10m.url, feature='states')

I was wondering if the same can be applied to other countries like India, Brazil or China.

Where should I look to get the states for other countries? I want to plot visualization using Altair Python's library for visualization

import altair as alt
states = alt.topo_feature(data.us_10m.url, feature='states')


问:
Running database script with Paramiko fails with exit code
The output file is created before the database results are available.

Passing a simple os command works fine:

```<code># command = "whoami > result.txt"
</code>```

works fine. I would get my user name when I open the result.txt file. The problem is waiting for the database to return the result. It comes out empty even though there is data returned from the actual query

import paramiko

def get_report(command):
    # reference: https://stackoverflow.com/questions/5193886/python-paramiko-issue-while-closing-the-connection.
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('server123', username='username', password='password')

    stdin, stdout, stderr = client.exec_command(command)
    exit_status = stdout.channel.recv_exit_status()

    if exit_status == 0:
        print("File processed")
    else:
        print("Error", exit_status)
    client.close()

command = "sql_query.script > result.txt"
get_report(command=command)
```

I expect to received a data set of first_name, last_name, and location but instead I get Error 108.

答:
If a command does not work, when executed using Paramiko, debug it by reading its error output.

Use stderr.readlines() for that.

If the same command works in regular shell, but not in Paramiko, the problem is usually related to a different environment used by the SSH "exec" channel, which is used by SSHClient.exec_command. See:

Some Unix commands fail with "<command> not found", when executed using Python Paramiko exec_command

Environment variable differences when using Paramiko

Body:
The output file is created before the database results are available.

Passing a simple os command works fine:

# command = "whoami > result.txt"

works fine. I would get my user name when I open the result.txt file. The problem is waiting for the database to return the result. It comes out empty even though there is data returned from the actual query

import paramiko

def get_report(command):
    # reference: https://stackoverflow.com/questions/5193886/python-paramiko-issue-while-closing-the-connection.
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('server123', username='username', password='password')

    stdin, stdout, stderr = client.exec_command(command)
    exit_status = stdout.channel.recv_exit_status()

    if exit_status == 0:
        print("File processed")
    else:
        print("Error", exit_status)
    client.close()

command = "sql_query.script > result.txt"
get_report(command=command)

I expect to received a data set of first_name, last_name, and location but instead I get Error 108.


问:
DomPDF does not download file for AJAX request on Laravel
I'm working on 'DomPDF' using Ajax Post request on Laravel project. Below is ajax code.

```<code>       $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url:"{{ route('screen.pdfticket') }}",
            method:"POST",
            data:{
                id:$('#screenid').val()
            },
            success:function(data){
                console.log(data);
            }
        });
</code>```

And below is code in controller.

```<code>    $customPaper = array(0,0,216,158);
    $pdf->loadView("screen.ticket" , [
        'clinic' => 'clinic name' ,
        'queno' => $screen->que
    ])->setPaper($customPaper, 'landscape');
    return $pdf->download($screen->que .'.pdf');
</code>```

I can get correct response but it's not readable format. I would like to save in pdf format after ajax called success instead. Any advise or guidance would be greatly appreciated, Thanks.

答:
Since you're making the request using AJAX, you need a way to have the browser load the resource.

There are ways to go but not limited to the following:

Return the resource URL in the response to the AJAX request then make a separate browser request to load the resource.

Make a blob of the resource response to the AJAX request then load it from the blob's URL.

 This is shown in the example below.

```<code>function downloadFile(response) {
  var blob = new Blob([response], {type: 'application/pdf'})
  var url = URL.createObjectURL(blob);
  location.assign(url);
}

$.ajax({
  url: "{{ route('screen.pdfticket') }}",
  method: 'POST',
  data: {
    id: $('#screenid').val()
  }
})
.done(downloadFile);
</code>```

Body:
I'm working on 'DomPDF' using Ajax Post request on Laravel project. Below is ajax code.

       $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url:"{{ route('screen.pdfticket') }}",
            method:"POST",
            data:{
                id:$('#screenid').val()
            },
            success:function(data){
                console.log(data);
            }
        });

And below is code in controller.

    $customPaper = array(0,0,216,158);
    $pdf->loadView("screen.ticket" , [
        'clinic' => 'clinic name' ,
        'queno' => $screen->que
    ])->setPaper($customPaper, 'landscape');
    return $pdf->download($screen->que .'.pdf');

I can get correct response but it's not readable format. I would like to save in pdf format after ajax called success instead. Any advise or guidance would be greatly appreciated, Thanks.

Body:
Since you're making the request using AJAX, you need a way to have the browser load the resource.

There are ways to go but not limited to the following:

Return the resource URL in the response to the AJAX request then make a separate browser request to load the resource.

Make a blob of the resource response to the AJAX request then load it from the blob's URL.

 This is shown in the example below.

function downloadFile(response) {
  var blob = new Blob([response], {type: 'application/pdf'})
  var url = URL.createObjectURL(blob);
  location.assign(url);
}

$.ajax({
  url: "{{ route('screen.pdfticket') }}",
  method: 'POST',
  data: {
    id: $('#screenid').val()
  }
})
.done(downloadFile);