问:
How to compute column sum on the basis of other column value in pandas dataframe?

P
T1
T2
T3

0
1
2
3

1
1
2
0

2
3
1
2

3
1
0
2

In the above pandas dataframe df,
I want to add columns on the basis of the value of column 'P'.

```<code>if df['P'] == 0: 0
if df['P'] == 1: T1 (=1)
if df['P'] == 2: T1+T2 (=3+1=4)
if df['P'] == 3: T1+T2+T3 (=1+0+2=3)
</code>```

In other words, I want to add from T1 to TN if df['P'] == N.
How can I implement this with Python code?

答:
EDIT:

For sum values by P column create mask by broadcasting np.arange by length of filtered columns by DataFrame.filter, compare by P values and this mask pass to DataFrame.where, last use sum per rows:

```<code>np.random.seed(20)

c = [f'{x}{i + 1}' for x in ['T','U','V'] for i in range(3)]
df = pd.DataFrame(np.random.randint(4, size=(10,10)), columns=['P'] + c)

arrP = df['P'].to_numpy()[:, None]

for c in ['T','U','V']:
    df1 = df.filter(regex=rf'^{c}')
    df[f'{c}_SUM'] = df1.where(np.arange(len(df1.columns)) < arrP, 0).sum(axis=1)
print (df)
   P  T1  T2  T3  U1  U2  U3  V1  V2  V3  T_SUM  U_SUM  V_SUM
0  3   2   3   3   0   2   1   0   3   2      8      3      5
1  3   2   0   2   0   1   2   2   3   3      4      3      8
2  0   1   2   2   2   0   1   1   3   1      0      0      0
3  3   2   2   2   1   3   2   1   3   2      6      6      6
4  3   1   1   3   1   2   2   0   2   3      5      5      5
5  2   3   2   3   1   1   1   0   3   0      5      2      3
6  2   3   2   3   3   3   2   1   1   2      5      6      2
7  3   2   0   2   1   1   2   2   2   3      4      4      7
8  2   2   1   0   2   2   0   3   3   0      3      4      6
9  2   2   3   2   2   3   2   2   1   1      5      5      3
</code>```

Body:
P
T1
T2
T3

0
1
2
3

1
1
2
0

2
3
1
2

3
1
0
2

In the above pandas dataframe df,
I want to add columns on the basis of the value of column 'P'.

if df['P'] == 0: 0
if df['P'] == 1: T1 (=1)
if df['P'] == 2: T1+T2 (=3+1=4)
if df['P'] == 3: T1+T2+T3 (=1+0+2=3)

In other words, I want to add from T1 to TN if df['P'] == N.
How can I implement this with Python code?

Body:
EDIT:

For sum values by P column create mask by broadcasting np.arange by length of filtered columns by DataFrame.filter, compare by P values and this mask pass to DataFrame.where, last use sum per rows:

np.random.seed(20)

c = [f'{x}{i + 1}' for x in ['T','U','V'] for i in range(3)]
df = pd.DataFrame(np.random.randint(4, size=(10,10)), columns=['P'] + c)

arrP = df['P'].to_numpy()[:, None]

for c in ['T','U','V']:
    df1 = df.filter(regex=rf'^{c}')
    df[f'{c}_SUM'] = df1.where(np.arange(len(df1.columns)) < arrP, 0).sum(axis=1)
print (df)
   P  T1  T2  T3  U1  U2  U3  V1  V2  V3  T_SUM  U_SUM  V_SUM
0  3   2   3   3   0   2   1   0   3   2      8      3      5
1  3   2   0   2   0   1   2   2   3   3      4      3      8
2  0   1   2   2   2   0   1   1   3   1      0      0      0
3  3   2   2   2   1   3   2   1   3   2      6      6      6
4  3   1   1   3   1   2   2   0   2   3      5      5      5
5  2   3   2   3   1   1   1   0   3   0      5      2      3
6  2   3   2   3   3   3   2   1   1   2      5      6      2
7  3   2   0   2   1   1   2   2   2   3      4      4      7
8  2   2   1   0   2   2   0   3   3   0      3      4      6
9  2   2   3   2   2   3   2   2   1   1      5      5      3


来源: stackexchange

问:
Vuejs-Multiselect how to get just the selected option when enabling the multiple option
I am new to VueJS, and i am using Vuejs-Multiselect, enabling the multiple option.

I need to pass the selected value to the toggleSelected method .

In this pen, there is a simulation : https://codepen.io/amrigo/pen/arvadE

I see the values are concatenated, eg.: when i choose the first value i can see using console.log : [object Object], choosing the second [object Object],[object Object] and so on.

How can i get just the selected value and so the code value from the options array?

In the html i do use :

```<code><div id="app">
          <multiselect
            v-model="value"
            :options="options"
            :multiple="true"
            track-by="name"
            :hide-selected="true"
            :close-on-select="false"
            :custom-label="customLabel"
            :searchable="false"
            placeholder=""
            :show-labels="false"
            @input="toggleSelected(value)"
            >
          </multiselect>
            ```{{ value }}```
        </div>
</code>```

In the script i do use :

```<code>new Vue({
            components: {
                Multiselect: VueMultiselect.default
            },
            data: {
                value: [],
                options: [
                        { name: 'Agriculture', code: '1' },
                        { name: 'Police', code: '2' },
                        { name: 'Medical', code: '3' }
                ]
            },
          methods: {
            customLabel (option) {
              return `${option.name}`
            },
            toggleSelected(value) {
              alert( `${value.name}` )
              console.log(' >> '+ `${value}` )
            }
          }
        }).$mount('#app')
</code>```

答:
From the documentation,  to get the selected option you use the @select event.
Example:</p>
```<code><multiselect
    // ... all your props*
    @select="optionSelected">
</multiselect>

// dont put the brackets (),
  //js will automatically pass the values to toggleSelected
//In your method:
optionSelected(option, id) {
console.log(option)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to VueJS, and i am using Vuejs-Multiselect, enabling the multiple option.

I need to pass the selected value to the toggleSelected method .

In this pen, there is a simulation : https://codepen.io/amrigo/pen/arvadE

I see the values are concatenated, eg.: when i choose the first value i can see using console.log : [object Object], choosing the second [object Object],[object Object] and so on.

How can i get just the selected value and so the code value from the options array?

In the html i do use :

          <multiselect
            v-model="value"
            :options="options"
            :multiple="true"
            track-by="name"
            :hide-selected="true"
            :close-on-select="false"
            :custom-label="customLabel"
            :searchable="false"
            placeholder=""
            :show-labels="false"
            @input="toggleSelected(value)"
            >
          </multiselect>

{{ value }}

In the script i do use :

new Vue({
            components: {
                Multiselect: VueMultiselect.default
            },
            data: {
                value: [],
                options: [
                        { name: 'Agriculture', code: '1' },
                        { name: 'Police', code: '2' },
                        { name: 'Medical', code: '3' }
                ]
            },
          methods: {
            customLabel (option) {
              return `${option.name}`
            },
            toggleSelected(value) {
              alert( `${value.name}` )
              console.log(' >> '+ `${value}` )
            }
          }
        }).$mount('#app')

Body:
From the documentation,  to get the selected option you use the @select event.
Example:

<multiselect
    // ... all your props*
    @select="optionSelected">
</multiselect>

// dont put the brackets (),
  //js will automatically pass the values to toggleSelected
//In your method:
optionSelected(option, id) {
console.log(option)
}


问:
Detecting a mobile browser
I'm looking for a function that returns a boolean value if the user is using a mobile browser or not.

I know that I can use navigator.userAgent and write that function by using regex, but user-agents are too various for different platforms. I doubt that matching all possible devices would be easy, and I think this problem has been solved many times so there should be some kind of complete solution for such a task.

I was looking at this site, but sadly the script is so cryptic that I have no idea how to use it for my purpose, which is to create a function that returns true/false.

答:
Feature Detection

const isMobile = localStorage.mobile || window.navigator.maxTouchPoints > 1;
```

WORKS IN CHROME + SAFARI as of 2022-02-07 :: combining feature detections and trying everything in this thread and other sites. The localStorage.mobile works in Chrome mobile; the latter works in Safari mobile. Does not trigger desktop browsers with or w/o the dev-tools open and/or on a mobile simulator.  As of writing this, it triggers a real mobile browser but not desktops.

Please consider

I've also tested this on a Lenovo X1 Yoga (keyboard or tablet-mode) on Win10

localStorage.mobile is undefined no matter what

When the laptop is in keyboard mode:
window.navigator.maxTouchPoints is 1
→ isMobile is false

When the keyboard is flipped back and the laptop is in tablet-mode:
window.navigator.maxTouchPoints is 10
→ isMobile is true

Title: Detecting a mobile browser

Body:
Feature Detection

const isMobile = localStorage.mobile || window.navigator.maxTouchPoints > 1;

WORKS IN CHROME + SAFARI as of 2022-02-07 :: combining feature detections and trying everything in this thread and other sites. The localStorage.mobile works in Chrome mobile; the latter works in Safari mobile. Does not trigger desktop browsers with or w/o the dev-tools open and/or on a mobile simulator.  As of writing this, it triggers a real mobile browser but not desktops.

Please consider

I've also tested this on a Lenovo X1 Yoga (keyboard or tablet-mode) on Win10

localStorage.mobile is undefined no matter what

When the laptop is in keyboard mode:
window.navigator.maxTouchPoints is 1
→ isMobile is false

When the keyboard is flipped back and the laptop is in tablet-mode:
window.navigator.maxTouchPoints is 10
→ isMobile is true


问:
Issue in functioning of radio input in dynamically adding row through jQuery
A new row is dynamically creating on clicking "add Row" button through function in jQuery.
But when I select radio input in new row then selected value of previous radio input is removing.
Please run and see the codes as below:
enter image description here

function add_row(table_row_count)
{
    $("#add-row_"+table_row_count).hide();
    $("#delete-row_"+table_row_count).hide();

    var table_row_count = parseInt(table_row_count);

    table_row_count += 1;

    var markup =
    '
'+
    ''+table_row_count+'	'+
    ''+
          'Value in Range? :'+
          '<input type="radio" name="option" id="option_1_row_'+table_row_count+'" value="1"  > YES'+
          '<input type="radio" name="option" id="option_2_row_'+table_row_count+'" value="2"  > NO'+
    '	'+
    ''+
            'Range From :
'+
            '<input type="text" name="capacity_from[]" id="capacity_from_'+table_row_count+'"  />'+
    '	'+
    ''+
            'Range Upto :
'+
            '<input type="text" name="capacity_upto[]" id="capacity_upto_'+table_row_count+'" />'+
     '	'+
    ' Add Row	'+
    ' Delete Row	'+
    '
';

    var table = $("#tbl_details tbody");
    table.append(markup);

}

function delete_row(table_row_count)
{
    var r = confirm("Are you sure to delete row");
    if(r == false){
        return;
    }

    var table_row_count = parseInt(table_row_count);
    var previous_row = table_row_count - 1;
    $("#add-row_"+previous_row).show();
    if(previous_row != 1){
        $("#delete-row_"+previous_row).show();
    }

    $("#tbl_row_"+table_row_count).remove();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
        <h3>Enter Details</h3>
        <table class="table table-striped" id="tbl_details">
        <tbody>
        <tr id="row_1">
        <td>1.</td>
        <td>
          <label>Value in Range? :</label>
          <input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
          <input type="radio" name="option" id="option_2_row_1" value="2" > NO
        </td>
        <td id="capacity_from_row_1" >
            <label>Range From :</label><br>
            <input type="text" name="capacity_from[]" id="capacity_from_1" />
        </td>
        <td>
            <label id="lbl_capacity_range_1" >Range Upto :</label><br>
            <input type="text" name="capacity_upto[]" id="capacity_upto_1" />
        </td>
        <td class="align-middle"><i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row</td>
        <td class="align-middle"></td>
        </tr>
        </tbody>
        </table>
</body>
</html></code>```

How to solve the issue. kindly help me.
Thanks in advance.

答: *** Change dynamic radio input name. here, your code create all dynamic radio input with the same name. ***</p>

Body:
A new row is dynamically creating on clicking "add Row" button through function in jQuery.
But when I select radio input in new row then selected value of previous radio input is removing.
Please run and see the codes as below:
enter image description here

function add_row(table_row_count)
{
    $("#add-row_"+table_row_count).hide();
    $("#delete-row_"+table_row_count).hide();

    var table_row_count = parseInt(table_row_count);

    table_row_count += 1;

    var markup =
    '
'+
    ''+table_row_count+'	'+
    ''+
          'Value in Range? :'+
          '<input type="radio" name="option" id="option_1_row_'+table_row_count+'" value="1"  > YES'+
          '<input type="radio" name="option" id="option_2_row_'+table_row_count+'" value="2"  > NO'+
    '	'+
    ''+
            'Range From :
'+
            '<input type="text" name="capacity_from[]" id="capacity_from_'+table_row_count+'"  />'+
    '	'+
    ''+
            'Range Upto :
'+
            '<input type="text" name="capacity_upto[]" id="capacity_upto_'+table_row_count+'" />'+
     '	'+
    ' Add Row	'+
    ' Delete Row	'+
    '
';

    var table = $("#tbl_details tbody");
    table.append(markup);

}

function delete_row(table_row_count)
{
    var r = confirm("Are you sure to delete row");
    if(r == false){
        return;
    }

    var table_row_count = parseInt(table_row_count);
    var previous_row = table_row_count - 1;
    $("#add-row_"+previous_row).show();
    if(previous_row != 1){
        $("#delete-row_"+previous_row).show();
    }

    $("#tbl_row_"+table_row_count).remove();

}

Enter Details

        1.

          Value in Range? :
          <input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
          <input type="radio" name="option" id="option_2_row_1" value="2" > NO

            Range From :

            <input type="text" name="capacity_from[]" id="capacity_from_1" />

            Range Upto :

            <input type="text" name="capacity_upto[]" id="capacity_upto_1" />

         Add Row

How to solve the issue. kindly help me.
Thanks in advance.


问:
Get a JSONObject of a JSONArray with Value by jQuery
Hi assume that I have a JSON like this:

```<code>var myJson = [{"id":"111","name":"aaa","surname":"bbb"},
     {"id":"222","name":"ccc","surname":"ddd"}]
</code>```

is there any function to get one of jsonobject with a value of jsonobject?
I mean maybe I know that id is 111 how can get the jsonobject with id=111, I don't want to get it with loop I mean is there just function to do it with jQuery?

答:
You have an array with two objects in it.  To find which array element (if any) has an object with id=="111", you would have to search the array and look at each object to find which one has the desired object in it.

When using a plain array, there is no magic way to find something in it without looping through the array.  If keys are unique and order is not important, you can use an object instead of an array to directly index into a given object without searching for it.  But given the data structure you or some piece of code has to loop through the array.

```<code>function findId(target, array) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].id == target) {
            return(i);
        }
    }
    return(-1);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi assume that I have a JSON like this:

var myJson = [{"id":"111","name":"aaa","surname":"bbb"},
     {"id":"222","name":"ccc","surname":"ddd"}]

is there any function to get one of jsonobject with a value of jsonobject?
I mean maybe I know that id is 111 how can get the jsonobject with id=111, I don't want to get it with loop I mean is there just function to do it with jQuery?

Body:
You have an array with two objects in it.  To find which array element (if any) has an object with id=="111", you would have to search the array and look at each object to find which one has the desired object in it.

When using a plain array, there is no magic way to find something in it without looping through the array.  If keys are unique and order is not important, you can use an object instead of an array to directly index into a given object without searching for it.  But given the data structure you or some piece of code has to loop through the array.

function findId(target, array) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].id == target) {
            return(i);
        }
    }
    return(-1);
}


问:
How to add y bar in ggplot2() annotate?
I'm trying to add an annotation in my ggplot using annotate, but I was wondering if I can add the expression x bar (in latex it should be $\bar{x}$) in there.</p>

答:
Using ?plotmath and setting parse=TRUE you could do:

library(ggplot2)

ggplot(data.frame(x = 1, y = 1), aes(x, y)) +
  annotate(geom = "text", x = 1, y = 1, parse = TRUE, label ="bar(x)", size = 10)
```

Title: How to add y bar in ggplot2() annotate?


问:
Unity Hololens 2 Anchor persistant between sessions without cloud connexion
I am building an app on Unity 2020.3.19 version / MRTK 2.7.
I want to save localy the position of an object and to reload it on another session without any wifi connexion.
I have been locking for solutions but WSA obsolete/ qrcode for positioning microsoft solution crashing ...
How should I do?</p>

答: We recommend that you use World Locking Tools for all your hologram positioning needs. To persist spatial coordinate systems, we can enable AutoSave & AutoLoad on the World Locking Tools Manager, World Locking Tools will restore Unity's coordinate system relative to the physical world across sessions on the HoloLens family of devices. For more information please see: World locking and spatial anchors in Unity</p>


问:
Javascript - firebase.auth().onAuthStateChanged not firing upon login/logout
I have the following code:

```<code>var config = {
       apiKey: "xxxxx",
       authDomain: "xxxxx",
       databaseURL: "xxxxx",
       projectId: "xxxxx",
       storageBucket: "xxxxx",
       messagingSenderId: "xxxxx"
};

firebase.initializeApp(config);

$("#loginButton").on('click', function(){
    logIn($("#email").val(), $("#pwd").val());
});

$("#logoutButton").on('click', function(){
   firebase.auth().signOut();
   console.log("clicked logout button");
});

function logIn(email, password){
   firebase.auth().signInWithEmailAndPassword(email,    password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(error.message);
  });
}

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      console.log("Signed in");
      firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
        // Send token to your backend via HTTPS
        // ...
        console.log("Token = " + idToken);
        console.log("Logged in!");
        $("#loginButton").val(idToken);
        $("#loginForm").submit();
      }).catch(function(error) {
           // Handle error
           console.log(error);
      });
   }
   else{
       console.log("User signed out");
   }
});
</code>```

What I am trying to accomplish here is: The user fills the email and password fields, click on a button with id="loginButton", I sign in, get the token id and send it to server (Is this form hackish way of sending it recommended?) and verify the token id through the Admin SDK in my express app (Node.js).

The point is. The user does sign in and sign out (By refreshing the page I can see that "Signed in" and "User signed out" are printed).

But why is onAuthStateChanged called only once when it should be observing/listening to every change on auth state?

Why am I able to sign in and out but onAuthStateChanged is called only at the beginning (when page loads) and not called anymore upon button clicks (loginButton and logoutButton)?

答:
Although this is an old question it seems like some people are still struggling with this.

I was having the same problem with onAuthStateChange not being fired on SignOut and I realized it was because I was unsubscribing from the listener before I signed out, so that by the time I signed out there was no listener anymore.

Body:
I have the following code:

var config = {
       apiKey: "xxxxx",
       authDomain: "xxxxx",
       databaseURL: "xxxxx",
       projectId: "xxxxx",
       storageBucket: "xxxxx",
       messagingSenderId: "xxxxx"
};

firebase.initializeApp(config);

$("#loginButton").on('click', function(){
    logIn($("#email").val(), $("#pwd").val());
});

$("#logoutButton").on('click', function(){
   firebase.auth().signOut();
   console.log("clicked logout button");
});

function logIn(email, password){
   firebase.auth().signInWithEmailAndPassword(email,    password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(error.message);
  });
}

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      console.log("Signed in");
      firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
        // Send token to your backend via HTTPS
        // ...
        console.log("Token = " + idToken);
        console.log("Logged in!");
        $("#loginButton").val(idToken);
        $("#loginForm").submit();
      }).catch(function(error) {
           // Handle error
           console.log(error);
      });
   }
   else{
       console.log("User signed out");
   }
});

What I am trying to accomplish here is: The user fills the email and password fields, click on a button with id="loginButton", I sign in, get the token id and send it to server (Is this form hackish way of sending it recommended?) and verify the token id through the Admin SDK in my express app (Node.js).

The point is. The user does sign in and sign out (By refreshing the page I can see that "Signed in" and "User signed out" are printed).

But why is onAuthStateChanged called only once when it should be observing/listening to every change on auth state?

Why am I able to sign in and out but onAuthStateChanged is called only at the beginning (when page loads) and not called anymore upon button clicks (loginButton and logoutButton)?


问:
case-insensitive alphabetical sorting of nested lists
i'm trying to sort this nested list by inner's list first element:

```<code>ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
    print i
}
</code>```

by default python considers A > a, hence the output i get is:

```<code>['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]
</code>```

i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?

Edited:

Jarret and Brian, your
  assumptions about parenthesis were
  right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!

答:
```<code>ak.sort(cmp=lambda x, y: cmp(x[0].lower(), y[0].lower()))
</code>```

Did you forget the parens in x[0].lower()?

OwnerDisplayName: Alex

LastEditorDisplayName: Alex

ContentLicense: CC BY-SA 2.5

Body:
i'm trying to sort this nested list by inner's list first element:

ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
    print i
}

by default python considers A > a, hence the output i get is:

['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]

i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?

Edited:

Jarret and Brian, your
  assumptions about parenthesis were
  right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!

Body:
ak.sort(cmp=lambda x, y: cmp(x[0].lower(), y[0].lower()))

Did you forget the parens in x[0].lower()?

OwnerDisplayName: Brian Campbell


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
In addition to short-circuiting, another thing to keep in mind is that doing a bitwise logic operation on values that can be other than 0 or 1 has a very different meaning than conditional logic.  While it USUALLY is the same for | and ||, with & and && you get very different results (e.g. 2 & 4 is 0/false while 2 && 4 is 1/true).

If the thing you're getting from a function is actually an error code and you're testing for non-0-ness, this can matter quite a lot.

This isn't as much of an issue in Java where you have to explicitly typecast to boolean or compare with 0 or the like, but in other languages with similar syntax (C/C++ et al) it can be quite confusing.

Also, note that & and | can only apply to integer-type values, and not everything that can be equivalent to a boolean test.  Again, in non-Java languages, there are quite a few things that can be used as a boolean with an implicit != 0 comparison (pointers, floats, objects with an operator bool(), etc.) and bitwise operators are almost always nonsensical in those contexts.

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.


问:
Counting means from each row
I am using Jupyter notebook to get this data:

```<code>df = ascii.read ('http://www.astrouw.edu.pl/cgi-asas/asas_cgi_get_data?110545-5433.5,asas3')
</code>```

colums 2-6 are magnitudes. I would like to remove min and max of each 5 possibilities in a row and count mean of remaining three magnitudes.

How would I do that?
And how can I rename the columns?

Title: Counting means from each row

Body:
I am using Jupyter notebook to get this data:

df = ascii.read ('http://www.astrouw.edu.pl/cgi-asas/asas_cgi_get_data?110545-5433.5,asas3')

colums 2-6 are magnitudes. I would like to remove min and max of each 5 possibilities in a row and count mean of remaining three magnitudes.

How would I do that?
And how can I rename the columns?

Body:
One approach is to transform your table into a pandas dataframe and then calculate the centered mean:

import pandas as pd
import numpy as np
import io
from io import StringIO
from astropy.io import ascii

df = ascii.read ('http://www.astrouw.edu.pl/cgi-asas/asas_cgi_get_data?110545-5433.5,asas3')
ascii.write(df,'values1.csv', format='csv', fast_writer=False)

DF = pd.read_csv('values1.csv', sep=",")
DF_small = DF[['col2','col3','col4','col5','col6']]

DF_small['centered mean'] = DF_small.apply(lambda x: x.drop([x.idxmax(),x.idxmin()]).mean() , axis = 1)

as you can see, we dropped the max and min values. This returns

col2    col3    col4    col5    col6  centered mean
0    11.630  11.623  11.640  11.648  11.658      11.639333
1    11.552  11.541  11.592  11.627  11.629      11.590333
2    11.704  11.739  11.697  11.683  11.699      11.700000
3    11.688  11.693  11.718  11.752  11.728      11.713000
4    11.654  11.677  11.680  11.702  11.711      11.686333
..      ...     ...     ...     ...     ...            ...
626  11.613  11.564  11.631  11.632  11.613      11.619000
627  11.672  11.618  11.683  11.688  11.698      11.681000
628  11.654  11.614  11.670  11.672  11.663      11.662333
629  11.536  11.524  11.559  11.571  11.569      11.554667
630  11.647  11.641  11.660  11.664  11.673      11.657000

UPDATE:

If you want to keep all other columns:

DF['centered mean'] = DF[['col2','col3','col4','col5','col6']].apply(lambda x: x.drop([x.idxmax(),x.idxmin()]).mean() , axis = 1)

gives:

col1    col2    col3    col4    col5    col6   col7   col8   col9  \
0    3116.55170  11.630  11.623  11.640  11.648  11.658  0.054  0.054  0.057
1    1885.76359  11.552  11.541  11.592  11.627  11.629  0.037  0.049  0.035
2    1888.79953  11.704  11.739  11.697  11.683  11.699  0.044  0.064  0.045
3    1899.81685  11.688  11.693  11.718  11.752  11.728  0.039  0.046  0.032
4    1915.74475  11.654  11.677  11.680  11.702  11.711  0.038  0.054  0.037
..          ...     ...     ...     ...     ...     ...    ...    ...    ...
626  3385.79064  11.613  11.564  11.631  11.632  11.613  0.041  0.051  0.040
627  3391.76317  11.672  11.618  11.683  11.688  11.698  0.035  0.048  0.032
628  3448.69080  11.654  11.614  11.670  11.672  11.663  0.038  0.053  0.036
629  3450.66562  11.536  11.524  11.559  11.571  11.569  0.047  0.068  0.041
630  3452.79152  11.647  11.641  11.660  11.664  11.673  0.044  0.066  0.040

     col10  col11 col12   col13  centered mean
0    0.067  0.079     B   99788      11.639333
1    0.042  0.054     A    2479      11.590333
2    0.054  0.064     A    2974      11.700000
3    0.039  0.049     A    3272      11.713000
4    0.044  0.054     A    4974      11.686333
..     ...    ...   ...     ...            ...
626  0.045  0.052     A  126087      11.619000
627  0.037  0.045     A  126876      11.681000
628  0.042  0.049     A  134925      11.662333
629  0.045  0.049     B  135255      11.554667
630  0.048  0.054     A  135545      11.657000

[631 rows x 14 columns]


问:
Apache Camel, multicast and loop
I'm using Apache Camel for routing Rest request.
I want to get some count of messages from queue. But i have troubles with it.
I'm trying following code:

```<code>from("direct:read_some_messages")
    .multicast(new GroupedBodyAggregationStrategy(), false)
      .loop(count)
        .pollEnrich().simple(AMQ_PATH_TEMPLATE).timeout(receiveTimeout).end()
      .end()
    .end()
    .marshal().json(JsonLibrary.Jackson)
    .end();
</code>```

But in sush way multicast add only 1 result of pollEnrich.
Can anyone help me with it? Or may it can be solved another way without multicast?

p.s. i'm new in camel

答:
I get needed result sush way:

```<code>  from("direct:read_some_messages")
    .loopDoWhile(simple("${header[loop_counter]} > 0"))
      .pollEnrich().simple(AMQ_PATH_TEMPLATE).timeout(receiveTimeout)
      .aggregationStrategy(new ArrayListAggregationStrategy()).id("pollEnrich_from_activeMQ_with_page_id")
      .end()
    .end()
    .marshal().json(JsonLibrary.Jackson)
    .end();
</code>```

In ArrayListAggregationStrategy i'm decreasing loop_counter and adding some logic to stop loop beforehand if need.

Title: Apache Camel, multicast and loop

Body:
I'm using Apache Camel for routing Rest request.
I want to get some count of messages from queue. But i have troubles with it.
I'm trying following code:

from("direct:read_some_messages")
    .multicast(new GroupedBodyAggregationStrategy(), false)
      .loop(count)
        .pollEnrich().simple(AMQ_PATH_TEMPLATE).timeout(receiveTimeout).end()
      .end()
    .end()
    .marshal().json(JsonLibrary.Jackson)
    .end();

But in sush way multicast add only 1 result of pollEnrich.
Can anyone help me with it? Or may it can be solved another way without multicast?

p.s. i'm new in camel

Body:
I get needed result sush way:

  from("direct:read_some_messages")
    .loopDoWhile(simple("${header[loop_counter]} > 0"))
      .pollEnrich().simple(AMQ_PATH_TEMPLATE).timeout(receiveTimeout)
      .aggregationStrategy(new ArrayListAggregationStrategy()).id("pollEnrich_from_activeMQ_with_page_id")
      .end()
    .end()
    .marshal().json(JsonLibrary.Jackson)
    .end();

In ArrayListAggregationStrategy i'm decreasing loop_counter and adding some logic to stop loop beforehand if need.


问:
How do I store a list of int in one mysql colum?
I would like to make a shopingcart on my website and when you press buy it stores the things in your shoppingcart in a list of the id’s from the products. I want to safe the list in an mysql table with an id for the cart. What‘s the best type for that?</p>

答:
You're talking about a one-to-many relation, so don't store an array of integers in your relational database model.

Instead, you should create a second record type (table) named cart_items or similar, which holds the information about the items and is then related to the cart itself via a foreign key. This allows you to also track the quantity of items in the cart and additional information, for instance:

tbl_cart:

id
user_id
created
modified

1
1
2022-02-08 12:20:20
NULL

tbl_cart_items:

id
cart_id
name
qty
price
total
added

1
1
Lemon
1
0.87
0.87
2022-02-08 12:20:20

2
1
Apple
2
0.50
1.00
2022-02-08 12:25:20

3
1
Banana
1
0.65
0.65
2022-02-08 12:30:21


问:
How to kill app on button press
I have an app that has a lot of activities. In the "Settings" page there is a delete account button that is supposed to reset all the saved variables and exit the app. I haven't found a simple solution to exiting the app (eg calling finish only destroys the current activity) What do I call to close the app on a button press (eg when I reopen the the app it should start from the first activity)</p>

答:
Use this:

```<code>Process.killProcess(Process.myPid());
</code>```

Or there is another more safer approach. Just subclass all of your activities, from one parent Activity and keep list of all alive activities and then when necessary close them all using exit():

```<code>public class ControlActivity extends Activity
{
   private static ArrayList<Activity> activities=new ArrayList<Activity>();

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       activities.add(this);
   }

   @Override
   public void onDestroy()
   {
       super.onDestroy();
       activities.remove(this);
       if(activities.size()==0) //last activity
           //release resources and so on
   }

   //close all activities, when necessary
   public static void exit()
   {
      for(Activity activity:activities)
          activity.finish();
   }
}
</code>```

Title: How to kill app on button press

Body:
Use this:

Process.killProcess(Process.myPid());

Or there is another more safer approach. Just subclass all of your activities, from one parent Activity and keep list of all alive activities and then when necessary close them all using exit():

public class ControlActivity extends Activity
{
   private static ArrayList<Activity> activities=new ArrayList<Activity>();

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       activities.add(this);
   }

   @Override
   public void onDestroy()
   {
       super.onDestroy();
       activities.remove(this);
       if(activities.size()==0) //last activity
           //release resources and so on
   }

   //close all activities, when necessary
   public static void exit()
   {
      for(Activity activity:activities)
          activity.finish();
   }
}


问:
How to login to ArgoCD CLI non-interactive in CI like GitHub Actions?
We have a full-blown setup using AWS EKS with Tekton installed and want to use ArgoCD for application deployment.

As the docs state we installed ArgoCD on EKS in GitHub Actions with:

```<code>  - name: Install ArgoCD
    run: |
      echo "--- Create argo namespace and install it"
      kubectl create namespace argocd --dry-run=client -o yaml | kubectl apply -f -
      kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
</code>```

We also exposed the ArgoCD server (incl. dashboard) as the docs told us:

```<code>  - name: Expose ArgoCD Dashboard
    run: |
      echo "--- Expose ArgoCD Dashboard via K8s Service"
      kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'

      echo "--- Wait until Loadbalancer url is present (see https://stackoverflow.com/a/70108500/4964553)"
      until kubectl get service/argocd-server -n argocd --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done
</code>```

Finally we installed argocd CLI with brew:

```<code>      echo "--- Install ArgoCD CLI"
      brew install argocd
</code>```

Now how can we do a argocd login with GitHub Actions (without human interaction)? The argocd login command wants a username and password...

答:
The same docs tell us how to extract the password for argo with:

```<code>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo
</code>```

Obtaining the ArgoCD server's hostname is also no big deal using:

```<code>kubectl get service argocd-server -n argocd --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}'
</code>```

And as the argocd login command has the parameters --username and --password, we can craft our login command like this:

```<code>argocd login $(kubectl get service argocd-server -n argocd --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}') --username admin --password $(kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo) --insecure
</code>```

Mind the --insecure to prevent the argo CLI from asking things like WARNING: server certificate had error: x509: certificate is valid for localhost, argocd-server, argocd-server.argocd, argocd-server.argocd.svc, argocd-server.argocd.svc.cluster.local, not a5f715808162c48c1af54069ba37db0e-1371850981.eu-central-1.elb.amazonaws.com. Proceed insecurely (y/n)?.

The successful login should somehow look like this in the GitHub Actions UI (see a full log here):

```<code>'admin:login' logged in successfully
Context 'a5f715808162c48c1af54069ba37db0e-1371850981.eu-central-1.elb.amazonaws.com' updated
</code>```

Now your GitHub Actions workflow should be able to interact with the ArgoCD server.

Prevent error FATA[0000] dial tcp: lookup a965bfb530e8449f5a355f221b2fd107-598531793.eu-central-1.elb.amazonaws.com on 8.8.8.8:53: no such host

This error arises if the argocd-server Kubernetes service is freshly installed right before the argocd login command is run. Then the argocd login command failes for some time until it finally will work correctly.

Assuming some DNS propagation issues we can prevent this error from breaking our CI pipeline by wrapping our argocd login command into an until like already done in this answer. The full command will then look like this:

until argocd login $(kubectl get service argocd-server -n argocd --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}') --username admin --password $(kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo) --insecure; do : ; done
```
<p>In GitHub Actions this will then look somehow like this:</p>
```--- Login argocd CLI - now wrapped in until to prevent FATA[0000] dial tcp: lookup 12345.eu-central-1.elb.amazonaws.com on 8.8.8.8:53: no such host
time="2022-02-21T12:57:32Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:57:35Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:57:37Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
[...]
time="2022-02-21T12:58:27Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:58:30Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:58:32Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
'admin:login' logged in successfully
Context 'a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com' updated
```

Here's also a log.

Body:
We have a full-blown setup using AWS EKS with Tekton installed and want to use ArgoCD for application deployment.

As the docs state we installed ArgoCD on EKS in GitHub Actions with:

  - name: Install ArgoCD
    run: |
      echo "--- Create argo namespace and install it"
      kubectl create namespace argocd --dry-run=client -o yaml | kubectl apply -f -
      kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

We also exposed the ArgoCD server (incl. dashboard) as the docs told us:

  - name: Expose ArgoCD Dashboard
    run: |
      echo "--- Expose ArgoCD Dashboard via K8s Service"
      kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'

      echo "--- Wait until Loadbalancer url is present (see https://stackoverflow.com/a/70108500/4964553)"
      until kubectl get service/argocd-server -n argocd --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done

Finally we installed argocd CLI with brew:

      echo "--- Install ArgoCD CLI"
      brew install argocd

Now how can we do a argocd login with GitHub Actions (without human interaction)? The argocd login command wants a username and password...

Body:
The same docs tell us how to extract the password for argo with:

kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo

Obtaining the ArgoCD server's hostname is also no big deal using:

kubectl get service argocd-server -n argocd --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}'

And as the argocd login command has the parameters --username and --password, we can craft our login command like this:

argocd login $(kubectl get service argocd-server -n argocd --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}') --username admin --password $(kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo) --insecure

Mind the --insecure to prevent the argo CLI from asking things like WARNING: server certificate had error: x509: certificate is valid for localhost, argocd-server, argocd-server.argocd, argocd-server.argocd.svc, argocd-server.argocd.svc.cluster.local, not a5f715808162c48c1af54069ba37db0e-1371850981.eu-central-1.elb.amazonaws.com. Proceed insecurely (y/n)?.

The successful login should somehow look like this in the GitHub Actions UI (see a full log here):

'admin:login' logged in successfully
Context 'a5f715808162c48c1af54069ba37db0e-1371850981.eu-central-1.elb.amazonaws.com' updated

Now your GitHub Actions workflow should be able to interact with the ArgoCD server.

Prevent error FATA[0000] dial tcp: lookup a965bfb530e8449f5a355f221b2fd107-598531793.eu-central-1.elb.amazonaws.com on 8.8.8.8:53: no such host

This error arises if the argocd-server Kubernetes service is freshly installed right before the argocd login command is run. Then the argocd login command failes for some time until it finally will work correctly.

Assuming some DNS propagation issues we can prevent this error from breaking our CI pipeline by wrapping our argocd login command into an until like already done in this answer. The full command will then look like this:

until argocd login $(kubectl get service argocd-server -n argocd --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}') --username admin --password $(kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo) --insecure; do : ; done

In GitHub Actions this will then look somehow like this:

--- Login argocd CLI - now wrapped in until to prevent FATA[0000] dial tcp: lookup 12345.eu-central-1.elb.amazonaws.com on 8.8.8.8:53: no such host
time="2022-02-21T12:57:32Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:57:35Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:57:37Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
[...]
time="2022-02-21T12:58:27Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:58:30Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
time="2022-02-21T12:58:32Z" level=fatal msg="dial tcp: lookup a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com on 127.0.0.53:53: no such host"
'admin:login' logged in successfully
Context 'a071bed7e9ea14747951b04360133141-459093397.eu-central-1.elb.amazonaws.com' updated

Here's also a log.


问:
Full-text search contains NEAR had problem with "\n" , EOL
I used SQL Server full-text search but I had problem with CONTAINS NEAR query.

When I use ... CONTAINS(column_name, 'NEAR((John, 1999), 30)') in text query without "\n" like that

....xxx John Jacob Smith 1999

its OK.

but if the text query has "\n"

....xxx John Jacob Smith

1999.

It's not found by the query above

答:
NEAR() Search Term Distance Calculation

You need to increase the allowed distance number between your search terms of "John" and "1999". Your query example uses 30 which means 30 "terms" can be between John and 1999. But line breaks "equals" 128 terms.

For the line break example data, the gap is 130 from "John" to "1999"

```<code>+ 1 for "Jacob"
+ 1 for "Smith"
+ 128 for line break
= 130
</code>```

See quote about paragraph (line break) from Microsoft's doc on NEAR() full doc here

If a match spans the end of a sentence, paragraph, or chapter, the gap
used for ranking a document is increased by 8, 128, or 1024,
respectively.

SQL Script Example

```<code>/*Returns only the 1 row without a line break*/
SELECT *
FROM YourTable
WHERE CONTAINS(YourCol, 'NEAR((John, 1999), 129)')

/*Returns both rows*/
SELECT *
FROM YourTable
WHERE CONTAINS(YourCol, 'NEAR((John, 1999), 130)') /*Increased max distance to 130*/
</code>```

Body:
NEAR() Search Term Distance Calculation

You need to increase the allowed distance number between your search terms of "John" and "1999". Your query example uses 30 which means 30 "terms" can be between John and 1999. But line breaks "equals" 128 terms.

For the line break example data, the gap is 130 from "John" to "1999"

+ 1 for "Jacob"
+ 1 for "Smith"
+ 128 for line break
= 130

See quote about paragraph (line break) from Microsoft's doc on NEAR() full doc here

If a match spans the end of a sentence, paragraph, or chapter, the gap
used for ranking a document is increased by 8, 128, or 1024,
respectively.

SQL Script Example

/*Returns only the 1 row without a line break*/
SELECT *
FROM YourTable
WHERE CONTAINS(YourCol, 'NEAR((John, 1999), 129)')

/*Returns both rows*/
SELECT *
FROM YourTable
WHERE CONTAINS(YourCol, 'NEAR((John, 1999), 130)') /*Increased max distance to 130*/


问:
Is using 2 webservers (static/dynamic) an overkill to the website?
I use 2 webservers:

A dynamic website that servers static content.

A static website with content for the first website.
Technology: apache2/nginx for example...

Is this overkill?
Is this better or worse for the website?

答:
Companies in general have Apache and that Apache has modules or integrations with systems that are not easy to remove.

It is common to see three layers: NGINX - Apache - Java Server

And every piece serves a different (very important) purpose.


问:
Java 8 to Java 11 migration issues with JAXB API
We are in process of migrating our projects from Java 8 to Java 11. One of the APIs is dependent on a library that utilizes JAXB. As we know JAXB was removed from JAVA 11 we started to include the JAXB dependencies in the POM of the library.

```<code> <!-- https://mvnrepository.com/artifact/jakarta.xml.bind/jakarta.xml.bind-api -->
  <!-- API -->
  <dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>2.3.3</version>
  </dependency>
  <!-- Runtime -->
  <dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.2</version>
  </dependency>
</code>```

All works fine when we run the API project with

mvn spring-boot:run

However when the API is deployed in QA servers and is started using a start script with -

java -jar Sample-api-3.0.0-SNAPSHOT.jar

The API throws the following error when invoking the library that is dependent on JAXB -

```<code>Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
</code>```

with linked exception:

```<code> [java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
      at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:269)
      at javax.xml.bind.ContextFinder.find(ContextFinder.java:412)
      at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
      at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
      at com.eoriginal.ecore.client.documents.SearchDocumentHistoryAPI$RequestParameters.toMap(SearchDocumentHistoryAPI.java:344)
      ... 14 more
    Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
      at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
      at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
      at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
      at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
      at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
      at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:267)
</code>```

UPDATE :
I added the Maven Shade plugin to generate the JAR with all the dependencies but when the line of code is executed to create the JAXBContext the error still persists -
JAXBContext jaxbc = JAXBContext.newInstance(new Class[]{Abc.class});

答:
Add this dependency to POM:</p>
```<code><dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
</code>```

Body:
We are in process of migrating our projects from Java 8 to Java 11. One of the APIs is dependent on a library that utilizes JAXB. As we know JAXB was removed from JAVA 11 we started to include the JAXB dependencies in the POM of the library.

  <dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>2.3.3</version>
  </dependency>

  <dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.2</version>
  </dependency>

All works fine when we run the API project with

mvn spring-boot:run

However when the API is deployed in QA servers and is started using a start script with -

java -jar Sample-api-3.0.0-SNAPSHOT.jar

The API throws the following error when invoking the library that is dependent on JAXB -

Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.

with linked exception:

 [java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
      at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:269)
      at javax.xml.bind.ContextFinder.find(ContextFinder.java:412)
      at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
      at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
      at com.eoriginal.ecore.client.documents.SearchDocumentHistoryAPI$RequestParameters.toMap(SearchDocumentHistoryAPI.java:344)
      ... 14 more
    Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
      at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
      at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
      at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
      at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
      at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
      at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:267)

UPDATE :
I added the Maven Shade plugin to generate the JAR with all the dependencies but when the line of code is executed to create the JAXBContext the error still persists -
JAXBContext jaxbc = JAXBContext.newInstance(new Class[]{Abc.class});

Body:
Add this dependency to POM:

<dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>


问:
Generating and counting consecutive number as cumsum and second as 0
if we have a dataframe where a column is df.Series = ["a","a","b","c","d","d"] and i want count the consecutive but like the first value should be the cumsum  and second occurrence should be 0 like</p>
```<code>col["A"] col["B"]
       a        2
       a        0
       b        1
       c        1
       d        2
</code>```

答:
IIUC, you want to add the count of consecutive values as the first row per group, 0 otherwise.

You can use groupby+transform('size') to get the size per group and mask+duplicated to keep only the fist value:

```<code># input or use df['colA'] if dataframe
s = pd.Series(["a","a","b","c","d","d"])

# set groups of consecutive values
group = s.ne(s.shift()).cumsum()

# compute size and keep only first
g = s.groupby(group)
df['colB'] = g.transform('size').mask(g.apply(pd.Series.duplicated), 0)
</code>```

output:

```<code>0    2
1    0
2    1
3    1
4    2
5    0
dtype: int64
</code>```

Body:
if we have a dataframe where a column is df.Series = ["a","a","b","c","d","d"] and i want count the consecutive but like the first value should be the cumsum  and second occurrence should be 0 like

col["A"] col["B"]
       a        2
       a        0
       b        1
       c        1
       d        2

Body:
IIUC, you want to add the count of consecutive values as the first row per group, 0 otherwise.

You can use groupby+transform('size') to get the size per group and mask+duplicated to keep only the fist value:

# input or use df['colA'] if dataframe
s = pd.Series(["a","a","b","c","d","d"])

# set groups of consecutive values
group = s.ne(s.shift()).cumsum()

# compute size and keep only first
g = s.groupby(group)
df['colB'] = g.transform('size').mask(g.apply(pd.Series.duplicated), 0)

output:

0    2
1    0
2    1
3    1
4    2
5    0
dtype: int64


问:
How to use index and get rid of React Warning: Each child in a list should have a unique "key" prop?
Hello I'm facing this error, question is how to propertly pass index in this component?

Error:

```<code>react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop.
</code>```

Here is the component's code fragment:

```<code>                            {calculatorScreenshots.map((imgUrl: any, index) => {
                                return (
                                    <Zoom>
                                        {props.projectName == 'Calculator' && (
                                            <CardMedia
                                                key={index}
                                                component="img"
                                                height="200"
                                                alt="project picture"
                                                image={imgUrl}
                                            />
                                        )}
                                    </Zoom>
                                );
                            })}
</code>```

答:
You should be placing the key prop at the first element

```<code>                        {calculatorScreenshots.map((imgUrl: any, index) => {
                            return (
                                <Zoom key={index}>
                                    {props.projectName == 'Calculator' && (
                                        <CardMedia

                                            component="img"
                                            height="200"
                                            alt="project picture"
                                            image={imgUrl}
                                        />
                                    )}
                                </Zoom>
                            );
                        })}
</code>```

Body:
Hello I'm facing this error, question is how to propertly pass index in this component?

Error:

react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop.

Here is the component's code fragment:

                            {calculatorScreenshots.map((imgUrl: any, index) => {
                                return (
                                    <Zoom>
                                        {props.projectName == 'Calculator' && (
                                            <CardMedia
                                                key={index}
                                                component="img"
                                                height="200"
                                                alt="project picture"
                                                image={imgUrl}
                                            />
                                        )}
                                    </Zoom>
                                );
                            })}

Body:
You should be placing the key prop at the first element

                        {calculatorScreenshots.map((imgUrl: any, index) => {
                            return (
                                <Zoom key={index}>
                                    {props.projectName == 'Calculator' && (
                                        <CardMedia

                                            component="img"
                                            height="200"
                                            alt="project picture"
                                            image={imgUrl}
                                        />
                                    )}
                                </Zoom>
                            );
                        })}


答: The top-level <Zoom> component needs a key attribute as well.

Title: How to use index and get rid of React Warning: Each child in a list should have a unique "key" prop?


问:
C++ istream input fails yet consumes data. Expected to be able read bad data after failure
My understanding of iostream has always been that when an input conversion fails, the data remains in the stream to be read after clearing the error.  But I have an example that does not always work that way, and I would like to know if the behavior is correct.  If so, could someone point me at some good documentation of the actual rules?

This small program represents the idea of using an i/o failure to read an optional repeat count and a string.

```<code>#include <iostream>
#include <string>

int main()
{
    int cnt;
    std::cout << "in: ";
    std::cin >> cnt;
    if(!std::cin) {
        cnt = 1;
        std::cin.clear();
    }
    std::string s;
    std::cin >> s;
    std::cout << "out: " << cnt << " [" << s << "]" << std::endl;
}
</code>```

So, here's how it runs:

```<code>[me@localhost tmp]$ ./bother
in: 16 boxes
out: 16 [boxes]
[me@localhost tmp]$ ./bother
in: hatrack
out: 1 [hatrack]
[me@localhost tmp]$ ./bother
in: some things
out: 1 [some]
[me@localhost tmp]$ ./bother
in: 23miles
out: 23 [miles]
[me@localhost tmp]$ ./bother
in: @(#&$(@#&$ computer
out: 1 [@(#&$(@#&$]
</code>```

So it mostly works.  When there's a number first, it is read, then the string is.  When I give a non-numeric first, the read fails, the count is set to 1 and the non-numeric input is read.  But this breaks:

```<code>[me@localhost tmp]$ ./bother
in: + smith
out: 1 [smith]
</code>```

The + fails the integer read because it's not enough to make a number, but the + does not remain on the stream to be picked up by the string read.  Likewise with -.  If it reads the + or - as a zero, that would be reasonable, but then the read should succeed and cnt should show that zero.

Perhaps this is correct behavior, and I've just always been wrong about what it is supposed to do.  If so, what are the rules?

Your advice appreciated.

答:
Plus and minus are valid parts of an integer and so are read, when the next character is read the stream fails and that character is left in the stream but the leading sign character is not put back into the stream.

See https://en.cppreference.com/w/cpp/locale/num_get/get for the full rules

Body:
My understanding of iostream has always been that when an input conversion fails, the data remains in the stream to be read after clearing the error.  But I have an example that does not always work that way, and I would like to know if the behavior is correct.  If so, could someone point me at some good documentation of the actual rules?

This small program represents the idea of using an i/o failure to read an optional repeat count and a string.

#include <iostream>
#include <string>

int main()
{
    int cnt;
    std::cout << "in: ";
    std::cin >> cnt;
    if(!std::cin) {
        cnt = 1;
        std::cin.clear();
    }
    std::string s;
    std::cin >> s;
    std::cout << "out: " << cnt << " [" << s << "]" << std::endl;
}

So, here's how it runs:

[me@localhost tmp]$ ./bother
in: 16 boxes
out: 16 [boxes]
[me@localhost tmp]$ ./bother
in: hatrack
out: 1 [hatrack]
[me@localhost tmp]$ ./bother
in: some things
out: 1 [some]
[me@localhost tmp]$ ./bother
in: 23miles
out: 23 [miles]
[me@localhost tmp]$ ./bother
in: @(#&$(@#&$ computer
out: 1 [@(#&$(@#&$]

So it mostly works.  When there's a number first, it is read, then the string is.  When I give a non-numeric first, the read fails, the count is set to 1 and the non-numeric input is read.  But this breaks:

[me@localhost tmp]$ ./bother
in: + smith
out: 1 [smith]

The + fails the integer read because it's not enough to make a number, but the + does not remain on the stream to be picked up by the string read.  Likewise with -.  If it reads the + or - as a zero, that would be reasonable, but then the read should succeed and cnt should show that zero.

Perhaps this is correct behavior, and I've just always been wrong about what it is supposed to do.  If so, what are the rules?

Your advice appreciated.


问:
printing a list of values within a certain range
So I am having a problem with printing certain values that fall within a certain range from a list

Here is the code

```<code>import statistics as st

players = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]
players.sort()

avg = sum(players)/ len(players)

std = st.stdev(players)

low = avg - std
high = avg + std

for i in range (int(low), int(high)):
 print(players[i])
</code>```

It is giving me this error

```<code>Traceback (most recent call last):
File "file0.py", line 16, in <module>
print(players[i])
IndexError: list index out of range
</code>```

Thank you

答:
The mistake in your loop is that, you are trying to access the value at an index which is beyond your loop. Instead of accessing value at indices [int(low), int(high)), you can add an if case to check if the value lies in that range and print it.

Your intended (more pythonic) solution is

```<code>print([x for x in players if low < x < high])
</code>```

Edit : Suggested by @Barmar and @OlvinRoght

Body:
So I am having a problem with printing certain values that fall within a certain range from a list

Here is the code

import statistics as st

players = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]
players.sort()

avg = sum(players)/ len(players)

std = st.stdev(players)

low = avg - std
high = avg + std

for i in range (int(low), int(high)):
 print(players[i])

It is giving me this error

Traceback (most recent call last):
File "file0.py", line 16, in <module>
print(players[i])
IndexError: list index out of range

Thank you

Body:
The mistake in your loop is that, you are trying to access the value at an index which is beyond your loop. Instead of accessing value at indices [int(low), int(high)), you can add an if case to check if the value lies in that range and print it.

Your intended (more pythonic) solution is

print([x for x in players if low < x < high])

Edit : Suggested by @Barmar and @OlvinRoght


问:
Visual Studio 2019 - force C++11 features only
I use Visual Studio 2019 for C++ development. Due to constraints of legacy systems that code will be deployed to, I am limited to using only C++11 language features (specifically GCC 4.8.5).

The default in VS2019 is C++14, which is obviously a super set of C++11. I can't see a way to specify C++11 only. This would be useful as a much faster way to see if I accidentally include newer C++ features than seeing things fail in the build system.

Is there any way to change this setting?

答:
I am afraid it's not possible.

there is no plan to add a C++11 switch

Link: Standards version switches in the compiler

The compiler doesn't support standards options for C++98, C++03, or
C++11.

/Zc:__cplusplus


问:
Sharing data from main page to child page in angular 8.2.4
i am new to angular and trying to share data between pages on load of main page , i am using angular dynamic forms to create dynamic pages.
my main page consist of child components pages that load in main page but when the data from my main page is passed to the child page using providers on page load the data reaches the child but doesnt store it in variable of child page

main page:

```<code>import { Component, Input, OnInit } from '@angular/core';
import { AppSelect } from '../component/multiselect.component';

@Component({
providers: [AppSelect],      //child
selector: 'app-hello',
template: `<app-select></app-select>`,
styles: [`h1 { font-family: Lato; }`],
})

export class HelloComponent implements OnInit {
array: any[] = ['1', '2', '3', '4', '5', '6'];
constructor(private module: AppSelect  //child) {}

ngOnInit() {

this.module.valuefrommainrpage(this.array); //value from here is sent to multiselect.component page
}
}
</code>```

multiselect.component child page :

```<code>import { Component, VERSION } from '@angular/core';

@Component({
selector: 'app-select',
template: `
<select multiple="multiple" name="" id="" style="width:300px;height:300px;">
<option *ngFor="let items of module" [value]="items">{{items}}</option>
</select>

<br>
<button (click)="setvalue()">CLICK</button>
<button
(click)="console()">consolevalues</button>`,
styles: [`h1 { font-family: Lato; }`],
})

export class AppSelect {
module: string[] = [];
setvalue() {
this.module = ['one', 'two', 'three', 'four', 'five'];
}

valuefrommainrpage(data) {
//data is recievd from main page on ngOnInit of mainpage
console.log(data);
this.module = data; //data should be set here but doesnt
}
console() {
console.log(this.module);
}
}
</code>```

my stackblitz code : Sharing data from main to child component

i dont understand how this is happening as i am receiving data from main page but cannot store it in variable

答:
As Angular docs says:

A common pattern in Angular is sharing data between a parent component
and one or more child components. Implement this pattern with the
@Input() and @Output() decorators.

Sending data to a child component

It is necessary to create a variable with @Input() decorator:

```<code>@Input() item = ''; // decorate the property with @Input()
</code>```

and in parent component set value to this variable:

```<code><app-detail-component [item]="anItem"></app-detail-component>
</code>```

Body:
i am new to angular and trying to share data between pages on load of main page , i am using angular dynamic forms to create dynamic pages.
my main page consist of child components pages that load in main page but when the data from my main page is passed to the child page using providers on page load the data reaches the child but doesnt store it in variable of child page

main page:

import { Component, Input, OnInit } from '@angular/core';
import { AppSelect } from '../component/multiselect.component';

@Component({
providers: [AppSelect],      //child
selector: 'app-hello',
template: `<app-select></app-select>`,
styles: [`h1 { font-family: Lato; }`],
})

export class HelloComponent implements OnInit {
array: any[] = ['1', '2', '3', '4', '5', '6'];
constructor(private module: AppSelect  //child) {}

ngOnInit() {

this.module.valuefrommainrpage(this.array); //value from here is sent to multiselect.component page
}
}

multiselect.component child page :

import { Component, VERSION } from '@angular/core';

@Component({
selector: 'app-select',
template: `
<select multiple="multiple" name="" id="" style="width:300px;height:300px;">
<option *ngFor="let items of module" [value]="items">{{items}}</option>
</select>

<button (click)="setvalue()">CLICK</button>
<button
(click)="console()">consolevalues</button>`,
styles: [`h1 { font-family: Lato; }`],
})

export class AppSelect {
module: string[] = [];
setvalue() {
this.module = ['one', 'two', 'three', 'four', 'five'];
}

valuefrommainrpage(data) {
//data is recievd from main page on ngOnInit of mainpage
console.log(data);
this.module = data; //data should be set here but doesnt
}
console() {
console.log(this.module);
}
}

my stackblitz code : Sharing data from main to child component

i dont understand how this is happening as i am receiving data from main page but cannot store it in variable

Body:
As Angular docs says:

A common pattern in Angular is sharing data between a parent component
and one or more child components. Implement this pattern with the
@Input() and @Output() decorators.

Sending data to a child component

It is necessary to create a variable with @Input() decorator:

@Input() item = ''; // decorate the property with @Input()

and in parent component set value to this variable:

<app-detail-component [item]="anItem"></app-detail-component>


问:
Regex for matching specific words or their combination as well as the exception word
I would like to check source code scripts according to such a pattern:

'DELETE' or 'FROM' or 'DELETE FROM' followed by a space followed by any word not followed by another word separated by a dot, except for the word 'DUAL'

Something like

```<code>'(DELETE|FROM|DELETE FROM) \w+', where \w+ != DUAL
but not
'(DELETE|FROM|DELETE FROM) \w+\.\w+'
</code>```

Examples

text fragment
desired result

begin DELETE tbl1;
DELETE tbl1

select FROM tbl2) loop
FROM tbl2

fnc(); DELETE FROM tbl3 where
DELETE FROM tbl3

qqq DELETE DUAL; www

eee FROM DUAL rrr

ttt DELETE FROM DUAL where

yy DELETE sch1.tbl1; uuu

iii FROM sch2.tbl2 ooo

ppp DELETE FROM sch3.tbl3 aaa

My guess

```<code>(FROM|DELETE( FROM)?) (?!DUAL)(?!\w+\.)\w+
</code>```

matches too much by the 1st part. Is it correct in its 2nd part (after space)?

答:
You might use

```<code>\b(?>DELETE(?: FROM)?|FROM) (?!DUAL\b)\w+\b(?!\.)
</code>```

The pattern matches:

\b Word boundary to prevent a partial word match

(?>DELETE(?: FROM)?|FROM)  Atomic group (No backtracking) to match either DELETE with optional FROM or only FROM

(?!DUAL\b) Negative lookahead to assert not the word DUAL directly to the right followed by a word boundary

\w+\b Math 1+ word characters and a word boundary

(?!\.) Negative lookahead, assert not a dot directly to the right of the current position

.NET Regex demo

Body:
I would like to check source code scripts according to such a pattern:

'DELETE' or 'FROM' or 'DELETE FROM' followed by a space followed by any word not followed by another word separated by a dot, except for the word 'DUAL'

Something like

'(DELETE|FROM|DELETE FROM) \w+', where \w+ != DUAL
but not
'(DELETE|FROM|DELETE FROM) \w+\.\w+'

Examples

text fragment
desired result

begin DELETE tbl1;
DELETE tbl1

select FROM tbl2) loop
FROM tbl2

fnc(); DELETE FROM tbl3 where
DELETE FROM tbl3

qqq DELETE DUAL; www

eee FROM DUAL rrr

ttt DELETE FROM DUAL where

yy DELETE sch1.tbl1; uuu

iii FROM sch2.tbl2 ooo

ppp DELETE FROM sch3.tbl3 aaa

My guess

(FROM|DELETE( FROM)?) (?!DUAL)(?!\w+\.)\w+

matches too much by the 1st part. Is it correct in its 2nd part (after space)?

Body:
You might use

\b(?>DELETE(?: FROM)?|FROM) (?!DUAL\b)\w+\b(?!\.)

The pattern matches:

\b Word boundary to prevent a partial word match

(?>DELETE(?: FROM)?|FROM)  Atomic group (No backtracking) to match either DELETE with optional FROM or only FROM

(?!DUAL\b) Negative lookahead to assert not the word DUAL directly to the right followed by a word boundary

\w+\b Math 1+ word characters and a word boundary

(?!\.) Negative lookahead, assert not a dot directly to the right of the current position

.NET Regex demo


问:
Remove duplicates based on one column and keep latest entry in google sheets
I was working on some automation and wanted to remove the duplicate rows in my google sheet by comparing it on basis of 3rd column. I found one code which is working flawlessly but it does not remove the old entry in sheet, it removes the latest one. I wanted to keep the latest one from the duplicates.

This is the code which I found for appscript by Cooper:

```<code>function removeDuplicates() {
  var sh=SpreadsheetApp.getActiveSheet();
  var dt=sh.getDataRange().getValues();
  var uA=[];
  var d=0;
  for(var i=0;i<dt.length;i++) {
    if(uA.indexOf(dt[i][2])==-1) {
      uA.push(dt[i][2]);
    }else{
      sh.deleteRow(i+1-d++);
    }
  }
}
</code>```

Can anyone help me with the code which does the same work "removing duplicate rows (Keeps latest entry removes the old entry) based on column" ?

答:
From I wanted to keep the latest one from the duplicates., when the latest one is the last row, in your script, how about the following modification?

Modified script:

function removeDuplicates() {
  var sh = SpreadsheetApp.getActiveSheet();
  var dt = sh.getDataRange().getValues();
  var uA = [];
  for (var i = dt.length - 1; i >= 0; i--) {
    if (uA.indexOf(dt[i][2]) == -1) {
      uA.push(dt[i][2]);
    } else {
      sh.deleteRow(i + 1);
    }
  }
}
```

Body:
I was working on some automation and wanted to remove the duplicate rows in my google sheet by comparing it on basis of 3rd column. I found one code which is working flawlessly but it does not remove the old entry in sheet, it removes the latest one. I wanted to keep the latest one from the duplicates.

This is the code which I found for appscript by Cooper:

function removeDuplicates() {
  var sh=SpreadsheetApp.getActiveSheet();
  var dt=sh.getDataRange().getValues();
  var uA=[];
  var d=0;
  for(var i=0;i<dt.length;i++) {
    if(uA.indexOf(dt[i][2])==-1) {
      uA.push(dt[i][2]);
    }else{
      sh.deleteRow(i+1-d++);
    }
  }
}

Can anyone help me with the code which does the same work "removing duplicate rows (Keeps latest entry removes the old entry) based on column" ?


问:
How to use Application variable like ASP in Codeigniter
I want to count the click on the each part of homepage, but not by using database. I think DB will bring some overhead.

The ASP code is:

```<code><script language="vbscript" runat="server">

Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub

</script>
</code>```

答:
Here is a link to a project that adds an $_APP global variable. http://www.leosingleton.com/projects/code/phpapp/

FYI, it uses a file to store the $_APP data, but it doesn't look like it's doing any file locking or merging of $_APP when writing it back to the file. For a high traffic site or if you have CPU intensive pages, this could cause data issues in the file.


问:
Generate sequence in Cosmos DB
Need to create sequence so what the code was currently doing select max(name) from table where item1 = '' and item2= '' and item3 = '' . After fetching max then it insert the element starting from max. But it will lead to concurrency issue.

Note: The query will always be perform in same parition

Currently i have two approach:

One to create a sequence table which will contain the ID and sequence as column. Sequence column will contain the last sequence number for that ID. This will be updated using optimistic concurrency.

Second one is to use stored procedure.

But still i am looking for some more better approach if that is present.

答:
There is no better approach other than complicate things dramatically with semaphores etc, but I think you approach with Optimistic Concurrency Control will work fine.

Stored procedures will not help you in this instance at all.

ChangeFeed can be one way to update things after the fact but I dont see how this helps you unless you make a seperate document keeping track of current number etc but that seems like over kill for what you want.

Title: Generate sequence in Cosmos DB


问:
create thumbnail from video URL in C#
I want to generate thumbnail from a video URL in C#. I have searched a lot to find a neat way but no success. I have used Nreco and MediaToolKit but none of them extract thumbnail image. using ffmpeg also has mumbo jumbos which didn't worked!

using NReco:

```<code>var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
string thumbnailJPEGpath = "http://localhost:81882/content/hashem.jpeg";
ffMpeg.GetVideoThumbnail(videoUrl,thumbnailJPEGpath);
</code>```

using ffmpeg:

```<code>try
        {
            System.Diagnostics.Process ffmpeg;

            string video;
            string thumb;

            video = Server.MapPath("~/Content/Movies/bye.mp4");
            thumb = Server.MapPath("~/Content/frame.jpg");

            ffmpeg = new System.Diagnostics.Process();

            ffmpeg.StartInfo.Arguments = " -i " + video + " -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg " + thumb;
            ffmpeg.StartInfo.FileName = Server.MapPath("~/Content/ffmpeg.exe");
            ffmpeg.Start();
            ffmpeg.WaitForExit();
            ffmpeg.Close();
        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.Message);
        }
</code>```

to consider video files are not local and I have only a direct link to the file:
e.g.:http://phytonord.com/Film-Series/hana/26.mp4

does anyone has any solution? any sample code that works?

答:
Just in case, if some one looking for creating multiple thumb image extracting for sprite image creation using ffmpeg or NReco library.

Using Command line --> ffmpeg -i corpfilm.mp4 -s 280x150 -vf fps=1 thumb/img%03d.jpg

Under the hood NReco.VideoConverter executes ffmpeg with System.Diagnostics.Process API; this means that you can run any command that is possible in the command line.

For this concrete command VideoConverter's API equivalent:

```<code>var ffmpeg = new NReco.VideoConverter.FFMpegConverter();
ffmpeg.ConvertMedia(
  "corpfilm.mp4", null,
  " thumb/img%03d.jpg", null,
  new ConvertSettings() {
    CustomOutputArgs = " -s 280x150 -vf fps=1 "
  });
</code>```

Title: create thumbnail from video URL in C#

Body:
I want to generate thumbnail from a video URL in C#. I have searched a lot to find a neat way but no success. I have used Nreco and MediaToolKit but none of them extract thumbnail image. using ffmpeg also has mumbo jumbos which didn't worked!

using NReco:

var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
string thumbnailJPEGpath = "http://localhost:81882/content/hashem.jpeg";
ffMpeg.GetVideoThumbnail(videoUrl,thumbnailJPEGpath);

using ffmpeg:

try
        {
            System.Diagnostics.Process ffmpeg;

            string video;
            string thumb;

            video = Server.MapPath("~/Content/Movies/bye.mp4");
            thumb = Server.MapPath("~/Content/frame.jpg");

            ffmpeg = new System.Diagnostics.Process();

            ffmpeg.StartInfo.Arguments = " -i " + video + " -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg " + thumb;
            ffmpeg.StartInfo.FileName = Server.MapPath("~/Content/ffmpeg.exe");
            ffmpeg.Start();
            ffmpeg.WaitForExit();
            ffmpeg.Close();
        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.Message);
        }

to consider video files are not local and I have only a direct link to the file:
e.g.:http://phytonord.com/Film-Series/hana/26.mp4

does anyone has any solution? any sample code that works?

Body:
Just in case, if some one looking for creating multiple thumb image extracting for sprite image creation using ffmpeg or NReco library.

Using Command line --> ffmpeg -i corpfilm.mp4 -s 280x150 -vf fps=1 thumb/img%03d.jpg

Under the hood NReco.VideoConverter executes ffmpeg with System.Diagnostics.Process API; this means that you can run any command that is possible in the command line.

For this concrete command VideoConverter's API equivalent:

var ffmpeg = new NReco.VideoConverter.FFMpegConverter();
ffmpeg.ConvertMedia(
  "corpfilm.mp4", null,
  " thumb/img%03d.jpg", null,
  new ConvertSettings() {
    CustomOutputArgs = " -s 280x150 -vf fps=1 "
  });


问:
Firebase emulator is stoping with error: Pub/Sub Emulator has exited with code: 1
Firebase emulator is stopping with the following error

```<code>!  pubsub: Fatal error occurred:
   Pub/Sub Emulator has exited with code: 1,
   stopping all running emulators
</code>```

I don't know what is happening with emulator, even though I installed java and node correctly as said in the firebase documentation

Here is my firebase.json

```<code>{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ],
    "source": "functions"
  },
  "emulators": {
    "auth": {
      "port": 9099
    },
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8080
    },
    "pubsub": {
      "port": 8085
    },
    "ui": {
      "enabled": true
    }
  }
}
</code>```

答: I fixed the error by updating the JAVA_HOME variable in system environment variables and restarted the computer.</p>

Body:
Firebase emulator is stopping with the following error

!  pubsub: Fatal error occurred:
   Pub/Sub Emulator has exited with code: 1,
   stopping all running emulators

I don't know what is happening with emulator, even though I installed java and node correctly as said in the firebase documentation

Here is my firebase.json

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ],
    "source": "functions"
  },
  "emulators": {
    "auth": {
      "port": 9099
    },
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8080
    },
    "pubsub": {
      "port": 8085
    },
    "ui": {
      "enabled": true
    }
  }
}


问:
why won't WebProxy BypassProxyOnLocal work for me?
I'm trying to get HTTP calls I'm making from C# .NET to a local address (localhost:3000) to use the proxy I set (so I can go through fiddler).  Using the below WebProxy approach works if I point the target URL to a non-local address, however I need to point it to a local web-server I have (at localhost:3000), and when I do this the request is not going through the proxy.

I have inlcuded the "proxyObject.BypassProxyOnLocal = false".  This should make it work no?  Any suggestions re how to force the request to go through the WebProxy for http calls targetting a local address?

```<code>    WebProxy proxyObject = new WebProxy("http://localhost:8888/", false);
    proxyObject.Credentials = new NetworkCredential();
    proxyObject.BypassProxyOnLocal = false;
    WebRequest.DefaultWebProxy = proxyObject;

    var request = (HttpWebRequest)WebRequest.Create(targetUri);

    // I also included this line as a double check
    request.Proxy = proxyObject;
</code>```

Subsequent calls do not go through the proxy however, such as when I do:

```<code> var res = (HttpWebResponse)req.GetResponse();
</code>```

thanks

答:
I get around this simply by appending a "dot" to localhost, so instead of accessing "localhost", I try to access "localhost." (notice the dot at the end of the hostname)

Credit where credit is due:
I got this unusual tip from this thread http://www.west-wind.com/weblog/posts/2009/Jan/14/Monitoring-HTTP-Output-with-Fiddler-in-NET-HTTP-Clients-and-WCF-Proxies#596591

Works fine!

Body:
I'm trying to get HTTP calls I'm making from C# .NET to a local address (localhost:3000) to use the proxy I set (so I can go through fiddler).  Using the below WebProxy approach works if I point the target URL to a non-local address, however I need to point it to a local web-server I have (at localhost:3000), and when I do this the request is not going through the proxy.

I have inlcuded the "proxyObject.BypassProxyOnLocal = false".  This should make it work no?  Any suggestions re how to force the request to go through the WebProxy for http calls targetting a local address?

    WebProxy proxyObject = new WebProxy("http://localhost:8888/", false);
    proxyObject.Credentials = new NetworkCredential();
    proxyObject.BypassProxyOnLocal = false;
    WebRequest.DefaultWebProxy = proxyObject;

    var request = (HttpWebRequest)WebRequest.Create(targetUri);

    // I also included this line as a double check
    request.Proxy = proxyObject;

Subsequent calls do not go through the proxy however, such as when I do:

 var res = (HttpWebResponse)req.GetResponse();

thanks


答:
Create consecutive groups by compare by shifted values:

```<code>s = pd.Series(["a","a","b","c","d","d"])

g = s.ne(s.shift()).cumsum()
print (g)
0    1
1    1
2    2
3    3
4    4
5    4
dtype: int32
</code>```

Andf then mapping value by Series.value_counts with set 0 for duplicates:

```<code>print (g.map(g.value_counts()))
0    2
1    2
2    1
3    1
4    2
5    2
dtype: int64

out = g.map(g.value_counts()).mask(g.duplicated(), 0)
print (out)
0    2
1    0
2    1
3    1
4    2
5    0
dtype: int64
</code>```

Finally for DataFrame use:

```<code>df = pd.DataFrame({'A':s, 'B': out})
print (df)
   A  B
0  a  2
1  a  0
2  b  1
3  c  1
4  d  2
5  d  0
</code>```

Title: Generating and counting consecutive number as cumsum and second as 0

Body:
Create consecutive groups by compare by shifted values:

s = pd.Series(["a","a","b","c","d","d"])

g = s.ne(s.shift()).cumsum()
print (g)
0    1
1    1
2    2
3    3
4    4
5    4
dtype: int32

Andf then mapping value by Series.value_counts with set 0 for duplicates:

print (g.map(g.value_counts()))
0    2
1    2
2    1
3    1
4    2
5    2
dtype: int64

out = g.map(g.value_counts()).mask(g.duplicated(), 0)
print (out)
0    2
1    0
2    1
3    1
4    2
5    0
dtype: int64

Finally for DataFrame use:

df = pd.DataFrame({'A':s, 'B': out})
print (df)
   A  B
0  a  2
1  a  0
2  b  1
3  c  1
4  d  2
5  d  0


问:
Python Compile Mixed C and C++ Extension
I'm attempting to compile libspng with PyBind11 so I can easily convert image data into a numpy array.

The compilation process requires compiling a few C files and then linking them to C++. However, I'm not sure how to do this with Python setuptools. I've so far been compiling all C++ or all C modules in my practice, but on clang, this results in problems when I mix the pybind11 file with the C files.

Is there a simple way that I'm missing to compile and link the C files to C++ within setup.py?

I tried building an extension for libspng, but I wasn't sure how to reference the compiled shared object file which was in the build folder.

Thanks!

答:
In case it's helpful (and because I am procrastinating) I built a small demo based on the spng example

// pywrappers.cpp
#include <pybind11/pybind11.h>
#include <utility>
#include <cstdio>
extern "C" {
    #include <spng/spng.h>
}

namespace py = pybind11;

std::pair<size_t, size_t> get_size(const std::string& filename)
{
    FILE* fp = fopen(filename.c_str(), "rb");

    if (fp == nullptr)
    {
        fclose(fp);
        throw std::runtime_error("File not found");
    }

    spng_ctx* ctx = spng_ctx_new(0);

    spng_set_crc_action(ctx, SPNG_CRC_USE, SPNG_CRC_USE);

    size_t limit = 1024 * 1024 * 64;
    spng_set_chunk_limits(ctx, limit, limit);

    spng_set_png_file(ctx, fp);

    struct spng_ihdr ihdr;
    spng_get_ihdr(ctx, &ihdr);

    spng_ctx_free(ctx);
    fclose(fp);

    return std::make_pair<size_t, size_t>(ihdr.width, ihdr.height);
}

PYBIND11_MODULE(foo, m)
{
    m.def("get_size", &get_size);
}
```
<pre class="lang-py prettyprint-override"><code># setup.py
from setuptools import setup, Extension
import pybind11

SPNG_SOURCE = './libspng-0.7.1' # Wherever you put the spng headers and .a

libfoo = Extension(
    'foo',
    sources=['pywrappers.cpp'],
    extra_compile_args = ['-std=c++14'],
    include_dirs=[SPNG_SOURCE, pybind11.get_include()],
    extra_link_args=['-lspng_static','-lz'],
    library_dirs=[SPNG_SOURCE]
)

if __name__ == "__main__":
    setup(
        name = 'foo',
        ext_modules=[libfoo],
    )
</code>```

Build the extension as usual with e.g. python setup.py build_ext --inplace. Then for example

import foo
foo.get_size('stuff.png')
```

Body:
In case it's helpful (and because I am procrastinating) I built a small demo based on the spng example

// pywrappers.cpp
#include <pybind11/pybind11.h>
#include <utility>
#include <cstdio>
extern "C" {
    #include <spng/spng.h>
}

namespace py = pybind11;

std::pair<size_t, size_t> get_size(const std::string& filename)
{
    FILE* fp = fopen(filename.c_str(), "rb");

    if (fp == nullptr)
    {
        fclose(fp);
        throw std::runtime_error("File not found");
    }

    spng_ctx* ctx = spng_ctx_new(0);

    spng_set_crc_action(ctx, SPNG_CRC_USE, SPNG_CRC_USE);

    size_t limit = 1024 * 1024 * 64;
    spng_set_chunk_limits(ctx, limit, limit);

    spng_set_png_file(ctx, fp);

    struct spng_ihdr ihdr;
    spng_get_ihdr(ctx, &ihdr);

    spng_ctx_free(ctx);
    fclose(fp);

    return std::make_pair<size_t, size_t>(ihdr.width, ihdr.height);
}

PYBIND11_MODULE(foo, m)
{
    m.def("get_size", &get_size);
}

# setup.py
from setuptools import setup, Extension
import pybind11

SPNG_SOURCE = './libspng-0.7.1' # Wherever you put the spng headers and .a

libfoo = Extension(
    'foo',
    sources=['pywrappers.cpp'],
    extra_compile_args = ['-std=c++14'],
    include_dirs=[SPNG_SOURCE, pybind11.get_include()],
    extra_link_args=['-lspng_static','-lz'],
    library_dirs=[SPNG_SOURCE]
)

if __name__ == "__main__":
    setup(
        name = 'foo',
        ext_modules=[libfoo],
    )

Build the extension as usual with e.g. python setup.py build_ext --inplace. Then for example

import foo
foo.get_size('stuff.png')


问:
Spark Cassandra and resource allocation
My understanding is that the default spark.cassandra.input.split.size_in_mb is 64MB.It means the number of tasks that will be created for reading data from Cassandra will be Approx_table_size/64. Let's say the table size is 6400 MB (we are simply reading the data, doing foreachPartition and writing the data back to a DB), so the number of tasks will be 100. But while executing the job on YARN, if I specifically set --num-executors 3, --executor-cores 2, so this should create at max 6 tasks for the job. Now will the conf setting override the input.split.size value of 100 tasks when executed? OR will it be the case where while reading the data 100 tasks will be created but after that the partitions will be reduced to 6 and data shuffle would take place.

答:
First thing to mention - spark.cassandra.input.split.size_in_mb is default value, but if you have Cassandra partitions greater than that value, then it the Spark partition will have a size of the Cassandra partition, not the value from that setting.

Regarding processing - not really.  Spark Cassandra Connector will create 100 Spark partitions, that will be handled by Spark using the available cores (6), so it means that it will repeat the code 17 times (6*16 + 4), as in Spark each partition is handled by single core. Shuffling will happen only if you do .repartition explicitly.

Title: Spark Cassandra and resource allocation


问:
Make a program to solve this question using python:
Find the number of 6 digit numbers such that each digit appears atleast twice

I tried the below code but it doesn't work:

```<code>count = 0
for n in range(10**5,(10**6)-1):
    n = str(n).split()

for i in range(len(n)):

    n[i] = int(n[i])
    if n.count(i) >= 2:

        count+=1
print(count)
</code>```

The original question is of Permutation and Combinations but I want to solve this using python...

答:
```<code>answers = []
count = 0
my_dict = {}
digits = '0123456789'
for n in range(10**5, (10**6)-1):
    my_dict = {}
    ns = str(n)
    for m in ns:
        if m in digits:
            my_dict[m] = ns.count(m)
    if my_dict[min(my_dict, key=my_dict.get)] > 1:
        count += 1
        answers.append(ns)
print(count)
</code>```

Here is an alternative way. It gets the correct number.

Body:
Find the number of 6 digit numbers such that each digit appears atleast twice

I tried the below code but it doesn't work:

count = 0
for n in range(10**5,(10**6)-1):
    n = str(n).split()

for i in range(len(n)):

    n[i] = int(n[i])
    if n.count(i) >= 2:

        count+=1
print(count)

The original question is of Permutation and Combinations but I want to solve this using python...

Body:
answers = []
count = 0
my_dict = {}
digits = '0123456789'
for n in range(10**5, (10**6)-1):
    my_dict = {}
    ns = str(n)
    for m in ns:
        if m in digits:
            my_dict[m] = ns.count(m)
    if my_dict[min(my_dict, key=my_dict.get)] > 1:
        count += 1
        answers.append(ns)
print(count)

Here is an alternative way. It gets the correct number.