问:
jq: filter nested array objects
Here my documents:

[
  {
    "id": "3e67b455-8cdb-4bc0-a5e1-f90253870fc9",
    "identifier": [
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.91-INVENTAT"
        },
        "value": {
          "value": "04374"
        }
      },
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.2-INVENTAT"
        },
        "value": {
          "value": "INFP3"
        }
      },
      {
        "system": {
          "value": "urn:oid:INVENTAT"
        },
        "value": {
          "value": "CBOU035"
        }
      }
    ]
  },
  {
    "id": "0f22e5ff-70bc-457f-bdaf-7afe86d478de",
    "identifier": [
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.91-INVENTAT"
        },
        "value": {
          "value": "04376"
        }
      },
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.2-INVENTAT"
        },
        "value": {
          "value": "INF07"
        }
      },
      {
        "system": {
          "value": "urn:oid:INVENTAT"
        },
        "value": {
          "value": "S527918"
        }
      }
    ]
  },
  {
    "id": "a1ea574c-438b-443c-ad87-d31d09d581f0",
    "identifier": [
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.91-INVENTAT"
        },
        "value": {
          "value": "08096"
        }
      },
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.2-INVENTAT"
        },
        "value": {
          "value": "INF04"
        }
      },
      {
        "system": {
          "value": "urn:oid:INVENTAT"
        },
        "value": {
          "value": "5635132"
        }
      }
    ]
  }
]
```
<p>I need to filter <code>.identifier</code> where <code>system.value="urn:oid:2.16.724.4.9.20.91-INVENTAT"</code>  or <code>system.value="urn:oid:2.16.724.4.9.20.2-INVENTAT"</code> and pick <code>.value.value</code>.</p>
<p>Desired output:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "id": "3e67b455-8cdb-4bc0-a5e1-f90253870fc9",
    "oid1": "04374",
    "oid2": "INFP3"
  },
  {
    "id": "0f22e5ff-70bc-457f-bdaf-7afe86d478de",
    "oid1": "04376",
    "oid2": "INF07"
  },
  {
    "id": "a1ea574c-438b-443c-ad87-d31d09d581f0",
    "oid1": "08096",
    "oid2": "INF04"
  }
]
</code>```

I've tried:

```<code>map(
    {
        id,
        oid1: select(.identifier?[]?.system.value == "urn:oid:2.16.724.4.9.20.91-INVENTAT") | .identifier[].value.value,
        oid2: select(.identifier?[]?.system.value == "urn:oid:2.16.724.4.9.20.2-INVENTAT") | .identifier[].value.value
    }
)
</code>```

But output is not what I need: you can find it on this jqplay.

Any ideas?

答:
This uses IN to check for your query strings, and with_entries on an array to generate the indeces for the oid keys.

jq '
  map({id} + (.identifier | map(select(IN(.system.value;
    "urn:oid:2.16.724.4.9.20.91-INVENTAT",
    "urn:oid:2.16.724.4.9.20.2-INVENTAT"
  )).value.value) | with_entries(.key |= "oid\(. + 1)")))
'
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "id": "3e67b455-8cdb-4bc0-a5e1-f90253870fc9",
    "oid1": "04374",
    "oid2": "INFP3"
  },
  {
    "id": "0f22e5ff-70bc-457f-bdaf-7afe86d478de",
    "oid1": "04376",
    "oid2": "INF07"
  },
  {
    "id": "a1ea574c-438b-443c-ad87-d31d09d581f0",
    "oid1": "08096",
    "oid2": "INF04"
  }
]
</code>```

Demo

Title: jq: filter nested array objects

Body:
Here my documents:

[
  {
    "id": "3e67b455-8cdb-4bc0-a5e1-f90253870fc9",
    "identifier": [
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.91-INVENTAT"
        },
        "value": {
          "value": "04374"
        }
      },
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.2-INVENTAT"
        },
        "value": {
          "value": "INFP3"
        }
      },
      {
        "system": {
          "value": "urn:oid:INVENTAT"
        },
        "value": {
          "value": "CBOU035"
        }
      }
    ]
  },
  {
    "id": "0f22e5ff-70bc-457f-bdaf-7afe86d478de",
    "identifier": [
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.91-INVENTAT"
        },
        "value": {
          "value": "04376"
        }
      },
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.2-INVENTAT"
        },
        "value": {
          "value": "INF07"
        }
      },
      {
        "system": {
          "value": "urn:oid:INVENTAT"
        },
        "value": {
          "value": "S527918"
        }
      }
    ]
  },
  {
    "id": "a1ea574c-438b-443c-ad87-d31d09d581f0",
    "identifier": [
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.91-INVENTAT"
        },
        "value": {
          "value": "08096"
        }
      },
      {
        "system": {
          "value": "urn:oid:2.16.724.4.9.20.2-INVENTAT"
        },
        "value": {
          "value": "INF04"
        }
      },
      {
        "system": {
          "value": "urn:oid:INVENTAT"
        },
        "value": {
          "value": "5635132"
        }
      }
    ]
  }
]

I need to filter .identifier where system.value="urn:oid:2.16.724.4.9.20.91-INVENTAT"  or system.value="urn:oid:2.16.724.4.9.20.2-INVENTAT" and pick .value.value.

Desired output:

[
  {
    "id": "3e67b455-8cdb-4bc0-a5e1-f90253870fc9",
    "oid1": "04374",
    "oid2": "INFP3"
  },
  {
    "id": "0f22e5ff-70bc-457f-bdaf-7afe86d478de",
    "oid1": "04376",
    "oid2": "INF07"
  },
  {
    "id": "a1ea574c-438b-443c-ad87-d31d09d581f0",
    "oid1": "08096",
    "oid2": "INF04"
  }
]

I've tried:

map(
    {
        id,
        oid1: select(.identifier?[]?.system.value == "urn:oid:2.16.724.4.9.20.91-INVENTAT") | .identifier[].value.value,
        oid2: select(.identifier?[]?.system.value == "urn:oid:2.16.724.4.9.20.2-INVENTAT") | .identifier[].value.value
    }
)

But output is not what I need: you can find it on this jqplay.

Any ideas?

Body:
This uses IN to check for your query strings, and with_entries on an array to generate the indeces for the oid keys.

jq '
  map({id} + (.identifier | map(select(IN(.system.value;
    "urn:oid:2.16.724.4.9.20.91-INVENTAT",
    "urn:oid:2.16.724.4.9.20.2-INVENTAT"
  )).value.value) | with_entries(.key |= "oid\(. + 1)")))
'

[
  {
    "id": "3e67b455-8cdb-4bc0-a5e1-f90253870fc9",
    "oid1": "04374",
    "oid2": "INFP3"
  },
  {
    "id": "0f22e5ff-70bc-457f-bdaf-7afe86d478de",
    "oid1": "04376",
    "oid2": "INF07"
  },
  {
    "id": "a1ea574c-438b-443c-ad87-d31d09d581f0",
    "oid1": "08096",
    "oid2": "INF04"
  }
]

Demo


来源: stackexchange

问:
Get and keep only original target of mousedown event?
I want to get and keep only the original target element of a mousedown event -- but as the user holds the mouse down, the event.target changes depending on what's under the pointer.

There is a property event.originalTarget which does exactly what I want, but it's only supported by Firefox (reference: https://developer.mozilla.org/en-US/docs/Web/API/Event/originalTarget ).

How can I replicate this behavior using standard event.target?

答:
Figured it out: you need to create flags outside the event listener.

```<code>let el = false
let mousedown = false;

document.addEventListener('mousedown', ev => {
        if (!mousedown) {
            el = ev.target;
            mousedown = true;
        }
    });

document.addEventListener('mouseup', ev => {
        mousedown = false;
        el = false;
    });

</code>```

So el will be set as the original target for the duration of the mousedown, but on mouseup, it's reset back to nothing.

ContentLicense: CC BY-SA 4.0

Body:
Figured it out: you need to create flags outside the event listener.

let el = false
let mousedown = false;

document.addEventListener('mousedown', ev => {
        if (!mousedown) {
            el = ev.target;
            mousedown = true;
        }
    });

document.addEventListener('mouseup', ev => {
        mousedown = false;
        el = false;
    });

So el will be set as the original target for the duration of the mousedown, but on mouseup, it's reset back to nothing.


问:
layout gets chopped off in a lower resolution screen
In my android app, I have a RelativeLayout with listview and 4 buttons in the bottom. Selecting any item in a listview will make four hidden buttons visible. I have followed the best practices from the http://developer.android.com/guide/practices/screens_support.html. It works fine in the emulator for WVGA800 and in the actual device. I was in a process of testing my app on different screen size. Looks like for QVGA(240x320), the buttons in the bottom gets chopped off.
Here is the xml

```<code><?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout android:id="@+id/listViewrelativeLayout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"  >
  <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/info_tv_id" android:textSize="10sp" android:layout_marginLeft="10dip"></TextView>
  <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:choiceMode="singleChoice" android:layout_marginTop="25dip" android:layout_below="@id/info_tv_id">
  </ListView>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="bottom" android:layout_alignParentBottom="true" android:id="@+id/relativekeybuttons" android:layout_below="@+id/listView1" android:visibility="gone">"
               <Button android:id="@+id/setasdefault" android:text="@string/default_btn_text" android:layout_marginTop="10dip"
                android:layout_height="50sp" android:layout_width="75sp">
               </Button>
               <Button android:id="@+id/changepassphrase" android:layout_marginTop="10dip" android:text="@string/passphrase_btn_text" android:layout_width="75sp" android:layout_height="50sp"
                android:layout_toRightOf="@+id/setasdefault"></Button>
               <Button android:id="@+id/rename" android:text="@string/rename_btn_text" android:layout_marginTop="10dip" android:layout_width="75sp"  android:layout_height="50sp"
                android:layout_toRightOf="@+id/changepassphrase"></Button>
               <Button android:id="@+id/delete" android:layout_width="75sp" android:layout_marginTop="10dip" android:layout_height="50sp" android:text="@string/delete_btn_text"
               android:layout_toRightOf="@+id/rename"></Button>
  </RelativeLayout>
</RelativeLayout>
</code>```

Also, I want the listview to occupy a fixed length in the layout. Eg: atleast 70% of the screen, so that the length of the listview is not dependent on the items in the listview.

Thanks in advance

答: Change all units in the xml to dp. Then adjust the controls. Else you'll have to use scrollview as the parent.</p>

ContentLicense: CC BY-SA 3.0

Body:
In my android app, I have a RelativeLayout with listview and 4 buttons in the bottom. Selecting any item in a listview will make four hidden buttons visible. I have followed the best practices from the http://developer.android.com/guide/practices/screens_support.html. It works fine in the emulator for WVGA800 and in the actual device. I was in a process of testing my app on different screen size. Looks like for QVGA(240x320), the buttons in the bottom gets chopped off.
Here is the xml

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout android:id="@+id/listViewrelativeLayout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"  >
  <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/info_tv_id" android:textSize="10sp" android:layout_marginLeft="10dip"></TextView>
  <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:choiceMode="singleChoice" android:layout_marginTop="25dip" android:layout_below="@id/info_tv_id">
  </ListView>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="bottom" android:layout_alignParentBottom="true" android:id="@+id/relativekeybuttons" android:layout_below="@+id/listView1" android:visibility="gone">"
               <Button android:id="@+id/setasdefault" android:text="@string/default_btn_text" android:layout_marginTop="10dip"
                android:layout_height="50sp" android:layout_width="75sp">
               </Button>
               <Button android:id="@+id/changepassphrase" android:layout_marginTop="10dip" android:text="@string/passphrase_btn_text" android:layout_width="75sp" android:layout_height="50sp"
                android:layout_toRightOf="@+id/setasdefault"></Button>
               <Button android:id="@+id/rename" android:text="@string/rename_btn_text" android:layout_marginTop="10dip" android:layout_width="75sp"  android:layout_height="50sp"
                android:layout_toRightOf="@+id/changepassphrase"></Button>
               <Button android:id="@+id/delete" android:layout_width="75sp" android:layout_marginTop="10dip" android:layout_height="50sp" android:text="@string/delete_btn_text"
               android:layout_toRightOf="@+id/rename"></Button>
  </RelativeLayout>
</RelativeLayout>

Also, I want the listview to occupy a fixed length in the layout. Eg: atleast 70% of the screen, so that the length of the listview is not dependent on the items in the listview.

Thanks in advance


问:
Flutter: AppBar background image
Is it possible to add a background image to the Scaffold's AppBar? I know about sliver but when you scrolldown the image gets hidden and the AppBar changes color right? So I want to know if this is possible and if not, are there any existing workarounds? Thanks!</p>

答:
full example

```<code>Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text('How to Flutter', style: TextStyle(
            color: Colors.white,
            fontSize: 28
        ),) ,
        elevation: 0,
        backgroundColor: Colors.transparent,
      ),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/bg.jpg'),
            fit: BoxFit.fill
          )
        ),
      ),
    )
</code>```

Title: Flutter: AppBar background image

Body:
full example

Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text('How to Flutter', style: TextStyle(
            color: Colors.white,
            fontSize: 28
        ),) ,
        elevation: 0,
        backgroundColor: Colors.transparent,
      ),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/bg.jpg'),
            fit: BoxFit.fill
          )
        ),
      ),
    )


问:
can we do Denisty plotting with timestamp in Python?
My question is somewhat similar to this-: how to put label in dataframe in Density plotting in matplotlib

because of this I am not putting a code because it is almost same.

but Here I want to do as you can see in the picture.

let me interpret further more.
first this is the data we can take.

```<code>a_str = '''
timestamp      count
2021-08-16     20
2021-08-17     60
2021-08-18     35
2021-08-19      1
2021-08-20      0
2021-08-21      1
2021-08-22     50
2021-08-23     36
2021-08-24     68
2021-08-25    125
2021-08-26     54'''

a_str1 = '''
timestamp      count
2021-07-16     20
2021-07-17     60
2021-07-18     35
2021-07-19      1
2021-07-20      0
2021-07-21      1
2021-07-22     50
2021-07-23     36
2021-07-24     68
2021-07-25    125
2021-07-26     54'''

a_str2 = '''
timestamp      count
2021-06-16     20
2021-06-17     60
2021-06-18     35
2021-06-19      1
2021-06-20      0
2021-06-21      1
2021-06-22     50
2021-06-23     36
2021-06-24     68
2021-06-25    125
2021-06-26     54'''

</code>```

As we know that Density graph gives info about (density of each values (X axis-: values, Y axis-: actual value))
like this one

what I want

(Plotting does not has to be what i posted above, it is just for the idea of What i want to do)

On the X there are actual value of count

want to plot "density" of it

y axis is a month

before all, is it even possible like this? because i am using density plot so it might not be possible with that.

Thanks in advance.

答:
The following code draws kde curves at y-values 0,1,2,...  Depending on your concrete situation, you might want to fine-tune some of the constants.

from matplotlib import pyplot as plt
from matplotlib.colors import to_rgb
import pandas as pd
import numpy as np
from scipy.stats import gaussian_kde

a1 = pd.DataFrame({'timestamp': pd.date_range('20210816', periods=11),
                   'count': np.random.randint(10, 21, 11)})
a2 = pd.DataFrame({'timestamp': pd.date_range('20210716', periods=11),
                   'count': np.random.randint(10, 21, 11)})
a3 = pd.DataFrame({'timestamp': pd.date_range('20210616', periods=11),
                   'count': np.random.randint(10, 21, 11)})
month_counts = [df['count'].values for df in [a1, a2, a3]]
month_names = ['August', 'July', 'June']

max_count = max([count_i.max() for count_i in month_counts])
min_count = min([count_i.min() for count_i in month_counts])
xs = np.linspace(min_count - 3, max_count + 3, 200)
month_kde = [gaussian_kde(count_i, bw_method=0.2) for count_i in month_counts]
max_kde = max([kde_i(xs).max() for kde_i in month_kde])
overlap_factor = 1.9
whiten_factor = 0.5

fig, ax = plt.subplots(figsize=(12, 8))
for index, color in zip(range(len(month_names) - 1, -1, -1), np.tile(plt.cm.Set2.colors, (3, 1))):
    kde = month_kde[index](xs) / max_kde * overlap_factor
    ax.plot(xs, index + kde, lw=2, color=color, zorder=50 - index)
    whitened = np.array(to_rgb(color)) * (1 - whiten_factor) + whiten_factor
    ax.fill_between(xs, index, index + kde, color=whitened, alpha=0.8, zorder=50 - index)
ax.set_xlim(xs[0], xs[-1])
ax.set_xlabel('Distribution of Counts')
ax.set_yticks(np.arange(len(month_names)))
ax.set_yticklabels(month_names)
for spine in ('top', 'left', 'right'):
    ax.spines[spine].set(visible=False)
plt.tight_layout()
plt.show()
```
<p><img src="https://i.stack.imgur.com/7JUgD.png" alt="kde curves for multiple months" /></p>
<p>Here is a variation using the <code>magma</code> color map as gradient:</p>
<pre class="lang-py prettyprint-override"><code>month_names = ['January', 'February', 'March', 'April', 'May', 'June',
               'July', 'August', 'September', 'October', 'November', 'December']
month_counts = [np.random.randint(15 - abs(k - 6), 30 - abs(k - 6), 30) for k in range(len(month_names))]

max_count = max([count_i.max() for count_i in month_counts])
min_count = min([count_i.min() for count_i in month_counts])
xs = np.linspace(min_count - 3, max_count + 3, 200)
month_kde = [gaussian_kde(count_i, bw_method=0.2) for count_i in month_counts]
max_kde = max([kde_i(xs).max() for kde_i in month_kde])
overlap_factor = 1.9

fig, ax = plt.subplots(figsize=(12, 8))
for index in range(len(month_names)):
    kde = month_kde[::-1][index](xs) / max_kde * overlap_factor
    ax.plot(xs, index + kde, lw=2, color='black', zorder=50 - 2 * index + 1)
    fill_poly = ax.fill_between(xs, index, index + kde, color='none', alpha=0.8)

    verts = np.vstack([p.vertices for p in fill_poly.get_paths()])
    gradient = ax.imshow(np.linspace(0, 1, 256).reshape(1, -1), cmap='magma', aspect='auto', zorder=50 - 2 * index,
                         extent=[verts[:, 0].min(), verts[:, 0].max(), verts[:, 1].min(), verts[:, 1].max()])
    gradient.set_clip_path(fill_poly.get_paths()[0], transform=plt.gca().transData)

ax.set_xlim(xs[0], xs[-1])
ax.set_ylim(ymin=-0.2)

ax.set_xlabel('Distribution of Counts')
ax.set_yticks(np.arange(len(month_names)))
ax.set_yticklabels(month_names[::-1])
for spine in ('top', 'left', 'right'):
    ax.spines[spine].set(visible=False)
plt.tight_layout()
plt.show()
</code>```

Body:
My question is somewhat similar to this-: how to put label in dataframe in Density plotting in matplotlib

because of this I am not putting a code because it is almost same.

but Here I want to do as you can see in the picture.

let me interpret further more.
first this is the data we can take.

a_str = '''
timestamp      count
2021-08-16     20
2021-08-17     60
2021-08-18     35
2021-08-19      1
2021-08-20      0
2021-08-21      1
2021-08-22     50
2021-08-23     36
2021-08-24     68
2021-08-25    125
2021-08-26     54'''

a_str1 = '''
timestamp      count
2021-07-16     20
2021-07-17     60
2021-07-18     35
2021-07-19      1
2021-07-20      0
2021-07-21      1
2021-07-22     50
2021-07-23     36
2021-07-24     68
2021-07-25    125
2021-07-26     54'''

a_str2 = '''
timestamp      count
2021-06-16     20
2021-06-17     60
2021-06-18     35
2021-06-19      1
2021-06-20      0
2021-06-21      1
2021-06-22     50
2021-06-23     36
2021-06-24     68
2021-06-25    125
2021-06-26     54'''

As we know that Density graph gives info about (density of each values (X axis-: values, Y axis-: actual value))
like this one

what I want

(Plotting does not has to be what i posted above, it is just for the idea of What i want to do)

On the X there are actual value of count

want to plot "density" of it

y axis is a month

before all, is it even possible like this? because i am using density plot so it might not be possible with that.

Thanks in advance.

Body:
The following code draws kde curves at y-values 0,1,2,...  Depending on your concrete situation, you might want to fine-tune some of the constants.

from matplotlib import pyplot as plt
from matplotlib.colors import to_rgb
import pandas as pd
import numpy as np
from scipy.stats import gaussian_kde

a1 = pd.DataFrame({'timestamp': pd.date_range('20210816', periods=11),
                   'count': np.random.randint(10, 21, 11)})
a2 = pd.DataFrame({'timestamp': pd.date_range('20210716', periods=11),
                   'count': np.random.randint(10, 21, 11)})
a3 = pd.DataFrame({'timestamp': pd.date_range('20210616', periods=11),
                   'count': np.random.randint(10, 21, 11)})
month_counts = [df['count'].values for df in [a1, a2, a3]]
month_names = ['August', 'July', 'June']

max_count = max([count_i.max() for count_i in month_counts])
min_count = min([count_i.min() for count_i in month_counts])
xs = np.linspace(min_count - 3, max_count + 3, 200)
month_kde = [gaussian_kde(count_i, bw_method=0.2) for count_i in month_counts]
max_kde = max([kde_i(xs).max() for kde_i in month_kde])
overlap_factor = 1.9
whiten_factor = 0.5

fig, ax = plt.subplots(figsize=(12, 8))
for index, color in zip(range(len(month_names) - 1, -1, -1), np.tile(plt.cm.Set2.colors, (3, 1))):
    kde = month_kde[index](xs) / max_kde * overlap_factor
    ax.plot(xs, index + kde, lw=2, color=color, zorder=50 - index)
    whitened = np.array(to_rgb(color)) * (1 - whiten_factor) + whiten_factor
    ax.fill_between(xs, index, index + kde, color=whitened, alpha=0.8, zorder=50 - index)
ax.set_xlim(xs[0], xs[-1])
ax.set_xlabel('Distribution of Counts')
ax.set_yticks(np.arange(len(month_names)))
ax.set_yticklabels(month_names)
for spine in ('top', 'left', 'right'):
    ax.spines[spine].set(visible=False)
plt.tight_layout()
plt.show()

Here is a variation using the magma color map as gradient:

month_names = ['January', 'February', 'March', 'April', 'May', 'June',
               'July', 'August', 'September', 'October', 'November', 'December']
month_counts = [np.random.randint(15 - abs(k - 6), 30 - abs(k - 6), 30) for k in range(len(month_names))]

max_count = max([count_i.max() for count_i in month_counts])
min_count = min([count_i.min() for count_i in month_counts])
xs = np.linspace(min_count - 3, max_count + 3, 200)
month_kde = [gaussian_kde(count_i, bw_method=0.2) for count_i in month_counts]
max_kde = max([kde_i(xs).max() for kde_i in month_kde])
overlap_factor = 1.9

fig, ax = plt.subplots(figsize=(12, 8))
for index in range(len(month_names)):
    kde = month_kde[::-1][index](xs) / max_kde * overlap_factor
    ax.plot(xs, index + kde, lw=2, color='black', zorder=50 - 2 * index + 1)
    fill_poly = ax.fill_between(xs, index, index + kde, color='none', alpha=0.8)

    verts = np.vstack([p.vertices for p in fill_poly.get_paths()])
    gradient = ax.imshow(np.linspace(0, 1, 256).reshape(1, -1), cmap='magma', aspect='auto', zorder=50 - 2 * index,
                         extent=[verts[:, 0].min(), verts[:, 0].max(), verts[:, 1].min(), verts[:, 1].max()])
    gradient.set_clip_path(fill_poly.get_paths()[0], transform=plt.gca().transData)

ax.set_xlim(xs[0], xs[-1])
ax.set_ylim(ymin=-0.2)

ax.set_xlabel('Distribution of Counts')
ax.set_yticks(np.arange(len(month_names)))
ax.set_yticklabels(month_names[::-1])
for spine in ('top', 'left', 'right'):
    ax.spines[spine].set(visible=False)
plt.tight_layout()
plt.show()


问:
Can we call onClick event of a button inside a fragment layout in MainActivity, instead of in that class of fragment?
I have created an onClick event of a button inside a fragment layout, and write it in main activity class. It works !. However, I tried create same onCLick event of the button in the fragment layout in the fragment class. It also works !

My question is what difference if we write an event and call it in main activity (button is inside of fragment layout) VS write it and call it in fragment class where the button belong to. Both are same ? Any pros and cons ?

答:
The main difference is where you call the 'onClick()'.

If you are calling the onclick after replacing the fragment, then it will work as expected.

But, If you are calling it before initializing fragment, then the app will crash.
So never ever do that.


问:
ansible + how to run ansible interactive like bash script that ask questions
we want to create ansible code that ask interactive questions like the bash script

for now we have the following bash script, with diff 43 Questions , that finally create ini file according to our Questions

```<code>bash /home/gentwo.bash

how many machines?23
how many datanode services?
IP address for first machine - andnenda01?

.
.
.

---
</code>```

as we know we cant do the same with ansible as the following:

```<code>- hosts: 17.12.22.56
  gather_facts: yes
  vars:
    app_name: interactive process
    ansible_user: root
    ansible_password: XXXXXXXXXXX

  tasks:
    - name: interactive process
      script: "/home/gentwo.bash"
      register: results
</code>```

so what is the equivalent approach with ansible?

答:
You can use prompts for interactive input

e.g. from docs:

---
- hosts: all
  vars_prompt:

    - name: username
      prompt: What is your username?
      private: no

    - name: password
      prompt: What is your password?

  tasks:

    - name: Print a message
      ansible.builtin.debug:
        msg: 'Logging in as {{ username }}'

```

Ansible Doc: https://docs.ansible.com/ansible/latest/user_guide/playbooks_prompts.html

Body:
we want to create ansible code that ask interactive questions like the bash script

for now we have the following bash script, with diff 43 Questions , that finally create ini file according to our Questions

bash /home/gentwo.bash

how many machines?23
how many datanode services?
IP address for first machine - andnenda01?

.
.
.

---

as we know we cant do the same with ansible as the following:

- hosts: 17.12.22.56
  gather_facts: yes
  vars:
    app_name: interactive process
    ansible_user: root
    ansible_password: XXXXXXXXXXX

  tasks:
    - name: interactive process
      script: "/home/gentwo.bash"
      register: results

so what is the equivalent approach with ansible?

Body:
You can use prompts for interactive input

e.g. from docs:

---
- hosts: all
  vars_prompt:

    - name: username
      prompt: What is your username?
      private: no

    - name: password
      prompt: What is your password?

  tasks:

    - name: Print a message
      ansible.builtin.debug:
        msg: 'Logging in as {{ username }}'

Ansible Doc: https://docs.ansible.com/ansible/latest/user_guide/playbooks_prompts.html


问:
Loading files from .npz with Keras custom data generator
I'm training a CNN using a Keras data generator (tf.keras.utils.Sequence) on NumPy arrays saved locally. For my baseline on a small dataset, loading the arrays like so works fine:

```<code>X_data = np.load("X_data.npz")
y_data = np.load("y_data.npz")

X = X_data["arr_0"]
y = y_data["arr_0"]

class Gen_Data(tf.keras.utils.Sequence):

    def __init__(self,batch_size,t_size,X_data,y_data):

        self.batch_size = batch_size
        self.t_size = t_size
        self.X_data = X_data
        self.y_data = y_data
        self.n_batches = len(self.X_data)//self.batch_size
        self.batch_idx = np.array_split(range(len(self.X_data)), self.n_batches)

    def __len__(self):

        return self.n_batches

    def __getitem__(self,idx):

        batch_X = self.X_data[self.batch_idx[idx]]
        batch_y = self.y_data[self.batch_idx[idx]]
        return batch_X, batch_y
</code>```

The problem is that this requires me to load the whole dataset into memory, right? Which might be a problem when I use my actual dataset which is much much larger. When the arrays are saved as .npz files using np.savez_compressed, I have to load the whole thing to access any of the data.

I would therefore like to know if there is a way to load batches of arrays from X.npz without loading it in its entirety? This way I can build this into the __getitem__ part of the generator.

I would also be interested in hearing any alternative strategies for batch-loading large arrays into Keras/TensorFlow. Thanks for any advice!

答:
depending on the size of the dataset, you could break it down into smaller files on a remote server with more memory available, or use numpy memmap : https://numpy.org/doc/stable/reference/generated/numpy.memmap.html

memmap does not load the file into RAM, but references the file in storage.

You must specify the shape or else it will be flattened

This is extremely slow to do calculations with as it is not in memory, batches are recommended with in memory data.

Example:

```<code>fp = np.memmap("ReallyBigArray.npy", dtype='float32', mode='r', shape = (cols,rows))

# load a slice of the array into memory for processing
fpInMemory = fp[:1000]
</code>```

Body:
I'm training a CNN using a Keras data generator (tf.keras.utils.Sequence) on NumPy arrays saved locally. For my baseline on a small dataset, loading the arrays like so works fine:

X_data = np.load("X_data.npz")
y_data = np.load("y_data.npz")

X = X_data["arr_0"]
y = y_data["arr_0"]

class Gen_Data(tf.keras.utils.Sequence):

    def __init__(self,batch_size,t_size,X_data,y_data):

        self.batch_size = batch_size
        self.t_size = t_size
        self.X_data = X_data
        self.y_data = y_data
        self.n_batches = len(self.X_data)//self.batch_size
        self.batch_idx = np.array_split(range(len(self.X_data)), self.n_batches)

    def __len__(self):

        return self.n_batches

    def __getitem__(self,idx):

        batch_X = self.X_data[self.batch_idx[idx]]
        batch_y = self.y_data[self.batch_idx[idx]]
        return batch_X, batch_y

The problem is that this requires me to load the whole dataset into memory, right? Which might be a problem when I use my actual dataset which is much much larger. When the arrays are saved as .npz files using np.savez_compressed, I have to load the whole thing to access any of the data.

I would therefore like to know if there is a way to load batches of arrays from X.npz without loading it in its entirety? This way I can build this into the __getitem__ part of the generator.

I would also be interested in hearing any alternative strategies for batch-loading large arrays into Keras/TensorFlow. Thanks for any advice!

Body:
depending on the size of the dataset, you could break it down into smaller files on a remote server with more memory available, or use numpy memmap : https://numpy.org/doc/stable/reference/generated/numpy.memmap.html

memmap does not load the file into RAM, but references the file in storage.

You must specify the shape or else it will be flattened

This is extremely slow to do calculations with as it is not in memory, batches are recommended with in memory data.

Example:

fp = np.memmap("ReallyBigArray.npy", dtype='float32', mode='r', shape = (cols,rows))

# load a slice of the array into memory for processing
fpInMemory = fp[:1000]


问:
A factor in Multiple Regression model shows NA
I want to make multiple regression analysis using three factors (Location, Trainer, Savings), but the factor Location shows NA.
data:

```<code>Location <- c(rep("Kono",4),rep("Kailahun",4),rep("Bo",4),rep("Freetown",4))
profit <- c(100,800,900,550,4500,3000,2000,1000,10,350,150,300,800,500,1500,1250)
savings <- c(80,60,440,900,2000,5500,100,200,900,1500,2000,3000,5000,9000,400,1200)
Month <- c(rep("May",3),rep("June",4),rep("July",3),rep("August",3),rep("September",3))
data$Location <- dummy(data$Location)
data$Month <- dummy(data$Month)
data <- data.frame(Location,profit,savings,Month)

summary(lm(Profit~savings+Month+ocation, data=d))

LocationLocationBo                             NA         NA      NA       NA
LocationLocationFreetown                       NA         NA      NA       NA
LocationLocationKailahun                       NA         NA      NA       NA
LocationLocationKono                           NA         NA      NA       NA
</code>```

it is categorical variable and has 4 levels, and I am not sure if I am handling it correctly. Can someone clarify what is wrong with it?

答:
If I understand correctly your predictors are all categorical, so if you want to include them in a linear regression model, you should first bild dummy variables (coded 0-1), because otherwise the regression will mistake your data for metric. Here is an article that explains it very well: https://www.statology.org/dummy-variables-in-r/

If the dependent variable (Profit) is categorical too a logistic regression model might be the better choice.

EDIT: After example data was added

Method 1: Basic without additional packages

This method is useful and easy in case you only have few dummy variables.

```<code>Location <- c(rep("Kono",4),rep("Kailahun",4),rep("Bo",4),rep("Freetown",4))
profit <- c(100,800,900,550,4500,3000,2000,1000,10,350,150,300,800,500,1500,1250)
savings <- c(80,60,440,900,2000,5500,100,200,900,1500,2000,3000,5000,9000,400,1200)
Month <- c(rep("May",3),rep("June",4),rep("July",3),rep("August",3),rep("September",3))
data <- data.frame(Location,profit,savings,Month)

data$Location.Bo <- 0
data$Location.Bo[data$Location == "Bo"] <- 1
data$Location.Freetown <- 0
data$Location.Freetown[data$Location == "Freetown"] <- 2
data$Location.Kailahun <- 0
data$Location.Kailahun[data$Location == "Kailahun"] <- 1
data$Location.Kono <- 0
data$Location.Kono[data$Location == "Kono"] <- 1

data$Month.May <- 0
data$Month.May[data$Month == "May"] <- 1
data$Month.June <- 0
data$Month.June[data$Month == "June"] <- 2
data$Month.July <- 0
data$Month.July[data$Month == "July"] <- 1
data$Month.August <- 0
data$Month.August[data$Month == "August"] <- 1
data$Month.September <- 0
data$Month.September[data$Month == "September"] <- 1

summary(lm(profit~savings+., data=data[,c(2,3,5:13)]))
</code>```

Method 2: Using the package fastDummies

```<code>install.packages("fastDummies")
library(fastDummies)

Location <- c(rep("Kono",4),rep("Kailahun",4),rep("Bo",4),rep("Freetown",4))
profit <- c(100,800,900,550,4500,3000,2000,1000,10,350,150,300,800,500,1500,1250)
savings <- c(80,60,440,900,2000,5500,100,200,900,1500,2000,3000,5000,9000,400,1200)
Month <- c(rep("May",3),rep("June",4),rep("July",3),rep("August",3),rep("September",3))
data <- data.frame(Location,profit,savings,Month)

data_new <- dummy_cols(data, select_columns = c("Location", "Month"))

summary(lm(profit~savings+., data=data_new[,c(2,3,5:13)]))
</code>```

Explanation: if you add the . function to the regression model, you need to specify the respective columns with the data. I did this by just specifying the column IDs but you can also write the column names, but that is usually more work.

Body:
I want to make multiple regression analysis using three factors (Location, Trainer, Savings), but the factor Location shows NA.
data:

Location <- c(rep("Kono",4),rep("Kailahun",4),rep("Bo",4),rep("Freetown",4))
profit <- c(100,800,900,550,4500,3000,2000,1000,10,350,150,300,800,500,1500,1250)
savings <- c(80,60,440,900,2000,5500,100,200,900,1500,2000,3000,5000,9000,400,1200)
Month <- c(rep("May",3),rep("June",4),rep("July",3),rep("August",3),rep("September",3))
data$Location <- dummy(data$Location)
data$Month <- dummy(data$Month)
data <- data.frame(Location,profit,savings,Month)

summary(lm(Profit~savings+Month+ocation, data=d))

LocationLocationBo                             NA         NA      NA       NA
LocationLocationFreetown                       NA         NA      NA       NA
LocationLocationKailahun                       NA         NA      NA       NA
LocationLocationKono                           NA         NA      NA       NA

it is categorical variable and has 4 levels, and I am not sure if I am handling it correctly. Can someone clarify what is wrong with it?

Body:
If I understand correctly your predictors are all categorical, so if you want to include them in a linear regression model, you should first bild dummy variables (coded 0-1), because otherwise the regression will mistake your data for metric. Here is an article that explains it very well: https://www.statology.org/dummy-variables-in-r/

If the dependent variable (Profit) is categorical too a logistic regression model might be the better choice.

EDIT: After example data was added

Method 1: Basic without additional packages

This method is useful and easy in case you only have few dummy variables.

Location <- c(rep("Kono",4),rep("Kailahun",4),rep("Bo",4),rep("Freetown",4))
profit <- c(100,800,900,550,4500,3000,2000,1000,10,350,150,300,800,500,1500,1250)
savings <- c(80,60,440,900,2000,5500,100,200,900,1500,2000,3000,5000,9000,400,1200)
Month <- c(rep("May",3),rep("June",4),rep("July",3),rep("August",3),rep("September",3))
data <- data.frame(Location,profit,savings,Month)

data$Location.Bo <- 0
data$Location.Bo[data$Location == "Bo"] <- 1
data$Location.Freetown <- 0
data$Location.Freetown[data$Location == "Freetown"] <- 2
data$Location.Kailahun <- 0
data$Location.Kailahun[data$Location == "Kailahun"] <- 1
data$Location.Kono <- 0
data$Location.Kono[data$Location == "Kono"] <- 1

data$Month.May <- 0
data$Month.May[data$Month == "May"] <- 1
data$Month.June <- 0
data$Month.June[data$Month == "June"] <- 2
data$Month.July <- 0
data$Month.July[data$Month == "July"] <- 1
data$Month.August <- 0
data$Month.August[data$Month == "August"] <- 1
data$Month.September <- 0
data$Month.September[data$Month == "September"] <- 1

summary(lm(profit~savings+., data=data[,c(2,3,5:13)]))

Method 2: Using the package fastDummies

install.packages("fastDummies")
library(fastDummies)

Location <- c(rep("Kono",4),rep("Kailahun",4),rep("Bo",4),rep("Freetown",4))
profit <- c(100,800,900,550,4500,3000,2000,1000,10,350,150,300,800,500,1500,1250)
savings <- c(80,60,440,900,2000,5500,100,200,900,1500,2000,3000,5000,9000,400,1200)
Month <- c(rep("May",3),rep("June",4),rep("July",3),rep("August",3),rep("September",3))
data <- data.frame(Location,profit,savings,Month)

data_new <- dummy_cols(data, select_columns = c("Location", "Month"))

summary(lm(profit~savings+., data=data_new[,c(2,3,5:13)]))

Explanation: if you add the . function to the regression model, you need to specify the respective columns with the data. I did this by just specifying the column IDs but you can also write the column names, but that is usually more work.


问:
Java: Get first item from a collection
If I have a collection, such as Collection<String> strs, how can I get the first item out? I could just call an Iterator, take its first next(), then throw the Iterator away. Is there a less wasteful way to do it?

答:
If you are using Apache Commons Collections 4 there is an IterableUtils.first method. It contains an optimization in the case of Lists and is neat to use. It's very similar to the Guava method. The code would look like

```<code>String firstStr = IterableUtils.first(strs);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java: Get first item from a collection

Body:
If you are using Apache Commons Collections 4 there is an IterableUtils.first method. It contains an optimization in the case of Lists and is neat to use. It's very similar to the Guava method. The code would look like

String firstStr = IterableUtils.first(strs);


问:
How to get the chat id, bot id, message id, channel id, group id using python-telegram-bot API?
I have created a bot in telegram and I wish to control it using python.

I am using python-telegram-bot API. What is the easiest way to figure out various ids using the python: bot id, chat id, message id, group id, channel id? Is there any readymade code available for this?

答:
I suppose you have something like that

```<code>updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text, echo))
</code>```

with dispatcher.add_handler you associate a specific function to run when the bot receive a message (in this case only text messages due to Filters.text)

The function will be something like that:

```<code>def echo(update, context):
    ...
    ...
    chat_id = update.message.chat_id
    message_id = update.message.message_id
    text = update.message.text
    ...
    ...
</code>```

All the informations you need are inside the Update object, received by the Dispatcher, i extracted the more usefull, but there are a lot others. Check the documentation for more details.

Body:
I suppose you have something like that

updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text, echo))

with dispatcher.add_handler you associate a specific function to run when the bot receive a message (in this case only text messages due to Filters.text)

The function will be something like that:

def echo(update, context):
    ...
    ...
    chat_id = update.message.chat_id
    message_id = update.message.message_id
    text = update.message.text
    ...
    ...

All the informations you need are inside the Update object, received by the Dispatcher, i extracted the more usefull, but there are a lot others. Check the documentation for more details.


问:
Do I need a gunicorn.config file to run Flask application in docker container?
I'm dockerizing a Flask / React application. I've started the process by installing gunicorn so that I could make this the default web server, and to that end created a wsgi.py file to load the application from there, and then from the command line I ran:

```<code>gunicorn --bind 0.0.0.0:5000 wsgi:app
</code>```

And it worked without any issues.

Now I'm attempting to dockerize the app for my first time. I didn't use a gunicorn.config file yet but I've seen it referred to in a couple of articles.

Do I need to add a gunicorn.config file to my application in order for it to run smoothly once inside a Docker container? I'm leaving it out for now but I'd appreciate any advice on what is good practice or downright necessary.

答:
It is generally a good idea to export any modifiable configuration to a config file when running your app in production. You don't have to use a config file, but hard coding all the configuration means you'll need to rebuild and redeploy the image if you want to make a change, which is not ideal.

When using Docker, you can use the -v option to mount specific files/directories from the host to the container, which is what you'd want to use when mounting an external config file.

Body:
I'm dockerizing a Flask / React application. I've started the process by installing gunicorn so that I could make this the default web server, and to that end created a wsgi.py file to load the application from there, and then from the command line I ran:

gunicorn --bind 0.0.0.0:5000 wsgi:app

And it worked without any issues.

Now I'm attempting to dockerize the app for my first time. I didn't use a gunicorn.config file yet but I've seen it referred to in a couple of articles.

Do I need to add a gunicorn.config file to my application in order for it to run smoothly once inside a Docker container? I'm leaving it out for now but I'd appreciate any advice on what is good practice or downright necessary.


问:
Debugging with breakpoints from console in Python
I'm trying to migrate from Matlab to python.  One of the things that is nice about Matlab is that when debugging I can put a breakpoint in some code and do something to call that code form the command line.  Using PyCharm + IPython I haven't found a way to do this in Python.  It seems I have to run an entire script in debug mode to do any debugging rather than being able to do so from a simple command.  I suppose I could write a one line script with the command I'm interested in, but it seems like there should be a better way.  What is the Python way of doing this?</p>

答:
To enter a permanent breakpoint in python3.7+, insert the expression breakpoint() in the source file. No more need to import anything, even pdb. In non-compiled Matlab the equivalent to breakpoint() is the statement keyboard.

The global picture is that after python's debug prompt (Pdb) (shown by breakpoint()) you may prefix python statements looking like debugging statements with exclamation mark (!), whereas after Matlab's debugging commands starts with db to lift ambiguity, and some of them only works after debug prompt K>.

I am also migrating from Matlab to Python. I am used to debugging inside matlab -nodisplay, and am switching to python3.10 without IDE. These are pretty similar, as can be seen in table below, which is a debugging-related rosetta stone.

You can create other breakpoints, using command tb or b, from that (Pdb) prompt (or in your file $HOME/.pdbrc). As their Matlab's counterpart dbstop, you can set them for another file, another line and let them be conditional.

Here is a short rosetta stone:

python
python's available shortcut
Matlab

breakpoint()

keyboard

where
w
dbstack

cont
c
dbcont

up
u
dbup

down
d
dbdown

step
s
dbstep

next
n
dbnext

print expression
p expression
expression

!nonlocal var;var=

var=

break
b
dbstop and dbstatus

clear
cl
dbclear

list
l
dbtype

display
d
variable window

help
h
help

pp vars()

save('b.mat');disp(load('b.mat'))

python -m pdb -c continuefilename.py

dbstop if error

Matlab does have no equivalent for:

ignore n p (n-th breakpoint will only trigger prompt after p-th execution)

prettyprint expression (shortcut: pp)

jump codelinenumber (shortcut: j)

I still don't know if Python has any usable equivalents for save and load except for pp vars(), evalin(caller,expr), and plots while debugging.


问:
Deprecated: Window: orientationchange event
The orientationchange event has been deprecated.

```<code>window.addEventListener("orientationchange", function(event) {
  console.log(event.target.screen.orientation.angle);
});
</code>```

Window: orientationchange event

Deprecated
This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

What can I use now? Is there any alternative way to do this?

答:
window.orientation

Still seems to work. I guess you can use

```<code>window.addEventListener('resize', function(e) {
  if (Math.abs(window.orientation) == 90) {
    // landscape mode => angle 90 or -90
  } else if (window.orientation == 0) {
    // portrait mode => angle 0
  }
})
</code>```

If you your target is strictly mobile

Body:
The orientationchange event has been deprecated.

window.addEventListener("orientationchange", function(event) {
  console.log(event.target.screen.orientation.angle);
});

Window: orientationchange event

Deprecated
This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

What can I use now? Is there any alternative way to do this?

Body:
window.orientation

Still seems to work. I guess you can use

window.addEventListener('resize', function(e) {
  if (Math.abs(window.orientation) == 90) {
    // landscape mode => angle 90 or -90
  } else if (window.orientation == 0) {
    // portrait mode => angle 0
  }
})

If you your target is strictly mobile


问:
Barplots of percentages with raw counts and confidence intervals
I have frequencies of occurrence of certain particle combinations in English and their respective percentages:

```<code>df <- structure(list(partcl = c("yeah well", "well yeah", "yeah yeah well",
                                "yeah well well", "yeah well yeah", "well yeah well", "well yeah yeah",
                                "well yeah yeah yeah", "yeah yeah yeah well", "well yeah well well"
), Freq = c(1515L, 408L, 52L, 20L, 17L, 11L, 8L, 2L, 2L, 1L),
Pct = c(74.3011280039235, 20.0098087297695, 2.55026974006866,
        0.980872976949485, 0.833742030407062, 0.539480137322217,
        0.392349190779794, 0.0980872976949485, 0.0980872976949485,
        0.0490436488474743)), class = c("tbl_df", "tbl", "data.frame"
        ), row.names = c(NA, -10L))
</code>```

I'd like to plot the percentages (in Pct), while at the same time including the raw counts (in Freq) as well as confidence intervals if that's possible at all. Here's how I plot the barplots:

```<code>library(ggplot2)
ggplot(df,
  aes(x = partcl, y = Pct)) +
  geom_bar(stat = "identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90))
</code>```

答:
You could add a label to each bar with the frequency, though Pct and Freq aren't on the same scale.

```<code>+ geom_text(aes(x = partcl, y = Pct, label = Freq))
</code>```

You have exact counts for each bar, so there wouldn't be a confidence interval as your confidence is 100% that what you have is the correct value.

Body:
I have frequencies of occurrence of certain particle combinations in English and their respective percentages:

df <- structure(list(partcl = c("yeah well", "well yeah", "yeah yeah well",
                                "yeah well well", "yeah well yeah", "well yeah well", "well yeah yeah",
                                "well yeah yeah yeah", "yeah yeah yeah well", "well yeah well well"
), Freq = c(1515L, 408L, 52L, 20L, 17L, 11L, 8L, 2L, 2L, 1L),
Pct = c(74.3011280039235, 20.0098087297695, 2.55026974006866,
        0.980872976949485, 0.833742030407062, 0.539480137322217,
        0.392349190779794, 0.0980872976949485, 0.0980872976949485,
        0.0490436488474743)), class = c("tbl_df", "tbl", "data.frame"
        ), row.names = c(NA, -10L))

I'd like to plot the percentages (in Pct), while at the same time including the raw counts (in Freq) as well as confidence intervals if that's possible at all. Here's how I plot the barplots:

library(ggplot2)
ggplot(df,
  aes(x = partcl, y = Pct)) +
  geom_bar(stat = "identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90))

Body:
You could add a label to each bar with the frequency, though Pct and Freq aren't on the same scale.

+ geom_text(aes(x = partcl, y = Pct, label = Freq))

You have exact counts for each bar, so there wouldn't be a confidence interval as your confidence is 100% that what you have is the correct value.


问:
Google MLKIt TextRecognition on iOS return always empty result
I am using react-native, react-native-vision-camera (with frameProcessor) and mlkit to perform in device text recognition.

My code works on Android, but I got always empty results on iOS.

Here is my Objective C implementation:

```<code>static inline id scanOCR(Frame* frame, NSArray* args) {
  MLKTextRecognizer *textRecognizer = [MLKTextRecognizer textRecognizer];
  MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:frame.buffer];
  image.orientation = frame.orientation;

  NSError *error;
  MLKText *result = [textRecognizer resultsInImage:image error:&error];
  if (error != nil || result == nil) {
    NSLog(@"%@", error); // <- This is NEVER called
  } else {
    NSLog(@"text: %@", result.text); // <- this is always empty
    NSLog(@"blocks lenght: %lu", (unsigned long)result.blocks.count); // <- this is always 0
  }
  return @{@"text": result.text};
}
</code>```

The project corretly compile, with no errors, but results.text is always empty, even if the camera is framing texts.

I think that MLKit is corretly installed. This is my Podfile

```<code>require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'com.digitalbore.papertag' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  pod 'GoogleMLKit/TextRecognition','2.2.0'

  target 'com.digitalbore.papertagTests' do
    inherit! :complete
    # Pods for testing
    pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen'

    pod 'react-native-receive-sharing-intent', :path => '../node_modules/react-native-receive-sharing-intent'

  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end
</code>```

答: To further understand the situation here, could you verify that you are not getting any text result with the Google ML Kit quickstart vision app on your device?</p>

Body:
I am using react-native, react-native-vision-camera (with frameProcessor) and mlkit to perform in device text recognition.

My code works on Android, but I got always empty results on iOS.

Here is my Objective C implementation:

static inline id scanOCR(Frame* frame, NSArray* args) {
  MLKTextRecognizer *textRecognizer = [MLKTextRecognizer textRecognizer];
  MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:frame.buffer];
  image.orientation = frame.orientation;

  NSError *error;
  MLKText *result = [textRecognizer resultsInImage:image error:&error];
  if (error != nil || result == nil) {
    NSLog(@"%@", error); // <- This is NEVER called
  } else {
    NSLog(@"text: %@", result.text); // <- this is always empty
    NSLog(@"blocks lenght: %lu", (unsigned long)result.blocks.count); // <- this is always 0
  }
  return @{@"text": result.text};
}

The project corretly compile, with no errors, but results.text is always empty, even if the camera is framing texts.

I think that MLKit is corretly installed. This is my Podfile

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'com.digitalbore.papertag' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  pod 'GoogleMLKit/TextRecognition','2.2.0'

  target 'com.digitalbore.papertagTests' do
    inherit! :complete
    # Pods for testing
    pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen'

    pod 'react-native-receive-sharing-intent', :path => '../node_modules/react-native-receive-sharing-intent'

  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end


问:
Conditionally highlight cells in a html table based on the cells' value
The data of my html table is from this list:

```<code>mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}]
</code>```

My HTML table in my HTML file is:

```<code><table class="table table-striped" id="dataTable" width="100%" cellspacing="0">

     <thead>
        <tr>
            <th>StartDate</th>
            <th>ID</th>
            <th>Name</th>
            <th>Days</th>

     </thead>
     <body>

{% for element in mylist %}

      <tr>
        <td>{{ element.StartDate}}</td>
        <td>{{ element.ID }}</td>
        <td>{{ element.Receiver }}</td>
        <td>{{ element.Days }}</td>

       </tr>
      {% endfor %}
       </tbody>

      </table>
</code>```

I want to set the color of days that are larger than 14 into Red color. And I want to set the cells that contain "Mike" in Red and "Jane" in Blue.

Please advise what I should do

答:
Django has if statement template tags that can be used for this.

For example, for your days section you could write your  element like this in your template:

```<code><td {% if element.Days > 14 %} class="red_class"{% endif %}>{{ element.Days }}</td>
</code>```

You would then define a css class named red_class and set the background color attribute of that element to red.

The name part would be similar:

```<code><td
   {% if element.Receiver == "Mike" %}
      class="red_class"
   {% elif element.Receiver == 'Jane' %}
      class="blue_class"
   {% endif %} > {{ element.Receiver }}</td>
</code>```

Body:
The data of my html table is from this list:

mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}]

My HTML table in my HTML file is:

            StartDate
            ID
            Name
            Days

{% for element in mylist %}

        {{ element.StartDate}}
        {{ element.ID }}
        {{ element.Receiver }}
        {{ element.Days }}

      {% endfor %}

I want to set the color of days that are larger than 14 into Red color. And I want to set the cells that contain "Mike" in Red and "Jane" in Blue.

Please advise what I should do

Body:
Django has if statement template tags that can be used for this.

For example, for your days section you could write your <td> element like this in your template:

<td {% if element.Days > 14 %} class="red_class"{% endif %}>{{ element.Days }}</td>

You would then define a css class named red_class and set the background color attribute of that element to red.

The name part would be similar:

<td
   {% if element.Receiver == "Mike" %}
      class="red_class"
   {% elif element.Receiver == 'Jane' %}
      class="blue_class"
   {% endif %} > {{ element.Receiver }}</td>


问:
Why does discord.py bot sends multiple messages if there is a break out of loop?
My discord.py bot is meant to send notifications in "streamers" text channel when a streamer from SQLite3 DB assigned to this particular server goes live. The problem is that bot sends multiple notification messages (actually exactly equal to channel.history limit) when there is a break out of the loop. What may cause this problem?

P/S: don't mind me for these > 79 lines of code, they are going to get fixed when I'm done with the logic.

def _checkuser(user: str) -> dict | None:
    """Запрос к Twitch с проверкой, стримит ли указанный пользователь."""
    stream = requests.get(
        'https://api.twitch.tv/helix/streams?user_login=' + user,
        headers=TWITCH_HEADERS,
    )
    stream_data = stream.json()
    if len(stream_data['data']) == 1:
        return stream_data['data'][0]
    else:
        return None

@bot.event
async def on_ready() -> None:
    """Обработчик события при запуске бота."""
    @tasks.loop(seconds=10)
    async def live_notification_loop() -> None:
        """Луп проверки стримеров."""
        for guild in bot.guilds:
            cursor.execute(
                f'SELECT id, name FROM streamers WHERE server_id = {guild.id}'
            )
            streamers = cursor.fetchmany()
            if streamers is not None:
                channel: discord.TextChannel = discord.utils.get(
                    guild.channels,
                    name='streamers',
                )
                for user_id, name in streamers:
                    status = _checkuser(name)
                    user = bot.get_user(user_id)
                    if status:
                        # messages = await channel.history(limit=200).flatten()
                        # for message in messages:
                        async for message in channel.history(limit=10):
                            if str(user.mention) in message.content:
                                break
                            else:
                                ALERT_MSG = '{streamer} запустил трансляцию. Не пропустите!'
                                ALERT_EMBED = discord.Embed(
                                    title=EMBED_TITLE,
                                    description=f'{status["user_name"]} играет в {status["game_name"]} для {status["viewer_count"]} зрителей.',
                                    url=f'https://twitch.tv/{status["user_name"]}',
                                    colour=0x6441A5,
                                    timestamp=datetime.utcnow(),
                                )
                                ALERT_EMBED.set_author(
                                    name=f'{status["user_name"]} запустил трансляцию на Twitch.',
                                    url=f'https://twitch.tv/{status["user_name"]}'
                                )
                                ALERT_EMBED.set_image(
                                    url=status["thumbnail_url"].format(
                                        width=640,
                                        height=360,
                                    )
                                )
                                await channel.send(
                                    ALERT_MSG.format(
                                        streamer=user.mention
                                    ),
                                    embed=ALERT_EMBED,
                                )
    live_notification_loop.start()
```

答: Added break after await.send, one notification message now.</p>


问:
Changes in Apache SuperSet .less templates are not being applied to interface after build
I'm currently running Apache Superset which is working very well.

However, I've now received a requirement to make a few structural changes to the CSS layout and formatting of the Superset interface. Making changes to the dashboard CSS templates and config.py won't be sufficient. So what I would like to achieve is to make changes to the superset .less templates and have chose changes applied to the interface. However, so far I've not been able to successfully making any changes to the interface by changing the .less templates.

What I've tried to far is to:

Follow all the instructions to build my Apache Superset from source using the instructions here: https://github.com/apache/superset/blob/master/CONTRIBUTING.md#setup-local-environment-for-development

Make changes to the .less templates as described here: https://debaatobiee.wordpress.com/2019/08/04/customizing-apache-superset-ui-config-theme-changes/

However, after making changes to the .less templates, and rebuilding using "npm run build" and "npm run dev-server" in directory superset-frontend, it seems that those changes are not being applied.

Am I doing any steps incorrectly? I'm using a aws t3.large machine with Ubuntu Server 20.04 LTS (HVM) x86 and I run the following commands from machine creation:

```<code>sudo apt update
sudo apt upgrade
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev python3-pip libsasl2-dev libldap2-dev libmysqlclient-dev python3.8-venv
git clone https://github.com/apache/superset.git
cd superset
python3 -m venv venv
. venv/bin/activate
pip install -r requirements/development.txt
pip install pymssql
pip install -e .
superset db upgrade
superset fab create-admin
superset init
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.0/install.sh | bash
source ~/.nvm/nvm.sh
cd superset-frontend
nvm install --lts
nvm use --lts
npm ci
</code>```

I edit the file ~/superset/superset-frontend/src/assets/stylesheets/less/variables.less as follows:

Replace @primary-color: #20a7c9 with @primary-color: #00ff00

Now in one command prompt I run the following command:

```<code>FLASK_ENV=development superset run -p 8088 -h 0.0.0.0 --with-threads --reload --debugger
</code>```

And in another command prompt I run the following:

```<code>npm run build
npm run dev-server
</code>```

I can successfully connect to the page on port 9000. However, even after ctrl+f5 the css never seems to change according to the changes I made in the .less templates. In this example I would have expected the color to have changed (no more #20a7c9 in the css, but #00ff00 instead).

What am I doing incorrectly in my approach? Or is there an easier way to do what I'm trying to do (make site-wide LESS/CSS changes)? I've tried using Docker but I wasn't successful in making that work.

答: After more testing I found that my changes from the .less templates were in fact being applied using the approach I mentioned. I had just not made enough changes in the .less templates to notice the difference. So by making more changes, and checking in the right places, I could change the Superset interface. Moving forward I've learned to make more rigorous changes and figure out how they influence the interface through trial and error. Still feels like an inefficient approach though - if there would be a quicker way to apply & test css / less changes instead of rebuilding that would be helpful.</p>

Body:
I'm currently running Apache Superset which is working very well.

However, I've now received a requirement to make a few structural changes to the CSS layout and formatting of the Superset interface. Making changes to the dashboard CSS templates and config.py won't be sufficient. So what I would like to achieve is to make changes to the superset .less templates and have chose changes applied to the interface. However, so far I've not been able to successfully making any changes to the interface by changing the .less templates.

What I've tried to far is to:

Follow all the instructions to build my Apache Superset from source using the instructions here: https://github.com/apache/superset/blob/master/CONTRIBUTING.md#setup-local-environment-for-development

Make changes to the .less templates as described here: https://debaatobiee.wordpress.com/2019/08/04/customizing-apache-superset-ui-config-theme-changes/

However, after making changes to the .less templates, and rebuilding using "npm run build" and "npm run dev-server" in directory superset-frontend, it seems that those changes are not being applied.

Am I doing any steps incorrectly? I'm using a aws t3.large machine with Ubuntu Server 20.04 LTS (HVM) x86 and I run the following commands from machine creation:

sudo apt update
sudo apt upgrade
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev python3-pip libsasl2-dev libldap2-dev libmysqlclient-dev python3.8-venv
git clone https://github.com/apache/superset.git
cd superset
python3 -m venv venv
. venv/bin/activate
pip install -r requirements/development.txt
pip install pymssql
pip install -e .
superset db upgrade
superset fab create-admin
superset init
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.0/install.sh | bash
source ~/.nvm/nvm.sh
cd superset-frontend
nvm install --lts
nvm use --lts
npm ci

I edit the file ~/superset/superset-frontend/src/assets/stylesheets/less/variables.less as follows:

Replace @primary-color: #20a7c9 with @primary-color: #00ff00

Now in one command prompt I run the following command:

FLASK_ENV=development superset run -p 8088 -h 0.0.0.0 --with-threads --reload --debugger

And in another command prompt I run the following:

npm run build
npm run dev-server

I can successfully connect to the page on port 9000. However, even after ctrl+f5 the css never seems to change according to the changes I made in the .less templates. In this example I would have expected the color to have changed (no more #20a7c9 in the css, but #00ff00 instead).

What am I doing incorrectly in my approach? Or is there an easier way to do what I'm trying to do (make site-wide LESS/CSS changes)? I've tried using Docker but I wasn't successful in making that work.


问:
typescript: Derive types from Conditional Types
Typescript supports Conditional Types.
But when I try to set value of op as string, it gives me error, how do I check the type and assign value?

export const t = <IsMulti extends boolean = false>(): void => {
    const value = 'test';
    type S = string;
    type D = IsMulti extends true ? S[] : S;
    const op: D = value;
    console.log(op);
};
```
<p>Error: <code>Type 'string' is not assignable to type 'D'.</code></p>
<p>I have even tried adding a parameter of same type <code>IsMulti</code> and adding check based on it</p>
<pre class="lang-js prettyprint-override"><code>export const t = <IsMulti extends boolean = false>(isMulti: IsMulti): void => {
    const value = 'test';
    type S = string;
    type D = IsMulti extends true ? S[] : S;
    if (!isMulti) {
        const op: D = value;
        console.log(op);
    }
};
</code>```

still it gives the same error.

答:
Evaluation of conditional types which depend on as-yet unspecified generic type parameters is generally deferred by the compiler; if the compiler doesn't know exactly what IsMulti is, then it does not know exactly what IsMulti extends true ? S[] : S is, and so it won't let you assign a value of type (say) S to that conditional type, because it is unable to verify that this is a type-safe operation.  The compiler doesn't even really try to evaluate such conditional types; it leaves them as opaque things that almost nothing can be assigned to.

For your first example this is the desired behavior from the compiler; it really isn't safe to assign a string to op because D may well be string[].  Nothing stops someone from calling t<true>().  Just because IsMulti has a default of false doesn't mean it is false.

For your second example, this is currently a limitation of TypeScript.  The compiler cannot use control flow analysis to narrow type parameters.  And therefore it cannot verify assignability to a See microsoft/TypeScript#33912 for details.

When you check if (!isMulti), the compiler narrows the type of the isMulti inside the subsequent code block from the IsMulti type to just false:

```<code>export const t = <IsMulti extends boolean = false>(isMulti: IsMulti): void => {
  if (!isMulti) {
    // isMulti is now known to be false
    const fls: false = isMulti; // okay
    const tru: true = isMulti; // error
  }
};
</code>```

But it does not narrow the type parameter IsMulti itself.  In general this is also desired behavior from the compiler, since IsMulti extends boolean implies that IsMulti might actually be the full union boolean (as opposed to just true or just false) and so checking a value of type IsMulti would not be useful to narrow IsMulti itself.  All you could say with if (!isMulti) is that IsMulti could not be just true... but it might still be boolean.  Of course if it is boolean, then D, a distributive conditional type would become the union S[] | S, and you should be allowed to assign a string to that.  So there's no plausible way that assigning "test" to op should be unsafe.

And yet, the compiler is unable to verify this.  It stubbornly leaves IsMulti alone, and won't let you assign anything to D because it defers evaluation.  It would be nice if there were some supported way to narrow type parameters, or to verify assignability to generic conditional types.  For now, there really isn't.  The above linked GitHub issue is a feature request to improve this, and there are a bunch of related requests that might help (e.g., microsoft/TypeScript#27808 could restrict IsMulti to be exactly true or exactly false, and presumably then if (!isMulti) would narrow the previously generic type IsMulti to the specific type false, and D would be evaluated eagerly).  You could go to these issues and give them a , but it's not obvious that anything is going to happen here anytime soon.

Instead, in situations like this where you know more about the types than the compiler does, you can use a type assertion to suppress assignability errors:

```<code>export const t = <IsMulti extends boolean = false>(isMulti: IsMulti): void => {
  const value = 'test';
  type S = string;
  type D = IsMulti extends true ? S[] : S;
  if (!isMulti) {
    const op = value as D; // okay
    console.log(op);
  }
};
</code>```

By writing value as D you're telling the compiler that you know that value is definitely of type D, even though the compiler cannot.  This allows the program to compile without error.  Note that this is not magic, and by doing a type assertion you are taking some of the responsibility for type safety away from the compiler.  If you have made a mistake or lied to the compiler, it can't always catch it:

```<code>if (!isMulti) {
  const op = ["oopsie"] as D; // still okay
  console.log(op);
}
</code>```

So be careful!

Playground link to code

Body:
Typescript supports Conditional Types.
But when I try to set value of op as string, it gives me error, how do I check the type and assign value?

export const t = <IsMulti extends boolean = false>(): void => {
    const value = 'test';
    type S = string;
    type D = IsMulti extends true ? S[] : S;
    const op: D = value;
    console.log(op);
};

Error: Type 'string' is not assignable to type 'D'.

I have even tried adding a parameter of same type IsMulti and adding check based on it

export const t = <IsMulti extends boolean = false>(isMulti: IsMulti): void => {
    const value = 'test';
    type S = string;
    type D = IsMulti extends true ? S[] : S;
    if (!isMulti) {
        const op: D = value;
        console.log(op);
    }
};

still it gives the same error.

Body:
Evaluation of conditional types which depend on as-yet unspecified generic type parameters is generally deferred by the compiler; if the compiler doesn't know exactly what IsMulti is, then it does not know exactly what IsMulti extends true ? S[] : S is, and so it won't let you assign a value of type (say) S to that conditional type, because it is unable to verify that this is a type-safe operation.  The compiler doesn't even really try to evaluate such conditional types; it leaves them as opaque things that almost nothing can be assigned to.

For your first example this is the desired behavior from the compiler; it really isn't safe to assign a string to op because D may well be string[].  Nothing stops someone from calling t<true>().  Just because IsMulti has a default of false doesn't mean it is false.

For your second example, this is currently a limitation of TypeScript.  The compiler cannot use control flow analysis to narrow type parameters.  And therefore it cannot verify assignability to a See microsoft/TypeScript#33912 for details.

When you check if (!isMulti), the compiler narrows the type of the isMulti inside the subsequent code block from the IsMulti type to just false:

export const t = <IsMulti extends boolean = false>(isMulti: IsMulti): void => {
  if (!isMulti) {
    // isMulti is now known to be false
    const fls: false = isMulti; // okay
    const tru: true = isMulti; // error
  }
};

But it does not narrow the type parameter IsMulti itself.  In general this is also desired behavior from the compiler, since IsMulti extends boolean implies that IsMulti might actually be the full union boolean (as opposed to just true or just false) and so checking a value of type IsMulti would not be useful to narrow IsMulti itself.  All you could say with if (!isMulti) is that IsMulti could not be just true... but it might still be boolean.  Of course if it is boolean, then D, a distributive conditional type would become the union S[] | S, and you should be allowed to assign a string to that.  So there's no plausible way that assigning "test" to op should be unsafe.

And yet, the compiler is unable to verify this.  It stubbornly leaves IsMulti alone, and won't let you assign anything to D because it defers evaluation.  It would be nice if there were some supported way to narrow type parameters, or to verify assignability to generic conditional types.  For now, there really isn't.  The above linked GitHub issue is a feature request to improve this, and there are a bunch of related requests that might help (e.g., microsoft/TypeScript#27808 could restrict IsMulti to be exactly true or exactly false, and presumably then if (!isMulti) would narrow the previously generic type IsMulti to the specific type false, and D would be evaluated eagerly).  You could go to these issues and give them a , but it's not obvious that anything is going to happen here anytime soon.

Instead, in situations like this where you know more about the types than the compiler does, you can use a type assertion to suppress assignability errors:

export const t = <IsMulti extends boolean = false>(isMulti: IsMulti): void => {
  const value = 'test';
  type S = string;
  type D = IsMulti extends true ? S[] : S;
  if (!isMulti) {
    const op = value as D; // okay
    console.log(op);
  }
};

By writing value as D you're telling the compiler that you know that value is definitely of type D, even though the compiler cannot.  This allows the program to compile without error.  Note that this is not magic, and by doing a type assertion you are taking some of the responsibility for type safety away from the compiler.  If you have made a mistake or lied to the compiler, it can't always catch it:

if (!isMulti) {
  const op = ["oopsie"] as D; // still okay
  console.log(op);
}

So be careful!

<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAYwgOwM73gXjgHgJKoCyArgDYwCWcoMwyAJqnAEYQSnACGyc2AZp1KpgAPgAUASgBccAG4QK9XiLgBvAFBxEKdHMHFgvOAHJa6YwG5NcGAE8whgMpH0UCsgDmVrXYdwAIkYEJORUNHSMNlAGcAD8cI4A2gC6cDKO3tpo8BBgMoHYsvrAmUho7MAAdKQQHmK5ElYAvlbqoJCwWbrERvhEZJTUILQMTKwV3EYCQqJiFP2hMsEDFNJyCkqYKhpaZbpFpDHYpsDmmb5OLjBunuf2hgVwy6FDI5HXMfFJqemZFHxwMQAQnmIUoEjU1l2OngfCEMmmwiMoJWFjgAHp0XAIABrTi2KFdDDRGQfQzYFGhNGY6hQKDQQl7HJgIwHGKcJj+alY3H4xk6CrVWr1MCNaxNdQtdRtcDQeBMuS9Z6DcKjFhsDiTfiCYTiSmUJYLcEyeSKZSQnz3BJXG5eawXAJBI1hYYRJhkuIJFJpBJ-AHA-WrC1aInYlnYRIAIjYYFQFGAkdSHIC3OxeIJIa6gpqdQamQlLSAA" rel="nofollow noreferrer">Playground link to code


问:
C# Setup Project Custom Action to save the installation directory to custom setting file
I am trying to make an application using windows installer as it's install method. When the installation succeeds I want to get the path where the primary output is located that I configured in the installer. In my case the primary output is in the folder [ApplicationData(Installroot)]\Bin\.

I also have a custom settings file called App.Settings in 1 my Class Library which controls several settings like file locations who are relative to the install location.

So the idea is that when the installation succeeds it should call the App.Settings and save the install folder to the settings file.

I already made an Install class and put it inside the Class Library. I am not sure if it is supposed to be in that project though.
This is the code of the Install Class:

```<code>using System.Collections;
using System.ComponentModel;

namespace WaspbaneModels
{
    [RunInstaller(true)]
    public partial class Installer : System.Configuration.Install.Installer
    {
        public Installer()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
        }

        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);

            SettingsControl.BaseURL = Context.Parameters["assemblypath"];
            SettingsControl.Save();
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
        }

        public override void Uninstall(IDictionary savedState)
        {
            base.Uninstall(savedState);
        }
    }
}
</code>```

In this code SettingsControl is the class that takes care of the Settings simply with some properties. I used this class so that my Windows Forms project also can access these settings.

In the Custom Actions tab I also added the Primary Output to everything. I am also not sure if this is correct because I think the Primary Output contains all .dll files including the Class Libraries.

I am not really sure where to continue from this point however because the Settings are not saved. I simply check this by putting up a messagebox at the startup of the application giving me the value of the setting.

Anyone interested in more data of the project just ask. I just won't post everything at once yet.

EDIT:

After some more testing I managed to find out that the Installer class isn't being called upon. I added something that would write out to a file when the method would've been called but nothing happened.

Therefore my question now is: How do I add the Custom Action to the Setup project properly?

答:
I had the same problem today.

My issue had to do with the project type I was using as Class Library.

I was selecting a new project of type Class Library.

I changed it to Class Library (.NET Framework).

Body:
I am trying to make an application using windows installer as it's install method. When the installation succeeds I want to get the path where the primary output is located that I configured in the installer. In my case the primary output is in the folder [ApplicationData(Installroot)]\Bin\.

I also have a custom settings file called App.Settings in 1 my Class Library which controls several settings like file locations who are relative to the install location.

So the idea is that when the installation succeeds it should call the App.Settings and save the install folder to the settings file.

I already made an Install class and put it inside the Class Library. I am not sure if it is supposed to be in that project though.
This is the code of the Install Class:

using System.Collections;
using System.ComponentModel;

namespace WaspbaneModels
{
    [RunInstaller(true)]
    public partial class Installer : System.Configuration.Install.Installer
    {
        public Installer()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
        }

        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);

            SettingsControl.BaseURL = Context.Parameters["assemblypath"];
            SettingsControl.Save();
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
        }

        public override void Uninstall(IDictionary savedState)
        {
            base.Uninstall(savedState);
        }
    }
}

In this code SettingsControl is the class that takes care of the Settings simply with some properties. I used this class so that my Windows Forms project also can access these settings.

In the Custom Actions tab I also added the Primary Output to everything. I am also not sure if this is correct because I think the Primary Output contains all .dll files including the Class Libraries.

I am not really sure where to continue from this point however because the Settings are not saved. I simply check this by putting up a messagebox at the startup of the application giving me the value of the setting.

Anyone interested in more data of the project just ask. I just won't post everything at once yet.

EDIT:

After some more testing I managed to find out that the Installer class isn't being called upon. I added something that would write out to a file when the method would've been called but nothing happened.

Therefore my question now is: How do I add the Custom Action to the Setup project properly?


问:
PHP / REST API: Splitting a string into three variables
I'm trying to split a string from Formstack's RestAPI into three variables and I'm not sure how to format the syntax for the division.

Need to turn:

```<code>$NameVar = "first = Stacy last = Lassy middle = M";
</code>```

Into:

```<code>$FirstNameVar = "Stacy";
$MiddleNameVar = "M";
$LastNameVar = "Lassy";
</code>```

答:
You can try like this</p>
```<code>$NameVar = "first = Stacy last = Lassy middle = M";

$vars = getVariableArrays($NameVar);

foreach($vars as $key => $var){
    ${ucfirst($key) . 'NameVar'} = $var;
}

echo 'First Name: '. $FirstNameVar .'<br>';
echo 'Middle Name: '. $MiddleNameVar .'<br>';
echo 'Last Name: '. $LastNameVar .'<br>';

function getVariableArrays($NameVar){
  $NameVar = str_replace(' = ', ',', $NameVar);

  $strArr  = explode(' ', $NameVar);
  $nameVarArr = [];

  foreach($strArr as $str){
    $strVar = explode(',' , $str);
    $nameVarArr[$strVar[0]] = $strVar[1];
  }
  return $nameVarArr;
}
</code>```

Body:
I'm trying to split a string from Formstack's RestAPI into three variables and I'm not sure how to format the syntax for the division.

Need to turn:

$NameVar = "first = Stacy last = Lassy middle = M";

Into:

$FirstNameVar = "Stacy";
$MiddleNameVar = "M";
$LastNameVar = "Lassy";

Body:
You can try like this

$NameVar = "first = Stacy last = Lassy middle = M";

$vars = getVariableArrays($NameVar);

foreach($vars as $key => $var){
    ${ucfirst($key) . 'NameVar'} = $var;
}

echo 'First Name: '. $FirstNameVar .'<br>';
echo 'Middle Name: '. $MiddleNameVar .'<br>';
echo 'Last Name: '. $LastNameVar .'<br>';

function getVariableArrays($NameVar){
  $NameVar = str_replace(' = ', ',', $NameVar);

  $strArr  = explode(' ', $NameVar);
  $nameVarArr = [];

  foreach($strArr as $str){
    $strVar = explode(',' , $str);
    $nameVarArr[$strVar[0]] = $strVar[1];
  }
  return $nameVarArr;
}


问:
What exactly are the rules for configuring postcss.config.js (mainly with tailwndcss)?
The number of variants that exist to showcase how postcss.config.js has to be configured is extremely confusing. There are examples (like the one at the tailwindcss documentation) that use this:

// Example 1:
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}
```
<p>then there are those which require the libraries:</p>
<pre class="lang-js prettyprint-override"><code>// Example 2:
module.exports = {
  plugins: {
    require('tailwindcss'),
    require('postcss-preset-env')({
      stage: 0,
      'nesting-rules': true
    })
  },
}
</code>```

Others require external libs before they configure module.exports:

// Example 3:

const tailwindcss = require('tailwindcss');
const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  plugins: {
    tailwindcss,
    postcssPresetEnv
  },
}
```
<p>and again some more that are necessary, when a configuration file that is not named according to the defaults has to be incorporated.</p>
<p>Today I get this error, when running <code>yarn dev</code> with a postcss.config.js as show in Example 2:</p>
<pre class="lang-sh prettyprint-override"><code>Syntax Error: /[path]/_pod-test/postcss.config.js:3
    require('tailwindcss'),
             ^^^^^^^^^^^

SyntaxError: Unexpected string
</code>```

When I remove the line with "tailwindcss", the same thing happens for "postcss-preset-env":

Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
    require('postcss-preset-env')({
            ^^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected string
```
<p>When I then switch to a setup as shown in example 1, I get this error:</p>
<pre class="lang-sh prettyprint-override"><code>Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
Migration guide for end-users:
https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users
</code>```

I do use postcss 8.3.9!

This all happens in a project that was setup with vue-cli as a Vue2 project.

Which witch craft do I have to apply to make this setup work?

答:
for me is THIS config that can run correctly :

```<code>// Example 3:

const tailwindcss = require('tailwindcss');
const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  plugins: {
    tailwindcss,
    postcssPresetEnv
  },
}
</code>```

and with this versions libraries :

```<code>"postcss": "^8.4.6",
"postcss-cli": "^9.1.0",
"tailwindcss": "^3.0.18",
</code>```

I do not try all features postcss at this time but basic process file into CLI run correctly...

Body:
The number of variants that exist to showcase how postcss.config.js has to be configured is extremely confusing. There are examples (like the one at the tailwindcss documentation) that use this:

// Example 1:
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

then there are those which require the libraries:

// Example 2:
module.exports = {
  plugins: {
    require('tailwindcss'),
    require('postcss-preset-env')({
      stage: 0,
      'nesting-rules': true
    })
  },
}

Others require external libs before they configure module.exports:

// Example 3:

const tailwindcss = require('tailwindcss');
const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  plugins: {
    tailwindcss,
    postcssPresetEnv
  },
}

and again some more that are necessary, when a configuration file that is not named according to the defaults has to be incorporated.

Today I get this error, when running yarn dev with a postcss.config.js as show in Example 2:

Syntax Error: /[path]/_pod-test/postcss.config.js:3
    require('tailwindcss'),
             ^^^^^^^^^^^

SyntaxError: Unexpected string

When I remove the line with "tailwindcss", the same thing happens for "postcss-preset-env":

Syntax Error: /Volumes/_III_/Z_WWW/_ZZZ PoD/_pod-test/postcss.config.js:3
    require('postcss-preset-env')({
            ^^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected string

When I then switch to a setup as shown in example 1, I get this error:

Syntax Error: Error: PostCSS plugin tailwindcss requires PostCSS 8.
Migration guide for end-users:
https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users

I do use postcss 8.3.9!

This all happens in a project that was setup with vue-cli as a Vue2 project.

Which witch craft do I have to apply to make this setup work?

Body:
for me is THIS config that can run correctly :

// Example 3:

const tailwindcss = require('tailwindcss');
const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  plugins: {
    tailwindcss,
    postcssPresetEnv
  },
}

and with this versions libraries :

"postcss": "^8.4.6",
"postcss-cli": "^9.1.0",
"tailwindcss": "^3.0.18",

I do not try all features postcss at this time but basic process file into CLI run correctly...


问:
Shared function has non-shared return type
Getting error Shared function has non-shared return type for returning Item for the get method.

How would one make Item shared or is there a better way going about returning properties/object

```<code>public type Item = {
    id: Nat;
    var name: Text;
};

actor Maas {
    var items: [Item] = [];

    ...

    public shared query func get(id: Nat) : async Item {
        return businesses[id - 1];
    };
};
</code>```

答:
I just started getting into Motoko but I dug a little bit into documentation.

As I understood you need to make your type shared type (https://smartcontracts.org/docs/language-guide/language-manual.html#sharability)

```<code>A type T is shared if it is:

- an object type where all fields are immutable and have shared type, or

- a variant type where all tags have shared type
</code>```

Since var is declares mutable variables (https://smartcontracts.org/docs/language-guide/mutable-state.html#_immutable_versus_mutable_variables)
The type becomes non shared type.

All there is need to be done is to remove var from the type Item

```<code>public type Item = {
    id: Nat;
    name: Text;
};

actor Maas {
    var items: [Item] = [];

    ...

    public shared query func get(id: Nat) : async Item {
        return businesses[id - 1];
    };
};
</code>```

Body:
Getting error Shared function has non-shared return type for returning Item for the get method.

How would one make Item shared or is there a better way going about returning properties/object

public type Item = {
    id: Nat;
    var name: Text;
};

actor Maas {
    var items: [Item] = [];

    ...

    public shared query func get(id: Nat) : async Item {
        return businesses[id - 1];
    };
};

Body:
I just started getting into Motoko but I dug a little bit into documentation.

As I understood you need to make your type shared type (https://smartcontracts.org/docs/language-guide/language-manual.html#sharability)

A type T is shared if it is:

- an object type where all fields are immutable and have shared type, or

- a variant type where all tags have shared type

Since var is declares mutable variables (https://smartcontracts.org/docs/language-guide/mutable-state.html#_immutable_versus_mutable_variables)
The type becomes non shared type.

All there is need to be done is to remove var from the type Item

public type Item = {
    id: Nat;
    name: Text;
};

actor Maas {
    var items: [Item] = [];

    ...

    public shared query func get(id: Nat) : async Item {
        return businesses[id - 1];
    };
};