问:
Optimizing MySQL "IN" Select?
I have the following MySQL query:

```<code>SELECT
    `influencers`.*,
    `locations`.`country_name`
FROM
    `influencers`
    LEFT JOIN `locations` ON `influencers`.`country_id` = `locations`.`id`
WHERE
    `is_dead` = 0
    AND `influencers`.`is_private` = 0
    AND `influencers`.`country_id` = '31'
    AND influencers.uuid IN(
        SELECT
            `influencer_uuid` FROM `category_influencer`
        WHERE
            `category_influencer`.`category_id` = 17
            AND `category_influencer`.`is_main` = 1)
ORDER BY
    `influencers`.`followed_by` DESC
LIMIT 7 OFFSET 6
</code>```

I have identified the IN subquery is causing a lag of around 10s for this query to complete. Here is the EXPLAIN:

I have indexes on all columns being queried.

How can I significantly speed this query up?

Updated with SHOW CREATE TABLE for both:

locations

```<code>CREATE TABLE `locations` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `country_name` varchar(255) DEFAULT NULL,
    `city_name` varchar(255) DEFAULT NULL,
    `type` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `unique_index` (`city_name`, `country_name`),
    KEY `type` (`type`)
    USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 6479 DEFAULT CHARSET = utf8mb4
</code>```

influencers

```<code>CREATE TABLE `influencers` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `bio` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `url` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `followed_by` int(11) DEFAULT NULL,
    `follows` int(11) DEFAULT NULL,
    `full_name` varchar(255) CHARACTER
    SET utf8mb4 NOT NULL,
    `social_id` varchar(255) DEFAULT NULL,
    `is_private` tinyint (1) DEFAULT NULL,
    `avatar` varchar(255) NOT NULL,
    `username` varchar(30) NOT NULL,
    `text_search` text CHARACTER
    SET utf8mb4 NOT NULL,
    `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
    `uuid` varchar(255) DEFAULT NULL,
    `is_dead` tinyint (4) DEFAULT NULL,
    `country_id` int(11) DEFAULT NULL,
    `city_id` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `username` (`username`),
    UNIQUE KEY `uuid` (`uuid`),
    KEY `is_dead` (`is_dead`),
    KEY `updated_at` (`updated_at`),
    KEY `followed_by` (`followed_by`),
    KEY `social_id` (`social_id`),
    KEY `is_private` (`is_private`),
    KEY `country_id` (`country_id`),
    FULLTEXT KEY `text_search` (`text_search`)) ENGINE = InnoDB AUTO_INCREMENT = 2278376 DEFAULT CHARSET = utf8
</code>```

答:
Unless I missed something, you can replace the subselect with JOIN:</p>

```<code>SELECT influencers.*,
       locations.country_name
FROM influencers
         JOIN category_influencer T ON (
            T.influencer_uuid = influencers.uuid
            AND category_id = 17
            AND is_main = 1)
         LEFT JOIN locations ON influencers.country_id = locations.id
WHERE is_dead = 0
  AND is_private = 0
  AND country_id = '31'

ORDER BY followed_by DESC
LIMIT 7 OFFSET 6
</code>```

Title: Optimizing MySQL "IN" Select?

Body:
I have the following MySQL query:

SELECT
    `influencers`.*,
    `locations`.`country_name`
FROM
    `influencers`
    LEFT JOIN `locations` ON `influencers`.`country_id` = `locations`.`id`
WHERE
    `is_dead` = 0
    AND `influencers`.`is_private` = 0
    AND `influencers`.`country_id` = '31'
    AND influencers.uuid IN(
        SELECT
            `influencer_uuid` FROM `category_influencer`
        WHERE
            `category_influencer`.`category_id` = 17
            AND `category_influencer`.`is_main` = 1)
ORDER BY
    `influencers`.`followed_by` DESC
LIMIT 7 OFFSET 6

I have identified the IN subquery is causing a lag of around 10s for this query to complete. Here is the EXPLAIN:

I have indexes on all columns being queried.

How can I significantly speed this query up?

Updated with SHOW CREATE TABLE for both:

locations

CREATE TABLE `locations` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `country_name` varchar(255) DEFAULT NULL,
    `city_name` varchar(255) DEFAULT NULL,
    `type` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `unique_index` (`city_name`, `country_name`),
    KEY `type` (`type`)
    USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 6479 DEFAULT CHARSET = utf8mb4

influencers

CREATE TABLE `influencers` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `bio` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `url` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `followed_by` int(11) DEFAULT NULL,
    `follows` int(11) DEFAULT NULL,
    `full_name` varchar(255) CHARACTER
    SET utf8mb4 NOT NULL,
    `social_id` varchar(255) DEFAULT NULL,
    `is_private` tinyint (1) DEFAULT NULL,
    `avatar` varchar(255) NOT NULL,
    `username` varchar(30) NOT NULL,
    `text_search` text CHARACTER
    SET utf8mb4 NOT NULL,
    `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
    `uuid` varchar(255) DEFAULT NULL,
    `is_dead` tinyint (4) DEFAULT NULL,
    `country_id` int(11) DEFAULT NULL,
    `city_id` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `username` (`username`),
    UNIQUE KEY `uuid` (`uuid`),
    KEY `is_dead` (`is_dead`),
    KEY `updated_at` (`updated_at`),
    KEY `followed_by` (`followed_by`),
    KEY `social_id` (`social_id`),
    KEY `is_private` (`is_private`),
    KEY `country_id` (`country_id`),
    FULLTEXT KEY `text_search` (`text_search`)) ENGINE = InnoDB AUTO_INCREMENT = 2278376 DEFAULT CHARSET = utf8

Body:
Unless I missed something, you can replace the subselect with JOIN:

SELECT influencers.*,
       locations.country_name
FROM influencers
         JOIN category_influencer T ON (
            T.influencer_uuid = influencers.uuid
            AND category_id = 17
            AND is_main = 1)
         LEFT JOIN locations ON influencers.country_id = locations.id
WHERE is_dead = 0
  AND is_private = 0
  AND country_id = '31'

ORDER BY followed_by DESC
LIMIT 7 OFFSET 6


来源: stackexchange

问:
Password validation with vuetify
I need a password validation on my form.
I use vuetify validation like this :

```<code>passwordRules: [
      v => (v && 0 !== v.length >= 10) || 'Min length should be 10',
      v => (v && v.length <= 35) || 'Max length should be 35',
      ],
</code>```

I need a validation if password length is between 1 and 10 because I need to left a blank password.
but the validation work however its 0 or 10.

答:
Write two rules and remove required prop from your input:

```<code>passwordRules: [
   v => (v && v.length >= 1) || 'Name must be more than 1 character',
   v => (v && v.length <= 10) || 'Name must be less than 10 characters',
],
</code>```

ContentLicense: CC BY-SA 4.0

Title: Password validation with vuetify

Body:
I need a password validation on my form.
I use vuetify validation like this :

passwordRules: [
      v => (v && 0 !== v.length >= 10) || 'Min length should be 10',
      v => (v && v.length <= 35) || 'Max length should be 35',
      ],

I need a validation if password length is between 1 and 10 because I need to left a blank password.
but the validation work however its 0 or 10.

Body:
Write two rules and remove required prop from your input:

passwordRules: [
   v => (v && v.length >= 1) || 'Name must be more than 1 character',
   v => (v && v.length <= 10) || 'Name must be less than 10 characters',
],


问:
How to sort pandas dataframe in a special way
Given a pandas dataframe

```<code>df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})
</code>```

How to sort it along the column b in such a way that it is rearranged as {0,1,2,3,0,1,2,3}.

I.e. the resulting dataframe is

```<code>1   0
3   1
5   2
7   3
2   0
4   1
6   2
8   3
</code>```

答:
Add a column using cumcount

```<code>df.assign(x=df.groupby('b').cumcount()).sort_values(['x', 'b']).drop('x', axis=1)

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3
</code>```

Numpy's lexsort, iloc, and cumcount

```<code>df.iloc[np.lexsort([df['b'], df.groupby('b').cumcount()])]

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3
</code>```

Body:
Given a pandas dataframe

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})

How to sort it along the column b in such a way that it is rearranged as {0,1,2,3,0,1,2,3}.

I.e. the resulting dataframe is

1   0
3   1
5   2
7   3
2   0
4   1
6   2
8   3

Body:
Add a column using cumcount

df.assign(x=df.groupby('b').cumcount()).sort_values(['x', 'b']).drop('x', axis=1)

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3

Numpy's lexsort, iloc, and cumcount

df.iloc[np.lexsort([df['b'], df.groupby('b').cumcount()])]

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3


问:
How can I compare two matrixes for similarity using Python?
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

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

I would like to compare this to matrix y:

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

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?

答:
If your matrices are represented using the third-party library Numpy (which provides a lot of other useful stuff for dealing with matrices, as well as any kind of rectangular, multi-dimensional array):

```<code>>>> import numpy as np
>>> x = np.array([[1,0,1],[0,0,1],[1,1,0]])
>>> y = np.array([[1,0,1],[0,0,1],[1,1,1]])
</code>```

Then finding the number of corresponding equal elements is as simple as:

```<code>>>> (x == y).sum() / x.size
0.8888888888888888
</code>```

This works because x == y "broadcasts" the comparison to each corresponding element pair:

```<code>>>> x == y
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True, False]])
</code>```

and then we add up the boolean values (converted to integer, True has a value of 1 and False has a value of 0) and divide by the total number of elements.

Body:
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

1 0 1
0 0 1
1 1 0

I would like to compare this to matrix y:

1 0 1
0 0 1
1 1 1

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?

Body:
If your matrices are represented using the third-party library Numpy (which provides a lot of other useful stuff for dealing with matrices, as well as any kind of rectangular, multi-dimensional array):

>>> import numpy as np
>>> x = np.array([[1,0,1],[0,0,1],[1,1,0]])
>>> y = np.array([[1,0,1],[0,0,1],[1,1,1]])

Then finding the number of corresponding equal elements is as simple as:

>>> (x == y).sum() / x.size
0.8888888888888888

This works because x == y "broadcasts" the comparison to each corresponding element pair:

>>> x == y
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True, False]])

and then we add up the boolean values (converted to integer, True has a value of 1 and False has a value of 0) and divide by the total number of elements.


问:
Haskell in java, how can i implement "any"(haskell) in java?
So how can i implement "any"(Haskell) to java?

The "any" haskell code:

any p = foldr' (\x y -> p x || y) False

and my first try is this, but i dont know how i write p x in java.

```<code>boolean any(List<A> xs) {
return foldr(x -> y -> x==y || y, false, xs);
}
</code>```

答:
You would write p(x), BUT your Java implementation doesn't take p as an argument. I think your signature should be

```<code>boolean any (Predicate<? super A> p, List<A> xs)
</code>```

Body:
So how can i implement "any"(Haskell) to java?

The "any" haskell code:

any p = foldr' (\x y -> p x || y) False

and my first try is this, but i dont know how i write p x in java.

boolean any(List xs) {
return foldr(x -> y -> x==y || y, false, xs);
}

Body:
You would write p(x), BUT your Java implementation doesn't take p as an argument. I think your signature should be

boolean any (Predicate<? super A> p, List<A> xs)


问:
Issue with arabic language translation in android
I am having string like this in my string.xml for arabic language.

```<code><string name="storyboard_duration" ><xliff:g id="duration" >%1$ds</xliff:g></string>
<string name="str_date_yymmdd_format"><xliff:g id="date" >%1$d-%2$d-%3$d</xliff:g></string>
<string name="str_date_ddmmyy"><xliff:g id="date_summary" >dd-mm-yy</xliff:g></string>
</code>```

it is still translating number in arabic rather than showing in English.

答:
Somewhere the system is getting a right-to-left signal. This could be coming from device settings. One thing you could try is to force a language and ltr (left-to-right) direction in the xml code through the lang and dir attributes. See this question and answer for more on this:

Does XML officially support a "dir" or "xml:dir" attribute?

Body:
I am having string like this in my string.xml for arabic language.

<string name="storyboard_duration" ><xliff:g id="duration" >%1$ds</xliff:g></string>
<string name="str_date_yymmdd_format"><xliff:g id="date" >%1$d-%2$d-%3$d</xliff:g></string>
<string name="str_date_ddmmyy"><xliff:g id="date_summary" >dd-mm-yy</xliff:g></string>

it is still translating number in arabic rather than showing in English.


答:
Let's try:

```<code>s = df.groupby('b').cumcount().sort_values(kind='mergesort')

df = df.loc[s.index]
</code>```

Output:

```<code>   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3
</code>```

Title: How to sort pandas dataframe in a special way

Body:
Let's try:

s = df.groupby('b').cumcount().sort_values(kind='mergesort')

df = df.loc[s.index]

Output:

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3


问:
Syntax error in mySql to create Procedures
```<code>DELIMITER $$
DROP PROCEDURE IF EXISTS `unitstoamount`;
CREATE DEFINER=`root`@`localhost` PROCEDURE `unitstoamount`( IN units INT(14) , OUT result INT(14))
BEGIN

    DECLARE a INT(14) DEFAULT 0;
    DECLARE b INT(14) DEFAULT 0;
    DECLARE c INT(14) DEFAULT 0;

    SELECT twohundred FROM unitsRate INTO a ;
    SELECT fivehundred FROM unitsRate INTO b ;
    SELECT thousand FROM unitsRate INTO c  ;

    IF units<200
    then
        SELECT a*units INTO result;

    ELSEIF units<500
    then
        SELECT (a*200)+(b*(units-200)) INTO result;
    ELSEIF units > 500
    then
        SELECT (a*200)+(b*(300))+(c*(units-500)) INTO result;
    END IF;

END$$
DELIMITER ;
</code>```

答:
You have set the DELIMITER to be $$. So, you should use it also in the DROP PROCEDURE statement:

```<code>DELIMITER $$
DROP PROCEDURE IF EXISTS `unitstoamount`
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `unitstoamount`( IN units INT(14) , OUT result INT(14))
...
</code>```

Body:
You have set the DELIMITER to be $$. So, you should use it also in the DROP PROCEDURE statement:

DELIMITER $$
DROP PROCEDURE IF EXISTS `unitstoamount`
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `unitstoamount`( IN units INT(14) , OUT result INT(14))
...


问:
Vue Remove duplicates from an array of string
I am using [...new Map] on date which should pass an unique values of date only. But console.log(uniqueObjects); does not print out unique date values. There is something that I am doing wrong at [...new Map(date.map(item => [item.date, item])).values()]; which is not passing the unique date values. Is there a way to print unique date value using class='filter'?

SCRIPT

```<code>new Vue({
  el: "#app",
  data: {
    todos: [
      { id:"1", date:"2020-05-28T18:30:00.000Z", peopleName: "David" },
      { id:"2", date:"2020-05-28T18:30:00.000Z", peopleName: "Jack" },
      { id:"3", date:"2020-05-28T20:00:00.000Z", peopleName: "John" },
      { id:"4", date:"2020-05-28T20:00:00.000Z", peopleName: "Thomas" },
      { id:"5", date:"2020-05-28T20:00:00.000Z", peopleName: "Will" },
      { id:"6", date:"2020-05-28T21:30:00.000Z", peopleName: "Hary" },
    ]
  },
  computed:{
    filter: {
    moment: function (date) {
        console.log("its not printing");

        /** return moment(date).format('h:mm A') **/

        console.log(date);

        const uniqueObjects = [...new Map(date.map(item => [item.date, item])).values()];

       /** i am using new Map to remove the same value for date but it's not working **/

       console.log(uniqueObjects);
    }
  }
 },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
</code>```

VIEW

```<code><div id="app">
  <div v-for="reservation in todos" v-bind:key="reservation.id">
     <p class="filter">{{ reservation.date | moment }}</p>
     <p>{{reservation.peopleName}}</p>
  </div>
</div>
</code>```

Below is the link for the code on jsfidddle

https://jsfiddle.net/ujjumaki/ro5p4kxt/21/

答:
You wanted to create a moment filter but you put it inside the computed property! that's why your console.log is not printing.

Is there a way to print unique date value using class='filter'?

you're confusing css with vueJs, class='filter' is just used for styling, if you want to show unique values you have to filter your todos array in v-for="reservation in todos"

Please re-read this section https://v2.vuejs.org/v2/guide/filters.html and https://v2.vuejs.org/v2/guide/list.html

Body:
I am using [...new Map] on date which should pass an unique values of date only. But console.log(uniqueObjects); does not print out unique date values. There is something that I am doing wrong at [...new Map(date.map(item => [item.date, item])).values()]; which is not passing the unique date values. Is there a way to print unique date value using class='filter'?

SCRIPT

new Vue({
  el: "#app",
  data: {
    todos: [
      { id:"1", date:"2020-05-28T18:30:00.000Z", peopleName: "David" },
      { id:"2", date:"2020-05-28T18:30:00.000Z", peopleName: "Jack" },
      { id:"3", date:"2020-05-28T20:00:00.000Z", peopleName: "John" },
      { id:"4", date:"2020-05-28T20:00:00.000Z", peopleName: "Thomas" },
      { id:"5", date:"2020-05-28T20:00:00.000Z", peopleName: "Will" },
      { id:"6", date:"2020-05-28T21:30:00.000Z", peopleName: "Hary" },
    ]
  },
  computed:{
    filter: {
    moment: function (date) {
        console.log("its not printing");

        /** return moment(date).format('h:mm A') **/

        console.log(date);

        const uniqueObjects = [...new Map(date.map(item => [item.date, item])).values()];

       /** i am using new Map to remove the same value for date but it's not working **/

       console.log(uniqueObjects);
    }
  }
 },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})

VIEW

{{ reservation.date | moment }}

{{reservation.peopleName}}

Below is the link for the code on jsfidddle

https://jsfiddle.net/ujjumaki/ro5p4kxt/21/


问:
Python Web Framework for Small Team
I have 4 days off and I will use this time to rewrite our RoR (Ruby on Rails) Application in a python web framework just for fun ;-] (and why not make the switch, RoR is great but keep changing all the time, can be exhausting.)

I don't know the python web framework very well, I've glad web.py, django, cherry.py, pylons/pyramid and few others. Our requirements are (put everything can be irrelevant) :

MVC (Strict or not)

Small Team (2-3 people included one designer)

Fun to use

REST support

Multilevel caching (DB query, page cache)

Nginx Support (X-Accel-Redirect File Download)

Heavy traffic (1,200,000 ~ views)

Urls rewrting (Multi-domains support not only subdomain)

Not a problem if it's not hype

Not a problem if there is no plugins

Either SQL or NOSQL (can be fun to try NOSQL)

So what you would advise ?

答:
I think most of the big frameworks will fit your requirements so maybe you might look at it from the perspective of the app you are writing. How much do you want to work "out of the box". Will you need user management? Will you need an admin panel etc.

I use Django and it's great when you don't want to rewrite a lot of boilerplate. It can be a bit tedious at times trying to bend it to do what you want, but once you get your head around it's intricacies , you can get things done very quickly.

With Django anyway:

MVC (Strict or not)

Not MVC, but similar > http://www.djangobook.com/en/2.0/chapter05/#cn16

Small Team (2-3 people included one designer)

not sure how the framework will effect this, but yes, it's quick to develop on your own or with a team via version control

Fun to use

well there's a lot of great documentation, so less time is spent pulling your hair out, and you can get going very quickly which is nice

REST support

Yes, as a library: > https://bitbucket.org/jesperndjjango-piston/wiki/Home

Multilevel caching (DB query, page cache)

Yep > https://docs.djangoproject.com/en/dev/topics/cache/?from=olddocs

Nginx Support (X-Accel-Redirect File Download)

Again, not sure this is relevant, but yes. I use nginx with UWSGI and it's very quick

Heavy traffic (1,200,000 ~ views)

Yes > Does Django scale?

Urls rewriting (Multi-domains support not only subdomain)

Not sure about this

Not a problem if it's not hype

It's no node-js, but again, lots of really good documentation

Not a problem if there is no plugins

There are .... my god there are

Either SQL or NOSQL (can be fun to try NOSQL)

SQL out of the box, but NOSQL is supported > http://www.allbuttonspressed.com/projects/django-nonrel

ContentLicense: CC BY-SA 3.0

Title: Python Web Framework for Small Team


问:
How can I make all the points on a dense plot visible in matplotlib?
I'm using this basic code to display a plot using matplotlib. The lists for the x and y axis are large.

plt.plot(r,trajectory,"k.")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()
```

<p>How can I format my plot better to view all the details? </p>

<p>With the above configuration what I see is</p>

<p><img src="https://i.stack.imgur.com/VEFsP.png" alt="Initial"></p>

<p>But what I want to get to is something that looks like this with each point visible (atleast high enough resolution to zoom in)</p>

<p><img src="https://i.stack.imgur.com/trN4q.png" alt="final"></p>

<p>Update:
I found that tuning the available parameters iteratively can yield good results. Used a combination of the answers below to understand parameters and arrive at this configuration.</p>

<pre class="lang-py prettyprint-override"><code>f = plt.figure(figsize=(6,4),dpi=300)
plt.plot(r, trajectory, "k,", markersize=0.01, mew=0)
f.savefig("bifurcation_diag.png")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()
</code>```

答:
I think you can obtain this result by setting the transparency of the plot. Try this:</p>

```<code>#just add alpha to your plt.plot() method
plt.plot(r,trajectory,"k.", alpha=0.2)
</code>```

Body:
I'm using this basic code to display a plot using matplotlib. The lists for the x and y axis are large.

plt.plot(r,trajectory,"k.")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()

How can I format my plot better to view all the details?

With the above configuration what I see is

But what I want to get to is something that looks like this with each point visible (atleast high enough resolution to zoom in)

Update:
I found that tuning the available parameters iteratively can yield good results. Used a combination of the answers below to understand parameters and arrive at this configuration.

f = plt.figure(figsize=(6,4),dpi=300)
plt.plot(r, trajectory, "k,", markersize=0.01, mew=0)
f.savefig("bifurcation_diag.png")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()

Body:
I think you can obtain this result by setting the transparency of the plot. Try this:

#just add alpha to your plt.plot() method
plt.plot(r,trajectory,"k.", alpha=0.2)


问:
Python:Group By Multiple Column Pandas
I'm trying to group by a flattened data such as 2 columns group as list & the third one should be the sum of rows of that column .

Suppose data frame looks like

```<code>ColA      ColB     ColC     ColD
A         Hi       Hello     2
A         There    You       4
B         Okay     Tap       4
B         Bye      Here      6
</code>```

I want the output dataframe to look like:

```<code>ColA     ColB        ColC          ColD
A       [Hi,There]   [Hello,You]    6
B       [Okay,Bye]   [Tap,Here]     10
</code>```

答:
IIUC, try groupby with agg and a dictionary defining how to aggregate the columns:

```<code>df.groupby('ColA').agg({'ColB':list, 'ColC':list, 'ColD':'sum'})
</code>```

Output:

```<code>             ColB          ColC  ColD
ColA
A     [Hi, There]  [Hello, You]     6
B     [Okay, Bye]   [Tap, Here]    10
</code>```

Title: Python:Group By Multiple Column Pandas

Body:
I'm trying to group by a flattened data such as 2 columns group as list & the third one should be the sum of rows of that column .

Suppose data frame looks like

ColA      ColB     ColC     ColD
A         Hi       Hello     2
A         There    You       4
B         Okay     Tap       4
B         Bye      Here      6

I want the output dataframe to look like:

ColA     ColB        ColC          ColD
A       [Hi,There]   [Hello,You]    6
B       [Okay,Bye]   [Tap,Here]     10

Body:
IIUC, try groupby with agg and a dictionary defining how to aggregate the columns:

df.groupby('ColA').agg({'ColB':list, 'ColC':list, 'ColD':'sum'})

Output:

             ColB          ColC  ColD
ColA
A     [Hi, There]  [Hello, You]     6
B     [Okay, Bye]   [Tap, Here]    10


问:
How to retrieve a title attribute from an image using Beautiful Soup
```<code>container = page_soup.findAll("img",{"class":"logo"})
container[0]
<img alt="GIGABYTE" class="logo" src="//c1.neweggimages.com/brandimage//Brand1314.gif" title="GIGABYTE">
</img>
</code>```

How can I scrape the world "GIGABYTE" as text from the above?

I am a beginner at this.

```<code>container = page_soup.findAll("img",{"class":"logo"})

container[0]  and the Result => img alt="GIGABYTE" class="logo" src="//c1.neweggimages.com/brandimage//Brand1314.gif" title="GIGABYTE">
</code>```

Now I can scrape the word "GIGABYTE" as text from the above result. I am a beginner at this. plz, help.

sorry this is the question

答:
It appears that webscraping goes against the terms of service of that website, however I believe you're free to do whatever you'd like with the html if you obtain it manually.

soup.find_all('img', class_='logo')[0]['title']

Body:
container = page_soup.findAll("img",{"class":"logo"})
container[0]

How can I scrape the world "GIGABYTE" as text from the above?

I am a beginner at this.

container = page_soup.findAll("img",{"class":"logo"})

container[0]  and the Result => img alt="GIGABYTE" class="logo" src="//c1.neweggimages.com/brandimage//Brand1314.gif" title="GIGABYTE">

Now I can scrape the word "GIGABYTE" as text from the above result. I am a beginner at this. plz, help.

sorry this is the question


问:
Difference between two date strings in java
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

```<code>public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }
</code>```

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

```<code>try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.

答:
If you parse dates with a resolution of 1 day, i.e. 86.000.000 milliseconds, you will never get a situation where they are exactly 3 ms different.

getTime() returns the time in ms since "the start of the epoch", so it returns milliseconds, or 1/1000 s.

```<code>diff < 3 || diff > 3
</code>```

is the same as

```<code>diff != 3
</code>```

If you want to detect dates which are exactly 3 days different, you could divide the number of millis by the number of ms/day before comparing.

Body:
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.

Body:
If you parse dates with a resolution of 1 day, i.e. 86.000.000 milliseconds, you will never get a situation where they are exactly 3 ms different.

getTime() returns the time in ms since "the start of the epoch", so it returns milliseconds, or 1/1000 s.

diff < 3 || diff > 3

is the same as

diff != 3

If you want to detect dates which are exactly 3 days different, you could divide the number of millis by the number of ms/day before comparing.


问:
Pythonic way to access data from a tuple?
I am working with sklearn's partial_dependency function. I am aware of the plot_partial_dependency function, but I am not interested in using it.

I want to, for each feature in my dataset, determine the average dependency to create a dict of features and their average dependency. I have the ability to do this, but quite frankly, the solution is rather verbose with how I am accessing the tuple that is returned from partial_dependency. Is there a more pythonic way to get the average of the first ndarray returned in the tuple?

Code below:

```<code>feature_dict = {}

for feature in X_test.columns:
    results = partial_dependence(mlp, X_test, features=feature,
                                percentiles=(0.001, 0.999), grid_resolution=25)
    lists = [x for x in results]
    yx = lists[0]
    y=yx[0]
    feature_dict[feature] = np.avg(y)
</code>```

This works, as if I print(feature_dict) I get:

{'Feature0': 0.8403025353927007, 'Feature1': 0.7832550769883906, 'Feature2': 0.8396910956294878, 'Feature3': 0.6738822611060408, 'Feature4': 0.45209427548019937}

However, the code isn't pythonic and is a confusing way to access the tuple released from the partial_dependence function. What can I do for a more simple solution?

答:
"...is a confusing way to access the tuple released from the partial_dependence function."

If results is a tuple, then [x for x in results] could just be results = list(results). But list items can be accessed by index just like tuples. So there's no need to convert it to a tuple first.

You're then doing yx = lists[0] which refers to the first part of the return value of partial_dependence(). That's averaged_predictions. So that line could have been just yx = results.averaged_predictions.

Then, y=yx[0] which is the first element of the first part of the partial_dependence return value. That would be y = results.averaged_predictions[0].

Putting all that together, the code becomes:

feature_dict = {}

for feature in X_test.columns:
    results = partial_dependence(mlp, X_test, features=feature,
                                 percentiles=(0.001, 0.999), grid_resolution=25)
    y = results.averaged_predictions[0]
    feature_dict[feature] = np.avg(y)
```

<p>And unless you're processing <code>y</code> further, it doesn't need to be assigned separately:</p>

<pre class="lang-py prettyprint-override"><code>for feature in X_test.columns:
    results = partial_dependence(mlp, X_test, features=feature,
                                 percentiles=(0.001, 0.999), grid_resolution=25)
    feature_dict[feature] = np.avg(results.averaged_predictions[0])
</code>```

Next step optional, and discouraged due to how it looks - you could make that whole loop a large almost-unreadable dictionary comprehension:

feature_dict = {
    feature: np.avg(
                partial_dependence(mlp, X_test,
                                   features=feature,
                                   percentiles=(0.001, 0.999),
                                   grid_resolution=25
                ).averaged_predictions[0])
    for feature in X_test.columns
}
```

Body:
I am working with sklearn's partial_dependency function. I am aware of the plot_partial_dependency function, but I am not interested in using it.

I want to, for each feature in my dataset, determine the average dependency to create a dict of features and their average dependency. I have the ability to do this, but quite frankly, the solution is rather verbose with how I am accessing the tuple that is returned from partial_dependency. Is there a more pythonic way to get the average of the first ndarray returned in the tuple?

Code below:

feature_dict = {}

for feature in X_test.columns:
    results = partial_dependence(mlp, X_test, features=feature,
                                percentiles=(0.001, 0.999), grid_resolution=25)
    lists = [x for x in results]
    yx = lists[0]
    y=yx[0]
    feature_dict[feature] = np.avg(y)

This works, as if I print(feature_dict) I get:

{'Feature0': 0.8403025353927007, 'Feature1': 0.7832550769883906, 'Feature2': 0.8396910956294878, 'Feature3': 0.6738822611060408, 'Feature4': 0.45209427548019937}

However, the code isn't pythonic and is a confusing way to access the tuple released from the partial_dependence function. What can I do for a more simple solution?

Body:
"...is a confusing way to access the tuple released from the partial_dependence function."

If results is a tuple, then [x for x in results] could just be results = list(results). But list items can be accessed by index just like tuples. So there's no need to convert it to a tuple first.

You're then doing yx = lists[0] which refers to the first part of the return value of partial_dependence(). That's averaged_predictions. So that line could have been just yx = results.averaged_predictions.

Then, y=yx[0] which is the first element of the first part of the partial_dependence return value. That would be y = results.averaged_predictions[0].

Putting all that together, the code becomes:

feature_dict = {}

for feature in X_test.columns:
    results = partial_dependence(mlp, X_test, features=feature,
                                 percentiles=(0.001, 0.999), grid_resolution=25)
    y = results.averaged_predictions[0]
    feature_dict[feature] = np.avg(y)

And unless you're processing y further, it doesn't need to be assigned separately:

for feature in X_test.columns:
    results = partial_dependence(mlp, X_test, features=feature,
                                 percentiles=(0.001, 0.999), grid_resolution=25)
    feature_dict[feature] = np.avg(results.averaged_predictions[0])

Next step optional, and discouraged due to how it looks - you could make that whole loop a large almost-unreadable dictionary comprehension:

feature_dict = {
    feature: np.avg(
                partial_dependence(mlp, X_test,
                                   features=feature,
                                   percentiles=(0.001, 0.999),
                                   grid_resolution=25
                ).averaged_predictions[0])
    for feature in X_test.columns
}


答:
If you are using NumPy you can compare them and get the following output:

```<code>import numpy as np
a = np.array([[1,0,1],[0,0,1],[1,1,0]])
b = np.array([[1,0,1],[0,0,1],[1,1,1]])

print(a == b)
Out: matrix([[ True,  True,  True],
             [ True, True,  True],
             [ True,  True,  False]],
</code>```

To count the matches you can reshape the matrices to a list and count the matching values:

```<code>import numpy as np
a = np.array([[1,0,1],[0,0,1],[1,1,0]])
b = np.array([[1,0,1],[0,0,1],[1,1,1]])

res = list(np.array(a==b).reshape(-1,))
print(f'{res.count(True)}/{len(res)}')

Out: 8/9
</code>```

Title: How can I compare two matrixes for similarity using Python?

Body:
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

1 0 1
0 0 1
1 1 0

I would like to compare this to matrix y:

1 0 1
0 0 1
1 1 1

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?

Body:
If you are using NumPy you can compare them and get the following output:

import numpy as np
a = np.array([[1,0,1],[0,0,1],[1,1,0]])
b = np.array([[1,0,1],[0,0,1],[1,1,1]])

print(a == b)
Out: matrix([[ True,  True,  True],
             [ True, True,  True],
             [ True,  True,  False]],

To count the matches you can reshape the matrices to a list and count the matching values:

import numpy as np
a = np.array([[1,0,1],[0,0,1],[1,1,0]])
b = np.array([[1,0,1],[0,0,1],[1,1,1]])

res = list(np.array(a==b).reshape(-1,))
print(f'{res.count(True)}/{len(res)}')

Out: 8/9


问:
How to specify the filter condition with spark DataFrameReader API for a table?
I was reading about spark on databricks documentation https://docs.databricks.com/data/tables.html#partition-pruning-1

It says

When the table is scanned, Spark pushes down the filter predicates
  involving the partitionBy keys. In that case, Spark avoids reading
  data that doesn’t satisfy those predicates. For example, suppose you
  have a table  that is partitioned by <date>. A query
  such as SELECT max(id) FROM <example-data> WHERE date = '2010-10-10'
  reads only the data files containing tuples whose date value matches
  the one specified in the query.

How can I specify such filter condition in DataFrameReader API while reading a table?

答:
DataFrameReader is created (available) exclusively using SparkSession.read.
That means it is created when the following code is executed (example of csv file load)

```<code>val df = spark.read.csv("path1,path2,path3")
</code>```

Spark provides a pluggable Data Provider Framework (Data Source API) to rollout your own datasource. Basically, it provides interfaces that can be implemented for reading/writing to your custom datasource. That's where generally the partition pruning and predicate filter pushdowns are implemented.

Databricks spark supports many built-in datasources (along with predicate pushdown and partition pruning capabilities) as per https://docs.databricks.com/data/data-sources/index.html.

So, if the need is to load data from JDBC table and specify filter conditions, please see the following example

```<code>// Note: The parentheses are required.
val pushdown_query = "(select * from employees where emp_no < 10008) emp_alias"
val df = spark.read.jdbc(url=jdbcUrl, table=pushdown_query, properties=connectionProperties)
display(df)
</code>```

Please refer to more details here
https://docs.databricks.com/data/data-sources/sql-databases.html

Body:
DataFrameReader is created (available) exclusively using SparkSession.read.
That means it is created when the following code is executed (example of csv file load)

val df = spark.read.csv("path1,path2,path3")

Spark provides a pluggable Data Provider Framework (Data Source API) to rollout your own datasource. Basically, it provides interfaces that can be implemented for reading/writing to your custom datasource. That's where generally the partition pruning and predicate filter pushdowns are implemented.

Databricks spark supports many built-in datasources (along with predicate pushdown and partition pruning capabilities) as per https://docs.databricks.com/data/data-sources/index.html.

So, if the need is to load data from JDBC table and specify filter conditions, please see the following example

// Note: The parentheses are required.
val pushdown_query = "(select * from employees where emp_no < 10008) emp_alias"
val df = spark.read.jdbc(url=jdbcUrl, table=pushdown_query, properties=connectionProperties)
display(df)

Please refer to more details here
https://docs.databricks.com/data/data-sources/sql-databases.html


问:
Prevent the app to run twice, instead show the first window
I have a wpf app and I have to make the app to be run only once. There shouldnt be more than one instance on one machine.

Here's my code in App.xaml.cs, in the OnStartup() method:

```<code>var runningProcess = GetAnotherAppInstanceIfExists();

            if (runningProcess != null)
            {
                HandleMultipleInstances(runningProcess);
                Environment.Exit(0);
            }

public Process GetAnotherAppInstanceIfExists()
    {
        var currentProcess = Process.GetCurrentProcess();

        var appProcesses = new List<string> { "myApp", "myApp.vshost" };

        var allProcesses = Process.GetProcesses();

        var myAppProcess = (from process in allProcesses
            where process.Id != currentProcess.Id && appProcesses.Contains(process.ProcessName)
            select process).FirstOrDefault();

        if (myAppProcess != null)
        {
            return currentProcess;
        }

        return myAppProcess;
    }

public void HandleMultipleInstances(Process runningProcess)
    {
        SetForegroundWindow(runningProcess.MainWindowHandle);
        ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);
    }
</code>```

So the app, when run for the second time, doesnt open a new instance, which is great. However, I need to find the first instance and show the window again, if it is minimized. This line is for that:

```<code>ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);
</code>```

and it doesn't work. What am I doing wrong? I looked at a lot of examples online and my code is the same as them.

答:
For me the solution was to do this:

change your App.xaml file's build action to Page. (right click on the file then properties => Build Action => dropdown to page)

in App.xaml.cs:

```<code>    private static readonly Mutex Mutex = new Mutex(true, "42ae83c2-03a0-472e-a2ea-41d69524a85b"); // GUI can be what you want !
    private static App _app;

    [STAThread]
    static void Main()
    {
        if (Mutex.WaitOne(TimeSpan.Zero, true))
        {
            _app = new App();
            _app.InitializeComponent();
            _app.Run();
            Mutex.ReleaseMutex();
        }
        else
        {
            //MessageBox.Show("You can only run one instance!");
            _app.MainWindow.WindowState = WindowState.Maximized;
        }
    }
</code>```

Body:
I have a wpf app and I have to make the app to be run only once. There shouldnt be more than one instance on one machine.

Here's my code in App.xaml.cs, in the OnStartup() method:

var runningProcess = GetAnotherAppInstanceIfExists();

            if (runningProcess != null)
            {
                HandleMultipleInstances(runningProcess);
                Environment.Exit(0);
            }

public Process GetAnotherAppInstanceIfExists()
    {
        var currentProcess = Process.GetCurrentProcess();

        var appProcesses = new List<string> { "myApp", "myApp.vshost" };

        var allProcesses = Process.GetProcesses();

        var myAppProcess = (from process in allProcesses
            where process.Id != currentProcess.Id && appProcesses.Contains(process.ProcessName)
            select process).FirstOrDefault();

        if (myAppProcess != null)
        {
            return currentProcess;
        }

        return myAppProcess;
    }

public void HandleMultipleInstances(Process runningProcess)
    {
        SetForegroundWindow(runningProcess.MainWindowHandle);
        ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);
    }

So the app, when run for the second time, doesnt open a new instance, which is great. However, I need to find the first instance and show the window again, if it is minimized. This line is for that:

ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);

and it doesn't work. What am I doing wrong? I looked at a lot of examples online and my code is the same as them.

Body:
For me the solution was to do this:

change your App.xaml file's build action to Page. (right click on the file then properties => Build Action => dropdown to page)

in App.xaml.cs:

    private static readonly Mutex Mutex = new Mutex(true, "42ae83c2-03a0-472e-a2ea-41d69524a85b"); // GUI can be what you want !
    private static App _app;

    [STAThread]
    static void Main()
    {
        if (Mutex.WaitOne(TimeSpan.Zero, true))
        {
            _app = new App();
            _app.InitializeComponent();
            _app.Run();
            Mutex.ReleaseMutex();
        }
        else
        {
            //MessageBox.Show("You can only run one instance!");
            _app.MainWindow.WindowState = WindowState.Maximized;
        }
    }


问:
Git error on git pull (unable to update local ref)
I only have branch master and im getting this error every time i try to "git pull":

```<code>error: Couldn't set refs/remotes/origin/master
From /var/lib/git/xxx/project
 ! a0f80ea..49177a3  master     -> origin/master  (unable to update local ref)
</code>```

and when i do "git pull origin master" i get:

```<code>error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.
</code>```

i have been searching but cant find why

答:
This work for me</p>

```<code>rm .git/logs/refs/remotes/origin/master
</code>```

Body:
I only have branch master and im getting this error every time i try to "git pull":

error: Couldn't set refs/remotes/origin/master
From /var/lib/git/xxx/project
 ! a0f80ea..49177a3  master     -> origin/master  (unable to update local ref)

and when i do "git pull origin master" i get:

error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.

i have been searching but cant find why

Body:
This work for me

rm .git/logs/refs/remotes/origin/master


问:
Finding Power set of a Set
[Homework Assignment]

We have to find the power set of a given set using Java or C++. The set will be accepted in the form of an array of any size and I need to display the elements of the power set of that set. Note that the only concepts to use are arrays, loops and functions (recursive and iterative).

I need someone to point me in the right direction regarding the logic I can apply.
Please help.

PS : Power set of a set A is the set of all subsets of set A
Eg. A = { a, b, c}
    Power Set of A = {{},{a},{b},{c},{a,b},{b,c},{a,c},{a,b,c}}

Edit:

Thanks a lot to "wy" and "MrSmith42"! I have written my program using the logic they have given. Now I am trying to optimize it. Note that I am new to Java and find it slightly uncomfortable due to its newness.

Here's my code :

```<code>import java.util.Scanner;

public class PowerSet {

    //Function to increment binary string...

    static String incr_bin (String binary){
        char bin[] = new char[100];
        int size_bin, i;
        size_bin = binary.length();
        bin = binary.toCharArray();
        bin[size_bin-1]++;
        for(i=size_bin-1; i>=0; i--){
            if (i != 0){
                if(bin[i] > '1'){
                    bin[i]='0';
                    bin[i-1]++;
                }
            }
        }
        if (bin[0]>'1'){
            for(i=0;i<size_bin;i++){
                bin[i]='0';
            }
        }
        binary = new String (bin);
        return binary;
    }

    public static void main(String[] args) {

        //Declarations

        Scanner in = new Scanner (System.in);
        int a[] = new int [100];
        int size_a, i, count=0;

        String binary;

        //Input

        System.out.println("Enter the number of elements in A : ");
        size_a = in.nextInt();
        char bin[] = new char [size_a];
        System.out.println("Enter the elements in A : ");
        for(i=0; i<size_a; i++){
            a[i] = in.nextInt();
            bin[i] = '0';
        }
        binary = new String(bin);

        //Calculating and Setting up subsets
        System.out.println("MEMBERS OF POWER SET :");
        do{
            System.out.print("\n{.");
            count = 0;
            binary = incr_bin(binary);
            bin = binary.toCharArray();
            for(i=0; i<size_a; i++){
                if (bin[i] == '0') count++;
                if (bin[i] == '1') System.out.print(a[i] + "  ");
            }
            System.out.println("}");
        }while(count!=size_a);
    }
}
</code>```

答:
Binary counting using increment/decrement is fine until your universal set has more elements than your biggest integral type has bits.  However, The rule of succession is quite simple.  Given subset S_k represented as a bit vector, you generate S_{k+1} as follows:

```<code>for i in 0..len(s):
  if s[i]:
    s[i] = 0
  else:
    s[i] = 1
    break
</code>```

Starting with [000], its easy to see this generates [100],[010],[110],[001],...[111].  To generate all of them, wrap the above in a loop and keep track of cardinality of the subset, adding or subtracting 1 as you set bits to 1 or 0.  Your last subset will have cardinality n.

Title: Finding Power set of a Set

Body:
[Homework Assignment]

We have to find the power set of a given set using Java or C++. The set will be accepted in the form of an array of any size and I need to display the elements of the power set of that set. Note that the only concepts to use are arrays, loops and functions (recursive and iterative).

I need someone to point me in the right direction regarding the logic I can apply.
Please help.

PS : Power set of a set A is the set of all subsets of set A
Eg. A = { a, b, c}
    Power Set of A = {{},{a},{b},{c},{a,b},{b,c},{a,c},{a,b,c}}

Edit:

Thanks a lot to "wy" and "MrSmith42"! I have written my program using the logic they have given. Now I am trying to optimize it. Note that I am new to Java and find it slightly uncomfortable due to its newness.

Here's my code :

import java.util.Scanner;

public class PowerSet {

    //Function to increment binary string...

    static String incr_bin (String binary){
        char bin[] = new char[100];
        int size_bin, i;
        size_bin = binary.length();
        bin = binary.toCharArray();
        bin[size_bin-1]++;
        for(i=size_bin-1; i>=0; i--){
            if (i != 0){
                if(bin[i] > '1'){
                    bin[i]='0';
                    bin[i-1]++;
                }
            }
        }
        if (bin[0]>'1'){
            for(i=0;i<size_bin;i++){
                bin[i]='0';
            }
        }
        binary = new String (bin);
        return binary;
    }

    public static void main(String[] args) {

        //Declarations

        Scanner in = new Scanner (System.in);
        int a[] = new int [100];
        int size_a, i, count=0;

        String binary;

        //Input

        System.out.println("Enter the number of elements in A : ");
        size_a = in.nextInt();
        char bin[] = new char [size_a];
        System.out.println("Enter the elements in A : ");
        for(i=0; i<size_a; i++){
            a[i] = in.nextInt();
            bin[i] = '0';
        }
        binary = new String(bin);

        //Calculating and Setting up subsets
        System.out.println("MEMBERS OF POWER SET :");
        do{
            System.out.print("\n{.");
            count = 0;
            binary = incr_bin(binary);
            bin = binary.toCharArray();
            for(i=0; i<size_a; i++){
                if (bin[i] == '0') count++;
                if (bin[i] == '1') System.out.print(a[i] + "  ");
            }
            System.out.println("}");
        }while(count!=size_a);
    }
}

Body:
Binary counting using increment/decrement is fine until your universal set has more elements than your biggest integral type has bits.  However, The rule of succession is quite simple.  Given subset S_k represented as a bit vector, you generate S_{k+1} as follows:

for i in 0..len(s):
  if s[i]:
    s[i] = 0
  else:
    s[i] = 1
    break

Starting with [000], its easy to see this generates [100],[010],[110],[001],...[111].  To generate all of them, wrap the above in a loop and keep track of cardinality of the subset, adding or subtracting 1 as you set bits to 1 or 0.  Your last subset will have cardinality n.


问:
Write list of lists to text file Java
I have a list of lists to write in a text file :

```<code>ArrayList<ArrayList<String>> list = new ArrayList<>();
</code>```

Sample List:

```<code>[["sample_string_one","sample_string_two","sample_string_three"],["sample_string_four","sample_string_five","sample_string_six"]]
</code>```

Writing to text file:

```<code>Path sPath = Paths.get("output.txt");
for (ArrayList sampleArr: list){
    Files.write(sPath,sampleArr);
 }
</code>```

Error:

The code works, but the error is the contents of the file output.txt gets updated.

Expected Contents of output.txt:

```<code>sample_string_one
sample_string_two
sample_string_three
sample_string_four
sample_string_five
sample_string_six
</code>```

Original Contents:

```<code>sample_string_four
sample_string_five
sample_string_six
</code>```

Essentially, the content of the file gets updated with the latest inner list in the list of lists. Any suggestions to solve this would be great.

答:
Try this:

Files.write(path, list, StandardOpenOption.APPEND);
```

From the documentation: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-byte:A-java.nio.file.OpenOption...-

If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present.

public static final StandardOpenOption TRUNCATE_EXISTING

If the file already exists and it is opened for WRITE access, then its length is truncated to 0. This option is ignored if the file is opened only for READ access.

What you want is:

public static final StandardOpenOption APPEND

If the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning.
If the file is opened for write access by other programs, then it is file system specific if writing to the end of the file is atomic.

Title: Write list of lists to text file Java

Body:
I have a list of lists to write in a text file :

ArrayList<ArrayList<String>> list = new ArrayList<>();

Sample List:

[["sample_string_one","sample_string_two","sample_string_three"],["sample_string_four","sample_string_five","sample_string_six"]]

Writing to text file:

Path sPath = Paths.get("output.txt");
for (ArrayList sampleArr: list){
    Files.write(sPath,sampleArr);
 }

Error:

The code works, but the error is the contents of the file output.txt gets updated.

Expected Contents of output.txt:

sample_string_one
sample_string_two
sample_string_three
sample_string_four
sample_string_five
sample_string_six

Original Contents:

sample_string_four
sample_string_five
sample_string_six

Essentially, the content of the file gets updated with the latest inner list in the list of lists. Any suggestions to solve this would be great.

Body:
Try this:

Files.write(path, list, StandardOpenOption.APPEND);

From the documentation: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-byte:A-java.nio.file.OpenOption...-

If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present.

public static final StandardOpenOption TRUNCATE_EXISTING

If the file already exists and it is opened for WRITE access, then its length is truncated to 0. This option is ignored if the file is opened only for READ access.

What you want is:

public static final StandardOpenOption APPEND

If the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning.
If the file is opened for write access by other programs, then it is file system specific if writing to the end of the file is atomic.


问:
jQuery - ajax request not hitting .error state
I've got a pretty simple ajax call that will hit the success state but won't hit the error state it just throws a 404. The odd thing is this works just fine in IE but not in firefox or chrome. If I change the data type to text it works fine in firefox but not IE. Any help is appreciated!

```<code>$.ajax({
    type: "GET",
    crossDomain: true,
    url: 'http://www.google.com',
    contentType: 'application/json; charset=utf-8',
    dataType: 'jsonp',
    jsonp: 'callback'
}).success(function(){
    console.log("success");
}).error(function(xhr, ajaxOptions, thrownError) {
    console.log("error");
});
</code>```

答:
Success and error do not exist. You need to call the JS functions done and fail instead. Also, for best practices use console.error instead of console.log on your fail condition.

Try the following code:

```<code>$.ajax({
    type: "GET",
    crossDomain: true,
    url: 'http://www.google.com',
    contentType: 'application/json; charset=utf-8',
    dataType: 'jsonp',
    jsonp: 'callback'
}).done(function(){
    console.log("success");
}).fail(function(xhr, ajaxOptions, thrownError) {
    console.error("error");
});
</code>```

Body:
I've got a pretty simple ajax call that will hit the success state but won't hit the error state it just throws a 404. The odd thing is this works just fine in IE but not in firefox or chrome. If I change the data type to text it works fine in firefox but not IE. Any help is appreciated!

$.ajax({
    type: "GET",
    crossDomain: true,
    url: 'http://www.google.com',
    contentType: 'application/json; charset=utf-8',
    dataType: 'jsonp',
    jsonp: 'callback'
}).success(function(){
    console.log("success");
}).error(function(xhr, ajaxOptions, thrownError) {
    console.log("error");
});

Body:
Success and error do not exist. You need to call the JS functions done and fail instead. Also, for best practices use console.error instead of console.log on your fail condition.

Try the following code:

$.ajax({
    type: "GET",
    crossDomain: true,
    url: 'http://www.google.com',
    contentType: 'application/json; charset=utf-8',
    dataType: 'jsonp',
    jsonp: 'callback'
}).done(function(){
    console.log("success");
}).fail(function(xhr, ajaxOptions, thrownError) {
    console.error("error");
});


问:
How to create an automation test for a workflow
I am working on a workflow project that has 19 scenarios for testing the whole system and 34 steps.

So, my question is, how can I create an automation test for it?

My current approach is:
Create an integrated test per each scenario, and then create the main system test to run all integrated tests.

```<code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Project1
{
     // Unit tests
    public class UnitTest_step1
    {
        public void RunTest() { }
    }

    public class UnitTest_step2
    {
        public void RunTest() { }
    }

    public class UnitTest_step3
    {
        public void RunTest() { }
    }

    public class UnitTest_step4
    {
        public void RunTest() { }
    }
     // End of unit tests

    public class IntegrationTests
    {

        public void IntegrationTest1()
        {
            UnitTest_step1.RunTest();
            UnitTest_step2.RunTest();
            UnitTest_step4.RunTest();
        }

        public void IntegrationTest2()
        {
            UnitTest_step1.RunTest();
            UnitTest_step2.RunTest();
            UnitTest_step3.RunTest();
            UnitTest_step4.RunTest();
        }

        public void IntegrationTest3()
        {
            UnitTest_step1.RunTest();
            UnitTest_step4.RunTest();
        }

    }

    [TestClass]
    public class SystemTests
    {
        [TestMethod]
        public void Scenario1()
        {
            IntegrationTests.IntegrationTest1()
        }

        [TestMethod]
        public void Scenario2()
        {
            IntegrationTests.IntegrationTest2();
        }

        [TestMethod]
        public void Scenario3()
        {
            IntegrationTests.IntegrationTest3();
        }

        [TestMethod]
        public void ScenarioN()
        {
            IntegrationTests.IntegrationTestN();
        }
    }
}
</code>```

Best Regards.

答:
Well, in my opinion, the information provided in your question is very abstract and the question is a bit too broad.
The answer depends on how your workflow engine is implemented and what are your system requirements.
Requirements and implementation details are what defines your approach to testing.

I would start with clarifying what kind of steps you have, is there any data context is passed,
what side effects these steps produce (writes data to database, sends events, call other system APIs, etc.),
do steps depend on each other and so on.

Another question is how do you need to assert the results, after each step or after scenario?
The system should be testable and normally, each step should be covered with unit tests.
So, suggested hypothetical approach is to cover each step with isolated unit tests
and scenarios with integration tests.

I came up with a simple example just to illustrate one of the general approaches.
For simplicity, I assume that steps have little or no data context and can be reordered.

```<code>namespace Workflow.Test
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;
    using System.Collections.Generic;

    [TestClass]
    public class SystemTests
    {
        [TestMethod]
        public void Scenario1()
        {
            new Workflow().Run(new Scenario1());
        }

        [TestMethod]
        public void Scenario2()
        {
            new Workflow().Run(new Scenario2());
        }

        // The advantage of explicit steps declaration is test readability.
        // Declarative approach also enables the further possibility of test generation!
        [TestMethod]
        public void MoreExplicitAndDeclarative()
        {
            new Workflow().Run(new List<Type>
            {
                typeof(Step1),
                typeof(Step2),
                typeof(Step3),
            });
        }

        // Step instantiation may be needed if you want to parameterize some steps.
        [TestMethod]
        [DataRow("Custom step")]
        [DataRow("Another step")]
        public void MoreExplicitParameterizedScenario(string customName)
        {
            new Workflow().Run(new List<IRunnable>{
                new Step1(),
                new Step3(customName)
            });
        }
    }

    [TestClass]
    public class StepsUnitTests
    {
        [TestMethod]
        public void Step1DoesWhatWeWant()
        {
            // Mock dependencies

            new Step1().Run();

            // Assert results
        }
    }

    #region Workflow Engine Example

    public interface IRunnable
    {
        void Run();
    }

    public class Workflow
    {
        public void Run(Scenario scenario)
        {
            Run(CreateSteps(scenario.GetStepTypes()));
        }

        public void Run(IEnumerable<Type> stepTypes)
        {
            Run(CreateSteps(stepTypes));
        }

        public void Run(List<IRunnable> steps)
        {
            steps.ForEach(step => step.Run());
        }

        private List<IRunnable> CreateSteps(IEnumerable<Type> stepTypes)
        {
            var steps = new List<IRunnable>();
            foreach (var stepType in stepTypes)
            {
                steps.Add(CreateStep(stepType));
            }

            return steps;
        }

        private IRunnable CreateStep(Type stepType)
            => (IRunnable) Activator.CreateInstance(stepType);
    }

    #endregion

    // Step structure can differ according to system requirements.
    // We may add data context and link steps into pipeline if needed.
    #region Steps

    public abstract class Step : IRunnable
    {
        private readonly string _stepName;

        protected Step(string name)
        {
            _stepName = name;
        }

        public void Run()
        {
            Console.WriteLine($"{_stepName} in action.");
            Invoke();
        }

        public abstract void Invoke();
    }

    public class Step1 : Step
    {
        public Step1() : base(nameof(Step1))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step1 invoked.");
        }
    }

    public class Step2 : Step
    {
        public Step2() : base(nameof(Step2))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step2 invoked.");
        }
    }

    public class Step3 : Step
    {
        public Step3(string customName) : base(customName)
        {

        }

        public Step3() : this(nameof(Step3))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step3 invoked.");
        }
    }

    public class Step4 : Step
    {
        public Step4() : base(nameof(Step4))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step4 invoked.");
        }
    }

    #endregion

    // Scenarios should be as declarative as possible.
    // Let's say the scenario is just specification of what steps (step Type)
    // and in what order should be executed (List as a non-unique ordered collection).
    #region Scenarios

    public abstract class Scenario
    {
        public abstract List<Type> GetStepTypes();
    }

    public class Scenario1 : Scenario
    {
        public override List<Type> GetStepTypes()
            => new List<Type>
            {
                typeof(Step1),
                typeof(Step2),
                typeof(Step3)
            };
    }

    public class Scenario2 : Scenario
    {
        public override List<Type> GetStepTypes()
            => new List<Type>
            {
                typeof(Step1),
                typeof(Step2),
                typeof(Step4)
            };
    }

    #endregion
}
</code>```

Body:
I am working on a workflow project that has 19 scenarios for testing the whole system and 34 steps.

So, my question is, how can I create an automation test for it?

My current approach is:
Create an integrated test per each scenario, and then create the main system test to run all integrated tests.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Project1
{
     // Unit tests
    public class UnitTest_step1
    {
        public void RunTest() { }
    }

    public class UnitTest_step2
    {
        public void RunTest() { }
    }

    public class UnitTest_step3
    {
        public void RunTest() { }
    }

    public class UnitTest_step4
    {
        public void RunTest() { }
    }
     // End of unit tests

    public class IntegrationTests
    {

        public void IntegrationTest1()
        {
            UnitTest_step1.RunTest();
            UnitTest_step2.RunTest();
            UnitTest_step4.RunTest();
        }

        public void IntegrationTest2()
        {
            UnitTest_step1.RunTest();
            UnitTest_step2.RunTest();
            UnitTest_step3.RunTest();
            UnitTest_step4.RunTest();
        }

        public void IntegrationTest3()
        {
            UnitTest_step1.RunTest();
            UnitTest_step4.RunTest();
        }

    }

    [TestClass]
    public class SystemTests
    {
        [TestMethod]
        public void Scenario1()
        {
            IntegrationTests.IntegrationTest1()
        }

        [TestMethod]
        public void Scenario2()
        {
            IntegrationTests.IntegrationTest2();
        }

        [TestMethod]
        public void Scenario3()
        {
            IntegrationTests.IntegrationTest3();
        }

        [TestMethod]
        public void ScenarioN()
        {
            IntegrationTests.IntegrationTestN();
        }
    }
}

Best Regards.

Body:
Well, in my opinion, the information provided in your question is very abstract and the question is a bit too broad.
The answer depends on how your workflow engine is implemented and what are your system requirements.
Requirements and implementation details are what defines your approach to testing.

I would start with clarifying what kind of steps you have, is there any data context is passed,
what side effects these steps produce (writes data to database, sends events, call other system APIs, etc.),
do steps depend on each other and so on.

Another question is how do you need to assert the results, after each step or after scenario?
The system should be testable and normally, each step should be covered with unit tests.
So, suggested hypothetical approach is to cover each step with isolated unit tests
and scenarios with integration tests.

I came up with a simple example just to illustrate one of the general approaches.
For simplicity, I assume that steps have little or no data context and can be reordered.

namespace Workflow.Test
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;
    using System.Collections.Generic;

    [TestClass]
    public class SystemTests
    {
        [TestMethod]
        public void Scenario1()
        {
            new Workflow().Run(new Scenario1());
        }

        [TestMethod]
        public void Scenario2()
        {
            new Workflow().Run(new Scenario2());
        }

        // The advantage of explicit steps declaration is test readability.
        // Declarative approach also enables the further possibility of test generation!
        [TestMethod]
        public void MoreExplicitAndDeclarative()
        {
            new Workflow().Run(new List<Type>
            {
                typeof(Step1),
                typeof(Step2),
                typeof(Step3),
            });
        }

        // Step instantiation may be needed if you want to parameterize some steps.
        [TestMethod]
        [DataRow("Custom step")]
        [DataRow("Another step")]
        public void MoreExplicitParameterizedScenario(string customName)
        {
            new Workflow().Run(new List<IRunnable>{
                new Step1(),
                new Step3(customName)
            });
        }
    }

    [TestClass]
    public class StepsUnitTests
    {
        [TestMethod]
        public void Step1DoesWhatWeWant()
        {
            // Mock dependencies

            new Step1().Run();

            // Assert results
        }
    }

    #region Workflow Engine Example

    public interface IRunnable
    {
        void Run();
    }

    public class Workflow
    {
        public void Run(Scenario scenario)
        {
            Run(CreateSteps(scenario.GetStepTypes()));
        }

        public void Run(IEnumerable<Type> stepTypes)
        {
            Run(CreateSteps(stepTypes));
        }

        public void Run(List<IRunnable> steps)
        {
            steps.ForEach(step => step.Run());
        }

        private List<IRunnable> CreateSteps(IEnumerable<Type> stepTypes)
        {
            var steps = new List<IRunnable>();
            foreach (var stepType in stepTypes)
            {
                steps.Add(CreateStep(stepType));
            }

            return steps;
        }

        private IRunnable CreateStep(Type stepType)
            => (IRunnable) Activator.CreateInstance(stepType);
    }

    #endregion

    // Step structure can differ according to system requirements.
    // We may add data context and link steps into pipeline if needed.
    #region Steps

    public abstract class Step : IRunnable
    {
        private readonly string _stepName;

        protected Step(string name)
        {
            _stepName = name;
        }

        public void Run()
        {
            Console.WriteLine($"{_stepName} in action.");
            Invoke();
        }

        public abstract void Invoke();
    }

    public class Step1 : Step
    {
        public Step1() : base(nameof(Step1))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step1 invoked.");
        }
    }

    public class Step2 : Step
    {
        public Step2() : base(nameof(Step2))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step2 invoked.");
        }
    }

    public class Step3 : Step
    {
        public Step3(string customName) : base(customName)
        {

        }

        public Step3() : this(nameof(Step3))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step3 invoked.");
        }
    }

    public class Step4 : Step
    {
        public Step4() : base(nameof(Step4))
        {
        }

        public override void Invoke()
        {
            // do work
            Console.WriteLine($"Step4 invoked.");
        }
    }

    #endregion

    // Scenarios should be as declarative as possible.
    // Let's say the scenario is just specification of what steps (step Type)
    // and in what order should be executed (List as a non-unique ordered collection).
    #region Scenarios

    public abstract class Scenario
    {
        public abstract List<Type> GetStepTypes();
    }

    public class Scenario1 : Scenario
    {
        public override List<Type> GetStepTypes()
            => new List<Type>
            {
                typeof(Step1),
                typeof(Step2),
                typeof(Step3)
            };
    }

    public class Scenario2 : Scenario
    {
        public override List<Type> GetStepTypes()
            => new List<Type>
            {
                typeof(Step1),
                typeof(Step2),
                typeof(Step4)
            };
    }

    #endregion
}


问:
mysql Failed to read auto-increment value from storage engine
I am having mysql table with one id field as auto-increment .

When I insert values to the table am getting error as

1467 - Failed to read auto-increment value from storage engine

Also the show table status shows me that the field with auto increment  has

18446744073709551615 as Auto_increment value.

What would be the issue can any one help me ....?

答: fixed it very easily. Truncated the table and uploaded the data again and the error disappears. </p>


问:
How to set delay in vbscript
How to set delay in vbscript?

WScript.Sleep(100) does not work on Windows XP, Vista.

答:
As stated in this answer:

```<code>Application.Wait (Now + TimeValue("0:00:01"))
</code>```

will wait for 1 second

Title: How to set delay in vbscript

Body:
As stated in this answer:

Application.Wait (Now + TimeValue("0:00:01"))

will wait for 1 second


答:
Perhaps, we need</p>

```<code>library(dplyr)
library(tidyr)
dataset %>%
    select(-plot) %>%
    pivot_longer(cols = LAI:V5, names_to = 'measurement') %>%
    arrange(measurement)
</code>```

Title: Having trouble separating data using Tidyverse in R

Body:
I have a dataset consisting of 20 plant genotypes with measurements of LAI, V1, V2, V3, V4, V5 being taken at three growth stages (1, 2, 3).

I need to separate the data in R (using the tidyverse package) into columns of genotype, stage, and mesurement (consisting of LAI:V5). The code that I have tried does not work; how could I go about doing this? Here is what I have tried:

#Open packages
library(readr)
library(tidyr)
library(dplyr)

#Dataset:
dataset <- structure(list(plot = c(101, 102, 103, 104, 105, 106, 107, 108,
109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 101,
102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120
), genotype = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20), stage = c(1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), LAI = c(822, 763,
551, 251, 800, 761, 343, 593, 997, 261, 19, 429, 566, 574, 174,
356, 891, 918, 948, 782, 902, 383, 704, 157, 358, 453, 723, 644,
308, 149, 504, 437, 348, 165, 128, 305, 778, 516, 347, 212, 792,
423, 565, 828, 106, 605, 603, 551, 145, 393, 914, 919, 672, 628,
143, 103, 906, 717, 18, 324), V1 = c(52, 556, 222, 534, 953,
346, 635, 84, 592, 444, 34, 340, 343, 188, 554, 397, 315, 643,
376, 101, 663, 42, 360, 645, 718, 883, 266, 225, 674, 797, 726,
259, 829, 701, 601, 206, 325, 963, 292, 985, 954, 828, 839, 541,
301, 312, 187, 59, 563, 577, 961, 239, 147, 203, 421, 690, 542,
412, 812, 19), V2 = c(354, 719, 45, 376, 921, 243, 256, 316,
384, 450, 166, 850, 784, 291, 889, 389, 925, 157, 37, 528, 847,
942, 624, 387, 680, 380, 848, 745, 49, 69, 864, 649, 125, 117,
911, 947, 212, 628, 162, 165, 395, 437, 102, 136, 446, 51, 106,
141, 886, 373, 113, 186, 233, 937, 698, 202, 89, 623, 731, 474
), V3 = c(18, 87, 692, 888, 681, 134, 774, 619, 544, 32, 804,
993, 147, 352, 825, 490, 196, 794, 900, 796, 617, 160, 688, 947,
665, 122, 386, 968, 772, 836, 696, 806, 925, 410, 949, 546, 303,
550, 359, 285, 167, 605, 780, 419, 925, 822, 142, 4, 648, 18,
867, 204, 617, 5, 251, 198, 316, 205, 660, 680), V4 = c(728,
266, 678, 958, 946, 248, 425, 777, 86, 340, 527, 766, 161, 187,
129, 881, 149, 888, 811, 118, 379, 22, 953, 940, 520, 200, 557,
438, 401, 25, 55, 155, 73, 834, 614, 933, 235, 759, 852, 29,
475, 356, 992, 765, 593, 703, 929, 823, 466, 717, 86, 607, 730,
7, 416, 727, 400, 904, 503, 881), V5 = c(550, 785, 954, 852,
718, 295, 208, 2, 36, 185, 726, 540, 476, 994, 720, 532, 401,
525, 504, 868, 414, 878, 808, 550, 740, 9, 936, 570, 477, 516,
561, 648, 686, 906, 387, 621, 461, 323, 829, 948, 964, 853, 943,
805, 349, 254, 979, 784, 246, 444, 71, 883, 345, 973, 546, 120,
310, 347, 732, 308)), class = "data.frame", row.names = c(NA,
-60L))

Code I have tried....

data <- gather(dataset, LAI, V1, V2, V3, V4, V5, -plot)

....provides these results (a sample of the resulting dataset):

plot genotype stage LAI  V1
1    101        1     1  V2 354
2    102        2     1  V2 719
3    103        3     1  V2  45
4    104        4     1  V2 376
5    105        5     1  V2 921
6    106        6     1  V2 243
7    107        7     1  V2 256
8    108        8     1  V2 316
9    109        9     1  V2 384
10   110       10     1  V2 450
11   111       11     1  V2 166
12   112       12     1  V2 850
13   113       13     1  V2 784
14   114       14     1  V2 291

The outcome needs to be like this:

correct_format <- data.frame(genotype = c(1,
                                          2,
                                          3,
                                          4,
                                          5,
                                          6),
                             stage = c(1,
                                       1,
                                       1,
                                       1,
                                       1,
                                       1),
                             measurement = c("LAI",
                                             "LAI",
                                             "LAI",
                                             "LAI",
                                             "LAI",
                                             "LAI"),
                             value = c(822,
                                       763,
                                       551,
                                       251,
                                       800,
                                       761)

Body:
Perhaps, we need

library(dplyr)
library(tidyr)
dataset %>%
    select(-plot) %>%
    pivot_longer(cols = LAI:V5, names_to = 'measurement') %>%
    arrange(measurement)


问:
How to create kubernetes secret as json object and load the same in kubernetes environment as json
I need to pass a JWK as kubernetes environment variable to my app.

I created a file to store my key like so:

```<code>cat deploy/keys/access-signature-public-jwk
{
  algorithm = "RS256"
  jwk = {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"}
}
</code>```

Which is then used to create a kubernetes secret like so:

```<code>kubectl create secret generic intimations-signature-public-secret --from-file=./deploy/keys/access-signature-public-jwk
</code>```

Which is then retrived in the kubernetes environment variable as:

```<code>- name: ACCESS_SIGNATURE_PUBLIC_JWK
  valueFrom:
    secretKeyRef:
      name: intimations-signature-public-secret
      key: access-signature-public-jwk
</code>```

And passed to the application.conf of the application likeso:

```<code>pac4j.lagom.jwt.authenticator {
  signatures = [
    ${ACCESS_SIGNATURE_PUBLIC_JWK}
  ]
}
</code>```

The pac4j library expects the config pac4j.lagom.jwt.authenticator as a json object. But get the following exception when I run this app:

```<code>com.typesafe.config.ConfigException$WrongType: env variables: signatures has type list of STRING rather than list of OBJECT
    at com.typesafe.config.impl.SimpleConfig.getHomogeneousWrappedList(SimpleConfig.java:452)
    at com.typesafe.config.impl.SimpleConfig.getObjectList(SimpleConfig.java:460)
    at com.typesafe.config.impl.SimpleConfig.getConfigList(SimpleConfig.java:465)
    at org.pac4j.lagom.jwt.JwtAuthenticatorHelper.parse(JwtAuthenticatorHelper.java:84)
    at com.codingkapoor.holiday.impl.core.HolidayApplication.jwtClient$lzycompute(HolidayApplication.scala
</code>```

POD Description

```<code>Name:         holiday-deployment-55b86f955d-9klk2
Namespace:    default
Priority:     0
Node:         minikube/192.168.99.103
Start Time:   Thu, 28 May 2020 12:42:50 +0530
Labels:       app=holiday
              pod-template-hash=55b86f955d
Annotations:  <none>
Status:       Running
IP:           172.17.0.5
IPs:
  IP:           172.17.0.5
Controlled By:  ReplicaSet/holiday-deployment-55b86f955d
Containers:
  holiday:
    Container ID:   docker://18443cfedc7fd39440f5fa6f038f36c58cec1660a2974e6432500e8c7d51f5e6
    Image:          codingkapoor/holiday-impl:latest
    Image ID:       docker://sha256:6e0ddcf41e0257755b7e865424671970091d555c4bad88b5d896708ded139eb7
    Port:           8558/TCP
    Host Port:      0/TCP
    State:          Terminated
      Reason:       Error
      Exit Code:    255
      Started:      Thu, 28 May 2020 22:49:24 +0530
      Finished:     Thu, 28 May 2020 22:49:29 +0530
    Last State:     Terminated
      Reason:       Error
      Exit Code:    255
      Started:      Thu, 28 May 2020 22:44:15 +0530
      Finished:     Thu, 28 May 2020 22:44:21 +0530
    Ready:          False
    Restart Count:  55
    Liveness:       http-get http://:management/alive delay=20s timeout=1s period=10s #success=1 #failure=10
    Readiness:      http-get http://:management/ready delay=20s timeout=1s period=10s #success=1 #failure=10
    Environment:
      JAVA_OPTS:                     -Xms256m -Xmx256m -Dconfig.resource=prod-application.conf
      APPLICATION_SECRET:            <set to the key 'secret' in secret 'intimations-application-secret'>  Optional: false
      MYSQL_URL:                     jdbc:mysql://mysql/intimations_holiday_schema
      MYSQL_USERNAME:                <set to the key 'username' in secret 'intimations-mysql-secret'>                                 Optional: false
      MYSQL_PASSWORD:                <set to the key 'password' in secret 'intimations-mysql-secret'>                                 Optional: false
      ACCESS_SIGNATURE_PUBLIC_JWK:   <set to the key 'access-signature-public-jwk' in secret 'intimations-signature-public-secret'>   Optional: false
      REFRESH_SIGNATURE_PUBLIC_JWK:  <set to the key 'refresh-signature-public-jwk' in secret 'intimations-signature-public-secret'>  Optional: false
      REQUIRED_CONTACT_POINT_NR:     1
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-kqmmv (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-kqmmv:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-kqmmv
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason   Age                    From               Message
  ----     ------   ----                   ----               -------
  Normal   Pulled   5m21s (x23 over 100m)  kubelet, minikube  Container image "codingkapoor/holiday-impl:latest" already present on machine
  Warning  BackOff  27s (x466 over 100m)   kubelet, minikube  Back-off restarting failed container
</code>```

I was wondering if there is any way to pass the environment variable as a json object instead of string. Please suggest. TIA.

答:
First, the file access-signature-public-jwk is not a valid JSON file. You should update it as a valid one.

```<code>{
  "algorithm" : "RS256",
  "jwk" : {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"}
}
</code>```

Steps I followed to validate.

```<code>kubectl create secret generic token1 --from-file=jwk.json
</code>```

Mount the secret into the pod.

```<code>env:
  - name: JWK
    valueFrom:
      secretKeyRef:
        name: token
        key: jwk.json
</code>```

exec to the pod and check the env variable JWK

```<code>$ echo $JWK
{ "algorithm" : "RS256", "jwk" : {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"} }
</code>```

Copy the content to a file

```<code>echo $JWK > jwk.json
</code>```

Validate the file

```<code>$ jsonlint-php jwk.json
Valid JSON (jwk.json)
</code>```

If I use the file you are given and followed the same steps. It gives an json validation error. Also, env variables are always strings. You have to convert them into the required types in your code.

```<code>$ echo $JWK
{ algorithm = "RS256" jwk = {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"} }
$ echo $JWK > jwk.json
$ jsonlint-php jwk.json
jwk.json: Parse error on line 1:
{ algorithm = "RS256"
-^
Expected one of: 'STRING', '}'
</code>```

Body:
I need to pass a JWK as kubernetes environment variable to my app.

I created a file to store my key like so:

cat deploy/keys/access-signature-public-jwk
{
  algorithm = "RS256"
  jwk = {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"}
}

Which is then used to create a kubernetes secret like so:

kubectl create secret generic intimations-signature-public-secret --from-file=./deploy/keys/access-signature-public-jwk

Which is then retrived in the kubernetes environment variable as:

- name: ACCESS_SIGNATURE_PUBLIC_JWK
  valueFrom:
    secretKeyRef:
      name: intimations-signature-public-secret
      key: access-signature-public-jwk

And passed to the application.conf of the application likeso:

pac4j.lagom.jwt.authenticator {
  signatures = [
    ${ACCESS_SIGNATURE_PUBLIC_JWK}
  ]
}

The pac4j library expects the config pac4j.lagom.jwt.authenticator as a json object. But get the following exception when I run this app:

com.typesafe.config.ConfigException$WrongType: env variables: signatures has type list of STRING rather than list of OBJECT
    at com.typesafe.config.impl.SimpleConfig.getHomogeneousWrappedList(SimpleConfig.java:452)
    at com.typesafe.config.impl.SimpleConfig.getObjectList(SimpleConfig.java:460)
    at com.typesafe.config.impl.SimpleConfig.getConfigList(SimpleConfig.java:465)
    at org.pac4j.lagom.jwt.JwtAuthenticatorHelper.parse(JwtAuthenticatorHelper.java:84)
    at com.codingkapoor.holiday.impl.core.HolidayApplication.jwtClient$lzycompute(HolidayApplication.scala

POD Description

Name:         holiday-deployment-55b86f955d-9klk2
Namespace:    default
Priority:     0
Node:         minikube/192.168.99.103
Start Time:   Thu, 28 May 2020 12:42:50 +0530
Labels:       app=holiday
              pod-template-hash=55b86f955d
Annotations:  <none>
Status:       Running
IP:           172.17.0.5
IPs:
  IP:           172.17.0.5
Controlled By:  ReplicaSet/holiday-deployment-55b86f955d
Containers:
  holiday:
    Container ID:   docker://18443cfedc7fd39440f5fa6f038f36c58cec1660a2974e6432500e8c7d51f5e6
    Image:          codingkapoor/holiday-impl:latest
    Image ID:       docker://sha256:6e0ddcf41e0257755b7e865424671970091d555c4bad88b5d896708ded139eb7
    Port:           8558/TCP
    Host Port:      0/TCP
    State:          Terminated
      Reason:       Error
      Exit Code:    255
      Started:      Thu, 28 May 2020 22:49:24 +0530
      Finished:     Thu, 28 May 2020 22:49:29 +0530
    Last State:     Terminated
      Reason:       Error
      Exit Code:    255
      Started:      Thu, 28 May 2020 22:44:15 +0530
      Finished:     Thu, 28 May 2020 22:44:21 +0530
    Ready:          False
    Restart Count:  55
    Liveness:       http-get http://:management/alive delay=20s timeout=1s period=10s #success=1 #failure=10
    Readiness:      http-get http://:management/ready delay=20s timeout=1s period=10s #success=1 #failure=10
    Environment:
      JAVA_OPTS:                     -Xms256m -Xmx256m -Dconfig.resource=prod-application.conf
      APPLICATION_SECRET:            <set to the key 'secret' in secret 'intimations-application-secret'>  Optional: false
      MYSQL_URL:                     jdbc:mysql://mysql/intimations_holiday_schema
      MYSQL_USERNAME:                <set to the key 'username' in secret 'intimations-mysql-secret'>                                 Optional: false
      MYSQL_PASSWORD:                <set to the key 'password' in secret 'intimations-mysql-secret'>                                 Optional: false
      ACCESS_SIGNATURE_PUBLIC_JWK:   <set to the key 'access-signature-public-jwk' in secret 'intimations-signature-public-secret'>   Optional: false
      REFRESH_SIGNATURE_PUBLIC_JWK:  <set to the key 'refresh-signature-public-jwk' in secret 'intimations-signature-public-secret'>  Optional: false
      REQUIRED_CONTACT_POINT_NR:     1
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-kqmmv (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-kqmmv:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-kqmmv
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason   Age                    From               Message
  ----     ------   ----                   ----               -------
  Normal   Pulled   5m21s (x23 over 100m)  kubelet, minikube  Container image "codingkapoor/holiday-impl:latest" already present on machine
  Warning  BackOff  27s (x466 over 100m)   kubelet, minikube  Back-off restarting failed container

I was wondering if there is any way to pass the environment variable as a json object instead of string. Please suggest. TIA.

Body:
First, the file access-signature-public-jwk is not a valid JSON file. You should update it as a valid one.

{
  "algorithm" : "RS256",
  "jwk" : {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"}
}

Steps I followed to validate.

kubectl create secret generic token1 --from-file=jwk.json

Mount the secret into the pod.

env:
  - name: JWK
    valueFrom:
      secretKeyRef:
        name: token
        key: jwk.json

exec to the pod and check the env variable JWK

$ echo $JWK
{ "algorithm" : "RS256", "jwk" : {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"} }

Copy the content to a file

echo $JWK > jwk.json

Validate the file

$ jsonlint-php jwk.json
Valid JSON (jwk.json)

If I use the file you are given and followed the same steps. It gives an json validation error. Also, env variables are always strings. You have to convert them into the required types in your code.

$ echo $JWK
{ algorithm = "RS256" jwk = {"kty":"RSA","e":"AQAB","n":"ghhDZxuUo6TaSvAlD23mLP6n_T9pQuJsFY4JWdBYTjtcp_8Q3QeR477jou4cScPGczWw2JMGnx-Ao_b7ewagSl7VHpECBFHgcnlAgs5j6jfnd3M9ADKD2Yc756iXlIMT9xKDblIcXQQYlXalqxGvnLRLv1KAgVVVpVWzQd6Iz8WdTnexVrh7L9N87QQbOWcAVWGHCWCLCBsVE7JbC-XDt9h9P1g1sMqMV-qp7HjSXUKWuF2NwOnL2VeFSED7gdefs2Za1UYqhfwxdGl7aaPDXhjib0cfg4NvbcXMzxDEVkeJqhdDfD82wHOs4qFvnFMVxq9n6VVExSxsJq8gBJ7Z2AmfoXpmZC1L1ZwULB2KKpFXDCzgBELPLrfyIf8mNnk2nuuLT-aaMsqy2uB-ea3du4lyWo9MLk6x-L5g-n1oADKFKBY9aP2QQwruCG92XSd7jA9yLtbgr9OGVCYezxIxFp4vW6KcmPwJQjozWtwkZjeo4hv-zhRac73WDox2hDkif7WPTuEvC21fRy3GvyPIUPKPJA8pJjb2TXT7DXknR97CTnOWicuh3HMoRlVIwUzM5SVLGSXex0VjHZKgLYwQYukg5O2rab_4NxpD6LqLHx1bbPssC7BedCIfWX1Vcae40tlfvJAM09MiwQPZjWRahW_fK_9X5F5_rtUhCznm32M"} }
$ echo $JWK > jwk.json
$ jsonlint-php jwk.json
jwk.json: Parse error on line 1:
{ algorithm = "RS256"
-^
Expected one of: 'STRING', '}'