问:
Nuxt SPA without node server
I head to create Nuxt SPA with routing and mb API in future like that:

Backend server (on express or smth else) listen and on request give entire SPA to client.

Now user can use everything on client side (include routing) with no more else requests to backend (mb API requests only)

It means that server should give some .html file with js and css files as SPA and it will work on client side.

I tried to run some commands like nuxt build and nuxt generate
It looks like they return a same result - js files couldn't be found

And index.html file doesn't work properly

After some researching I found a solution

But now I got this:

It can't open the fourth js file in another js file. Path isn't right!

Every time I tried to run it as a static html file and from localhost (and also with using Live Server)

I think I did a lot of crutches and there should be another built-in function or feature that allows us to do what I want

I wrote a lot - if I made a mistake or you didn't get smth - please, ask! I need any help

答:
To test your locally built application, you need to serve all files within the generated /dist folder. You can setup very easily a local web server using Express/Node.js as you already have Node.js installed when running Nuxt. Create a new folder and install express via npm (run npm install express).

Then, copy everything from /dist into /public and create a file server.js:

const express = require('express');
const app = express();

app.use(express.static(__dirname + '/public'));
app.listen(3000);```

Run the web server with node server.js and you can access your generated files on http://localhost:3000.

Title: Nuxt SPA without node server

Body:
To test your locally built application, you need to serve all files within the generated /dist folder. You can setup very easily a local web server using Express/Node.js as you already have Node.js installed when running Nuxt. Create a new folder and install express via npm (run npm install express).

Then, copy everything from /dist into /public and create a file server.js:

const express = require('express');
const app = express();

app.use(express.static(__dirname + '/public'));
app.listen(3000);

Run the web server with node server.js and you can access your generated files on http://localhost:3000.


来源: stackexchange

问:
ImportError: Cannot import 'views' from '__main__'
This is the url.py file in the polls app on my website(project) file:

```<code>from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
</code>```

File "<string>", line 2, in <module>
ImportError: cannot import name 'views' from '__main__' (/storage/emulated/0/website/polls/urls.py)
```

<p>Now the main urls.py file in the website file</p>

```from django.contrib import admin

from django.urls import include, path

    urlpatterns = [
        path('polls/', include('polls.urls')),

        path('admin/', admin.site.urls),
    ]
```

<p>Traceback code:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File

    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

[Program finished]
</code>```

I have tried the polls urls.py like this
  from polls import views

but it gets a Module Error so what's the issue with the code?

答:
You need to separate your views and urls create a new module (file) urls.py in your app, in your case it is weather folder, and add these code there, and remove it from views.py, you can read here about it to understand it better.

`Path :

the_weather/weather/urls.py`

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.index),  #the path for our index view
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is the url.py file in the polls app on my website(project) file:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

File "<string>", line 2, in <module>
ImportError: cannot import name 'views' from '__main__' (/storage/emulated/0/website/polls/urls.py)

Now the main urls.py file in the website file

from django.contrib import admin

from django.urls import include, path

    urlpatterns = [
        path('polls/', include('polls.urls')),

        path('admin/', admin.site.urls),
    ]

Traceback code:

Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File

    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

[Program finished]

I have tried the polls urls.py like this
  from polls import views

but it gets a Module Error so what's the issue with the code?

Body:
You need to separate your views and urls create a new module (file) urls.py in your app, in your case it is weather folder, and add these code there, and remove it from views.py, you can read here about it to understand it better.

`Path :

the_weather/weather/urls.py`

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index),  #the path for our index view
]


问:
Changing background color of app with dynami theming
I have custom theming in Angular Material which looks:

```<code>@import '~@angular/material/theming';

@include mat-core();

/* ======== angular material custom theme ======== */
$my-custom-primary: mat-palette($mat-blue, 800, 900, A100);
$my-custom-accent: mat-palette($mat-pink, 100, 500, A100);
$my-custom-warn: mat-palette($mat-lime);

// Light theme
$my-custom-light-theme: mat-light-theme($my-custom-primary, $my-custom-accent, $my-custom-warn);
@include angular-material-theme($my-custom-light-theme);

$my-custom-dark-theme: mat-dark-theme($my-custom-primary, $my-custom-accent, $my-custom-warn);

// Dark theme
.dark-theme {
    color: $light-primary-text;
    @include angular-material-theme($my-custom-dark-theme);
}

//@include angular-material-theme($my-custom-dark-theme);

// Alternate Angular Material Theme
.my-alternate-theme {
    $my-alternate-primary: mat-palette($mat-red);
    $my-alternate-accent: mat-palette($mat-green, 400);
    $my-alternate-warn: mat-palette($mat-grey);

    $my-alternate-theme: mat-light-theme($my-alternate-primary, $my-alternate-accent, $my-alternate-warn);
    @include angular-material-theme($my-alternate-theme);
}
</code>```

and dynamic switcher in app.component:

```<code><div class="mat-app-background" [class.dark-theme]="theme.isDark()">
    <router-outlet></router-outlet>
</div>
</code>```

but when changing to dark theme the background color is still white - it does not change whether I set mat-app-background class on div section. Do you know which way should I follow to change this background color?

答:
Try this :-

Working Stackblitz :- https://stackblitz.com/edit/angular-scss-demo-expsck

```<code><div id="parentContainer" class="mat-app-background" [ngClass]="{'dark-theme': theme.isDark(), 'mat-app-background': true}">
    <router-outlet></router-outlet>
</div>
</code>```

Also by default body or any div takes height as per its content, if you want to treat it as whole height and width of browser. Add this css :-

```<code> #parentContainer{
     height: 100vh;
     body: 100vw;
     overflow: auto;
  }
</code>```

Body:
I have custom theming in Angular Material which looks:

@import '~@angular/material/theming';

@include mat-core();

/* ======== angular material custom theme ======== */
$my-custom-primary: mat-palette($mat-blue, 800, 900, A100);
$my-custom-accent: mat-palette($mat-pink, 100, 500, A100);
$my-custom-warn: mat-palette($mat-lime);

// Light theme
$my-custom-light-theme: mat-light-theme($my-custom-primary, $my-custom-accent, $my-custom-warn);
@include angular-material-theme($my-custom-light-theme);

$my-custom-dark-theme: mat-dark-theme($my-custom-primary, $my-custom-accent, $my-custom-warn);

// Dark theme
.dark-theme {
    color: $light-primary-text;
    @include angular-material-theme($my-custom-dark-theme);
}

//@include angular-material-theme($my-custom-dark-theme);

// Alternate Angular Material Theme
.my-alternate-theme {
    $my-alternate-primary: mat-palette($mat-red);
    $my-alternate-accent: mat-palette($mat-green, 400);
    $my-alternate-warn: mat-palette($mat-grey);

    $my-alternate-theme: mat-light-theme($my-alternate-primary, $my-alternate-accent, $my-alternate-warn);
    @include angular-material-theme($my-alternate-theme);
}

and dynamic switcher in app.component:

    <router-outlet></router-outlet>

but when changing to dark theme the background color is still white - it does not change whether I set mat-app-background class on div section. Do you know which way should I follow to change this background color?

Body:
Try this :-

Working Stackblitz :- https://stackblitz.com/edit/angular-scss-demo-expsck

<div id="parentContainer" class="mat-app-background" [ngClass]="{'dark-theme': theme.isDark(), 'mat-app-background': true}">
    <router-outlet></router-outlet>
</div>

Also by default body or any div takes height as per its content, if you want to treat it as whole height and width of browser. Add this css :-

 #parentContainer{
     height: 100vh;
     body: 100vw;
     overflow: auto;
  }


问:
Python SQLite Update Function not working
I'm using Python 3.7.5 and SQLite3 3.X as well as Tkinter (but that's irrelevant) and I can't seem to update my table called "Account"

```<code>try:
    Cursor.execute("""CREATE TABLE Account (
        Application text,
        Username text,
        Password text)""")
except sqlite3.OperationalError:
    Cursor.execute("""UPDATE Account SET
        Application = :NewApp,
        Username = :NewUser,
        Password = :NewPass
        WHERE oid = :oid""",
        {"NewApp": NewApplicationE.get(),
         "NewUser": NewUsernameE.get(),
         "NewPass": NewPasswordE.get(),
         "oid": X[3]
        })

</code>```

The try bit is just to create the table if there's not already one and if there is it goes on to update the table
I know for a fact there's columns called Application, Username, Password and the variable.get() all returns the proper string
The oid being X[3] gives you an integer

The program runs but it doesn't actually seem to update anything.
Any help with the formatting or just in general would be appreciated

答:
I think that you need just commit your change
I assume that you get cursor from a connectio,
For instance something like that should work:

```<code>import sqlite3
conn = sqlite3.connect('example.db')c = conn.cursor()
Cursor = conn.cursor()
try:
    Cursor.execute("""CREATE TABLE Account (
        Application text,
        Username text,
        Password text)""")
     conn.commit()

except sqlite3.OperationalError:
    Cursor.execute("""UPDATE Account SET
        Application = :NewApp,
        Username = :NewUser,
        Password = :NewPass
        WHERE oid = :oid""",
        {"NewApp": NewApplicationE.get(),
         "NewUser": NewUsernameE.get(),
         "NewPass": NewPasswordE.get(),
         "oid": X[3]
        })
        conn.commit()

conn.close()
</code>```

Referece
https://docs.python.org/3/library/sqlite3.html

Body:
I'm using Python 3.7.5 and SQLite3 3.X as well as Tkinter (but that's irrelevant) and I can't seem to update my table called "Account"

try:
    Cursor.execute("""CREATE TABLE Account (
        Application text,
        Username text,
        Password text)""")
except sqlite3.OperationalError:
    Cursor.execute("""UPDATE Account SET
        Application = :NewApp,
        Username = :NewUser,
        Password = :NewPass
        WHERE oid = :oid""",
        {"NewApp": NewApplicationE.get(),
         "NewUser": NewUsernameE.get(),
         "NewPass": NewPasswordE.get(),
         "oid": X[3]
        })

The try bit is just to create the table if there's not already one and if there is it goes on to update the table
I know for a fact there's columns called Application, Username, Password and the variable.get() all returns the proper string
The oid being X[3] gives you an integer

The program runs but it doesn't actually seem to update anything.
Any help with the formatting or just in general would be appreciated

Body:
I think that you need just commit your change
I assume that you get cursor from a connectio,
For instance something like that should work:

import sqlite3
conn = sqlite3.connect('example.db')c = conn.cursor()
Cursor = conn.cursor()
try:
    Cursor.execute("""CREATE TABLE Account (
        Application text,
        Username text,
        Password text)""")
     conn.commit()

except sqlite3.OperationalError:
    Cursor.execute("""UPDATE Account SET
        Application = :NewApp,
        Username = :NewUser,
        Password = :NewPass
        WHERE oid = :oid""",
        {"NewApp": NewApplicationE.get(),
         "NewUser": NewUsernameE.get(),
         "NewPass": NewPasswordE.get(),
         "oid": X[3]
        })
        conn.commit()

conn.close()

Referece
https://docs.python.org/3/library/sqlite3.html


问:
How to obtain data from sub query that has self join?
my table:

```<code>friends(uid_1 int, uid_2 int)
</code>```

This is my query :

```<code>SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a
  join friend b
    on a.uid_1 = b.uid_2;
</code>```

I want to obtain a2 and b1 from query for other purposes

So this query now:

```<code>Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )
</code>```

does not work. How do I obtain certain data from a range of displayed data?

答:
You need  table name alias for the subquery  eg : Select  ... FROM (subquery ) T

then you can refer the subquery content with a fully qualified  name

```<code>    Select T.a2, T.b1
    from (SELECT a.uid_1,a.uid_2 as a2, b.uid_1 as b1, b.uid_2 b2
          from friend a join
               friend b
               on a.uid_1=b.uid_2
         ) T
</code>```

Body:
my table:

friends(uid_1 int, uid_2 int)

This is my query :

SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a
  join friend b
    on a.uid_1 = b.uid_2;

I want to obtain a2 and b1 from query for other purposes

So this query now:

Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )

does not work. How do I obtain certain data from a range of displayed data?

Body:
You need  table name alias for the subquery  eg : Select  ... FROM (subquery ) T

then you can refer the subquery content with a fully qualified  name

    Select T.a2, T.b1
    from (SELECT a.uid_1,a.uid_2 as a2, b.uid_1 as b1, b.uid_2 b2
          from friend a join
               friend b
               on a.uid_1=b.uid_2
         ) T


问:
kubernetes - Couldn't able to join master node - error execution phase preflight: couldn't validate the identity of the API Server
I am novice to k8s, so this might be very simple issue for someone with expertise in the k8s.

I am working with two nodes

master - 2cpu, 2 GB memory

worker - 1 cpu, 1 GB memory

OS - ubuntu - hashicorp/bionic64

I did setup the master node successfully and i can see it is up and running

```<code>vagrant@master:~$ kubectl get nodes
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   29m   v1.18.2
</code>```

Here is token which i have generated

```<code>vagrant@master:~$ kubeadm token create --print-join-command
W0419 13:45:52.513532   16403 configset.go:202] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
kubeadm join 10.0.2.15:6443 --token xuz63z.todnwgijqb3z1vhz     --discovery-token-ca-cert-hash sha256:d4dadda6fa90c94eca1c8dcd3a441af24bb0727ffc45c0c27161ee8f7e883521
</code>```

Issue - But when i try to join it from the worker node i get

```<code>vagrant@worker:~$ sudo kubeadm join 10.0.2.15:6443 --token xuz63z.todnwgijqb3z1vhz     --discovery-token-ca-cert-hash sha256:d4dadda6fa90c94eca1c8dcd3a441af24bb0727ffc45c0c27161ee8f7e883521
W0419 13:46:17.651819   15987 join.go:346] [preflight] WARNING: JoinControlPane.controlPlane settings will be ignored when control-plane flag is not set.
[preflight] Running pre-flight checks
        [WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". Please follow the guide at https://kubernetes.io/docs/setup/cri/
error execution phase preflight: couldn't validate the identity of the API Server: Get https://10.0.2.15:6443/api/v1/namespaces/kube-public/configmaps/cluster-info?timeout=10s: dial tcp 10.0.2.15:6443: connect: connection refused
To see the stack trace of this error execute with --v=5 or higher
</code>```

Here are the ports which are occupied

```<code>10.0.2.15:2379
10.0.2.15:2380
10.0.2.15:68
</code>```

Note i am using CNI from -

```<code>kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
</code>```

答:
I ran into similar issue, problem was my node VM's timezone was different. Corrected the time on node and it worked!

Hope it may help someone.

Body:
I am novice to k8s, so this might be very simple issue for someone with expertise in the k8s.

I am working with two nodes

master - 2cpu, 2 GB memory

worker - 1 cpu, 1 GB memory

OS - ubuntu - hashicorp/bionic64

I did setup the master node successfully and i can see it is up and running

vagrant@master:~$ kubectl get nodes
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   29m   v1.18.2

Here is token which i have generated

vagrant@master:~$ kubeadm token create --print-join-command
W0419 13:45:52.513532   16403 configset.go:202] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
kubeadm join 10.0.2.15:6443 --token xuz63z.todnwgijqb3z1vhz     --discovery-token-ca-cert-hash sha256:d4dadda6fa90c94eca1c8dcd3a441af24bb0727ffc45c0c27161ee8f7e883521

Issue - But when i try to join it from the worker node i get

vagrant@worker:~$ sudo kubeadm join 10.0.2.15:6443 --token xuz63z.todnwgijqb3z1vhz     --discovery-token-ca-cert-hash sha256:d4dadda6fa90c94eca1c8dcd3a441af24bb0727ffc45c0c27161ee8f7e883521
W0419 13:46:17.651819   15987 join.go:346] [preflight] WARNING: JoinControlPane.controlPlane settings will be ignored when control-plane flag is not set.
[preflight] Running pre-flight checks
        [WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". Please follow the guide at https://kubernetes.io/docs/setup/cri/
error execution phase preflight: couldn't validate the identity of the API Server: Get https://10.0.2.15:6443/api/v1/namespaces/kube-public/configmaps/cluster-info?timeout=10s: dial tcp 10.0.2.15:6443: connect: connection refused
To see the stack trace of this error execute with --v=5 or higher

Here are the ports which are occupied

10.0.2.15:2379
10.0.2.15:2380
10.0.2.15:68

Note i am using CNI from -

kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml


问:
React-table: State doesn't change as expected, and table doesn't update
Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

I am using the react-table package (version 7.1.0).

I have a table which displays some invoices like so:

The user should be able to select some or all of these items using the selected checkbox.

The selected field is not part of the data. However, when the user hits a selected checkbox, the field should toggle and an array storing document numbers should be populated.

To store the document numbers, I have a stateful getter and setter:

```<code>const [selectedInvoiceIds, setSelectedInvoiceIds] = useState([]);
</code>```

To populate the field, I am attempting to simply add the document number to the array immutably, from the onChange of the checkbox:

```<code>      {
        Header: "Selected",
        accessor: "selected",
        Cell: item => {
          const { documentNumber } = item.row.values;
          return (
            <input
              type="checkbox"
              checked={selectedInvoiceIds.includes(documentNumber)}
              onChange={() => {
                setSelectedInvoiceIds([...selectedInvoiceIds, documentNumber]);
              }}
            />
          );
        }
      }
</code>```

When a checkbox is clicked for the first time, the selectedInvoiceIds becomes populated:

```<code>selectedInvoiceIds: ["706942"]
</code>```

The problems are:

The table does not update to reflect the state change, despite this prop on the checkbox:

```<code>checked={selectedInvoiceIds.includes(documentNumber)}
</code>```

The selectedInvoiceIds value gets overwritten when another document number is added, instead of being added to, as if the state is re-initialising to [] somewhere in between.

Can it be explained why these state issues are occurring and how to get around it?

I am aware of the useTableState value exposed by react-table, but I don't know how I can apply it to this use case.

Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

答:
Because of useMemo, add your array to last parameter

```<code>const columns = React.useMemo(
// ....
,
[selectedInvoiceIds]
  );
</code>```

And as we need toggle checkboxed it is more reasonable to keep selected ids in object instead of array and update it as this

```<code>setSelectedInvoices({
  ...selectedInovicesIds,
  documentNumber: !selectedInovicesIds[documentNumber]}
)
</code>```

so it will toggle mark

Body:
Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

I am using the react-table package (version 7.1.0).

I have a table which displays some invoices like so:

The user should be able to select some or all of these items using the selected checkbox.

The selected field is not part of the data. However, when the user hits a selected checkbox, the field should toggle and an array storing document numbers should be populated.

To store the document numbers, I have a stateful getter and setter:

const [selectedInvoiceIds, setSelectedInvoiceIds] = useState([]);

To populate the field, I am attempting to simply add the document number to the array immutably, from the onChange of the checkbox:

      {
        Header: "Selected",
        accessor: "selected",
        Cell: item => {
          const { documentNumber } = item.row.values;
          return (
            <input
              type="checkbox"
              checked={selectedInvoiceIds.includes(documentNumber)}
              onChange={() => {
                setSelectedInvoiceIds([...selectedInvoiceIds, documentNumber]);
              }}
            />
          );
        }
      }

When a checkbox is clicked for the first time, the selectedInvoiceIds becomes populated:

selectedInvoiceIds: ["706942"]

The problems are:

The table does not update to reflect the state change, despite this prop on the checkbox:

checked={selectedInvoiceIds.includes(documentNumber)}

The selectedInvoiceIds value gets overwritten when another document number is added, instead of being added to, as if the state is re-initialising to [] somewhere in between.

Can it be explained why these state issues are occurring and how to get around it?

I am aware of the useTableState value exposed by react-table, but I don't know how I can apply it to this use case.

Codesandbox example: https://codesandbox.io/s/react-table-state-not-updating-hmquq?file=/src/App.js

Body:
Because of useMemo, add your array to last parameter

const columns = React.useMemo(
// ....
,
[selectedInvoiceIds]
  );

And as we need toggle checkboxed it is more reasonable to keep selected ids in object instead of array and update it as this

setSelectedInvoices({
  ...selectedInovicesIds,
  documentNumber: !selectedInovicesIds[documentNumber]}
)

so it will toggle mark


问:
How do I fix my XSLT to correctly translate XML to HTML as expected?
I am using XSLT to translate XML to HTML.

The XML is:

```<code><PARA>
    1050
    <EMPH STYLE="min_max">
        <EMPH HL="LOW">-50</EMPH>
        <EMPH HL="HIGH">+50</EMPH>
    </EMPH>
     min
    <EMPH BOLD="0" HL="HIGH" ITAL="0" SMALLCAPS="0">-1</EMPH>
</PARA>
</code>```

How I do correctly render the output as:

1050 -50 +50 min-1

Currently I am getting 1050  min -50 +50 -1

My XSLT is:

```<code><xsl:template match="PARA">
    <xsl:value-of select="text()"/>
    <xsl:choose>
        <xsl:when test="EMPH">
            <xsl:apply-templates select="EMPH"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

<xsl:template match="EMPH">
    <xsl:choose>
        <xsl:when test="@BOLD=1"><b><xsl:value-of select="."/></b></xsl:when>
        <xsl:when test="@HL='HIGH'"><sup><xsl:value-of select="."/></sup></xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

答:
I would try to process the attributes with a recursive template and keep the mapping from attribute names to HTML elements in a map (in XSLT as supported since Saxon 9.8 you can use an XPath 3.1 map but in XSLT 2 if you need to use that rather old version of Saxon you can of course define some variable holding an XML structure mapping the names e.g. <map><att name="BOLD">b</att></map>):

```<code>  <xsl:param name="att-map" as="map(xs:string, xs:string)"
    select="map { 'BOLD' : 'b', 'HL' : 'sup', 'ITAL' : 'i' }"/>

  <xsl:template match="PARA">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="EMPH[@STYLE = 'min_max']/EMPH">
      <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="EMPH">
      <xsl:param name="atts" select="@*[. = ('1', 'HIGH')]"/>
      <xsl:choose>
          <xsl:when test="head($atts)">
              <xsl:element name="{$att-map(local-name(head($atts)))}">
                  <xsl:apply-templates select=".">
                      <xsl:with-param name="atts" select="tail($atts)"/>
                  </xsl:apply-templates>
              </xsl:element>
          </xsl:when>
          <xsl:otherwise>
              <xsl:apply-templates/>
          </xsl:otherwise>
      </xsl:choose>
  </xsl:template>
</code>```

https://xsltfiddle.liberty-development.net/jxDjims/1

I have also used XSLT/XPath 3 functions head and tail there but you can of course use XPath 2 subsequence equivalents or $atts[1] and $atts[position() gt 1].

Another option would be to write templates for the attributes you want to transform:

```<code>  <xsl:param name="att-map" as="map(xs:string, xs:string)"
    select="map { 'BOLD' : 'b', 'HL' : 'sup', 'ITAL' : 'i' }"/>

  <xsl:template match="PARA">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="EMPH[@STYLE = 'min_max']/EMPH" priority="5">
      <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="@BOLD[. = 1] | @ITAL[. = 1] | @HL[. = 'HIGH']">
      <xsl:param name="atts"/>
      <xsl:element name="{$att-map(local-name())}">
          <xsl:choose>
              <xsl:when test="$atts">
                  <xsl:apply-templates select="head($atts)">
                      <xsl:with-param name="atts" select="tail($atts)"/>
                  </xsl:apply-templates>
              </xsl:when>
              <xsl:otherwise>
                  <xsl:apply-templates select="../node()"/>
              </xsl:otherwise>
          </xsl:choose>
      </xsl:element>
  </xsl:template>

  <xsl:template match="EMPH[@*[. = ('1', 'HIGH')]]">
      <xsl:apply-templates select="head(@*[. = ('1', 'HIGH')])">
          <xsl:with-param name="atts" select="tail(@*[. = ('1', 'HIGH')])"/>
      </xsl:apply-templates>
  </xsl:template>

  <xsl:mode on-no-match="text-only-copy"/>
</code>```

https://xsltfiddle.liberty-development.net/jxDjims/2

As I guess the SMALLCAPPS can't be transformed with a simple attribute to element name map it might also help to write some more templates to allow for more flexibility, the following uses a base template for the recursive processing, it is called with <xsl:next-match/> by other, more specialized templates describing the transformation of attributes to elements:

```<code>  <xsl:param name="att-map" as="map(xs:string, xs:string)"
    select="map { 'BOLD' : 'b', 'HL' : 'sup', 'ITAL' : 'i' }"/>

  <xsl:template match="PARA">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="EMPH[@STYLE = 'min_max']/EMPH" priority="5">
      <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="@BOLD[. = 1] | @ITAL[. = 1] | @HL[. = 'HIGH']" mode="attributes-to-elements">
      <xsl:element name="{$att-map(local-name())}">
          <xsl:next-match/>
      </xsl:element>
  </xsl:template>

  <xsl:template match="@SMALLCAPS[. = 1]" mode="attributes-to-elements">
      <span style="font-variant: small-caps">
          <xsl:next-match/>
      </span>
  </xsl:template>

  <xsl:template match="@*" mode="attributes-to-elements">
      <xsl:param name="remaining-atts" tunnel="yes"/>
      <xsl:choose>
          <xsl:when test="$remaining-atts">
              <xsl:apply-templates select="head($remaining-atts)" mode="#current">
                  <xsl:with-param name="remaining-atts" tunnel="yes" select="tail($remaining-atts)"/>
              </xsl:apply-templates>
          </xsl:when>
          <xsl:otherwise>
              <xsl:apply-templates select="../node()"/>
          </xsl:otherwise>
      </xsl:choose>
  </xsl:template>

  <xsl:template match="EMPH[@*[. = ('1', 'HIGH')]]">
      <xsl:apply-templates select="head(@*[. = ('1', 'HIGH')])" mode="attributes-to-elements">
          <xsl:with-param name="remaining-atts" tunnel="yes" select="tail(@*[. = ('1', 'HIGH')])"/>
      </xsl:apply-templates>
  </xsl:template>
</code>```

https://xsltfiddle.liberty-development.net/jxDjims/3

In the end it might be simpler to do a two step transformation that first normalizes the input you have to strip any attributes not indicating some special HTML styling or wrapping and also to transform the attributes to normalized elements, then the second step can more easily use normal, elements-based apply-templates to simply transform the nested input to nested HTML.

Body:
I am using XSLT to translate XML to HTML.

The XML is:

<PARA>
    1050
    <EMPH STYLE="min_max">
        <EMPH HL="LOW">-50</EMPH>
        <EMPH HL="HIGH">+50</EMPH>
    </EMPH>
     min
    <EMPH BOLD="0" HL="HIGH" ITAL="0" SMALLCAPS="0">-1</EMPH>
</PARA>

How I do correctly render the output as:

1050 -50 +50 min-1

Currently I am getting 1050  min -50 +50 -1

My XSLT is:

<xsl:template match="PARA">
    <xsl:value-of select="text()"/>
    <xsl:choose>
        <xsl:when test="EMPH">
            <xsl:apply-templates select="EMPH"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

<xsl:template match="EMPH">
    <xsl:choose>
        <xsl:when test="@BOLD=1"><xsl:value-of select="."/></xsl:when>
        <xsl:when test="@HL='HIGH'"><xsl:value-of select="."/></xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Body:
I would try to process the attributes with a recursive template and keep the mapping from attribute names to HTML elements in a map (in XSLT as supported since Saxon 9.8 you can use an XPath 3.1 map but in XSLT 2 if you need to use that rather old version of Saxon you can of course define some variable holding an XML structure mapping the names e.g. <map><att name="BOLD">b</att></map>):

  <xsl:param name="att-map" as="map(xs:string, xs:string)"
    select="map { 'BOLD' : 'b', 'HL' : 'sup', 'ITAL' : 'i' }"/>

  <xsl:template match="PARA">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="EMPH[@STYLE = 'min_max']/EMPH">
      <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="EMPH">
      <xsl:param name="atts" select="@*[. = ('1', 'HIGH')]"/>
      <xsl:choose>
          <xsl:when test="head($atts)">
              <xsl:element name="{$att-map(local-name(head($atts)))}">
                  <xsl:apply-templates select=".">
                      <xsl:with-param name="atts" select="tail($atts)"/>
                  </xsl:apply-templates>
              </xsl:element>
          </xsl:when>
          <xsl:otherwise>
              <xsl:apply-templates/>
          </xsl:otherwise>
      </xsl:choose>
  </xsl:template>

https://xsltfiddle.liberty-development.net/jxDjims/1

I have also used XSLT/XPath 3 functions head and tail there but you can of course use XPath 2 subsequence equivalents or $atts[1] and $atts[position() gt 1].

Another option would be to write templates for the attributes you want to transform:

  <xsl:param name="att-map" as="map(xs:string, xs:string)"
    select="map { 'BOLD' : 'b', 'HL' : 'sup', 'ITAL' : 'i' }"/>

  <xsl:template match="PARA">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="EMPH[@STYLE = 'min_max']/EMPH" priority="5">
      <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="@BOLD[. = 1] | @ITAL[. = 1] | @HL[. = 'HIGH']">
      <xsl:param name="atts"/>
      <xsl:element name="{$att-map(local-name())}">
          <xsl:choose>
              <xsl:when test="$atts">
                  <xsl:apply-templates select="head($atts)">
                      <xsl:with-param name="atts" select="tail($atts)"/>
                  </xsl:apply-templates>
              </xsl:when>
              <xsl:otherwise>
                  <xsl:apply-templates select="../node()"/>
              </xsl:otherwise>
          </xsl:choose>
      </xsl:element>
  </xsl:template>

  <xsl:template match="EMPH[@*[. = ('1', 'HIGH')]]">
      <xsl:apply-templates select="head(@*[. = ('1', 'HIGH')])">
          <xsl:with-param name="atts" select="tail(@*[. = ('1', 'HIGH')])"/>
      </xsl:apply-templates>
  </xsl:template>

  <xsl:mode on-no-match="text-only-copy"/>

https://xsltfiddle.liberty-development.net/jxDjims/2

As I guess the SMALLCAPPS can't be transformed with a simple attribute to element name map it might also help to write some more templates to allow for more flexibility, the following uses a base template for the recursive processing, it is called with <xsl:next-match/> by other, more specialized templates describing the transformation of attributes to elements:

  <xsl:param name="att-map" as="map(xs:string, xs:string)"
    select="map { 'BOLD' : 'b', 'HL' : 'sup', 'ITAL' : 'i' }"/>

  <xsl:template match="PARA">
      <p>
          <xsl:apply-templates/>
      </p>
  </xsl:template>

  <xsl:template match="EMPH[@STYLE = 'min_max']/EMPH" priority="5">
      <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="@BOLD[. = 1] | @ITAL[. = 1] | @HL[. = 'HIGH']" mode="attributes-to-elements">
      <xsl:element name="{$att-map(local-name())}">
          <xsl:next-match/>
      </xsl:element>
  </xsl:template>

  <xsl:template match="@SMALLCAPS[. = 1]" mode="attributes-to-elements">
      <span style="font-variant: small-caps">
          <xsl:next-match/>
      </span>
  </xsl:template>

  <xsl:template match="@*" mode="attributes-to-elements">
      <xsl:param name="remaining-atts" tunnel="yes"/>
      <xsl:choose>
          <xsl:when test="$remaining-atts">
              <xsl:apply-templates select="head($remaining-atts)" mode="#current">
                  <xsl:with-param name="remaining-atts" tunnel="yes" select="tail($remaining-atts)"/>
              </xsl:apply-templates>
          </xsl:when>
          <xsl:otherwise>
              <xsl:apply-templates select="../node()"/>
          </xsl:otherwise>
      </xsl:choose>
  </xsl:template>

  <xsl:template match="EMPH[@*[. = ('1', 'HIGH')]]">
      <xsl:apply-templates select="head(@*[. = ('1', 'HIGH')])" mode="attributes-to-elements">
          <xsl:with-param name="remaining-atts" tunnel="yes" select="tail(@*[. = ('1', 'HIGH')])"/>
      </xsl:apply-templates>
  </xsl:template>

https://xsltfiddle.liberty-development.net/jxDjims/3

In the end it might be simpler to do a two step transformation that first normalizes the input you have to strip any attributes not indicating some special HTML styling or wrapping and also to transform the attributes to normalized elements, then the second step can more easily use normal, elements-based apply-templates to simply transform the nested input to nested HTML.


问:
Display js array acquired via JSON to webpage
Sorry if causing troubles again =x

With the help from you guys especially Scott Harwell,  I managed to get my php array passed to js array with the following code:

```<code>var horse_array = <?php echo json_encode($horse_info);?>;
</code>```

However, now I encounter problem in displaying the content of array. I could not load it into my html tag with id="horse1_r".

The following is my js code:

```<code><script type="text/javascript">

var horse_array = <?php echo json_encode($horse_info);?>;

function goto1(hid) {

$("#horse1_r").html(horse_array);

}

</script>
</code>```

Your kind help will be much appreciated.

答:
The first thing is that I don't see the function goto1 being called. With jQuery you will have to run it in document.ready:

```<code><script type="text/javascript">
var horse_array = <?php echo json_encode($horse_info);?>;

$(document).ready(function() {

$("#horse1_r").html(horse_array);

});
</script>
</code>```

Now the second thing is that horse_array will be an array containing maybe other arrays (or objects in JavaScript for that matter). You will have to loop through these arrays and objects and output it's properties the way you want them to.

ContentLicense: CC BY-SA 3.0

Body:
Sorry if causing troubles again =x

With the help from you guys especially Scott Harwell,  I managed to get my php array passed to js array with the following code:

var horse_array = <?php echo json_encode($horse_info);?>;

However, now I encounter problem in displaying the content of array. I could not load it into my html tag with id="horse1_r".

The following is my js code:

Your kind help will be much appreciated.

Body:
The first thing is that I don't see the function goto1 being called. With jQuery you will have to run it in document.ready:

<script type="text/javascript">
var horse_array = <?php echo json_encode($horse_info);?>;

$(document).ready(function() {

$("#horse1_r").html(horse_array);

});
</script>

Now the second thing is that horse_array will be an array containing maybe other arrays (or objects in JavaScript for that matter). You will have to loop through these arrays and objects and output it's properties the way you want them to.


问:
how to resolve async s3 resolver upload on nodejs + graphql?
what i want to do is upload the image first the save the link to a user in db.

This is my graphql resolver:

```<code>resolve: async (_root, args, { user, prisma }) => {

        ....

        const params = {
          Bucket: s3BucketName,
          Key: fileName,
          ACL: 'public-read',
          Body: file.createReadStream(),
          ContentType: file.mimetype,
        };
        return s3.putObject(params, async function (error, data) {
          if (error) {
            return {
              message: error,
              success: false,
            };
          } else {
            // user has updated
            if (user.profileImg)
              return prisma.user
                .update({
                  where: { id: Number(user.id) },
                  data: {
                    profileImg: fileName,
                  },
                })
                .then(
                  (response) => {
                    console.log('response: ', response);
                    return {
                      message: 'Success',
                      success: true,
                    };
                  },
                  (error) => {
                    return {
                      message: error,
                      success: false,
                    };
                  }
                );
            else {
              return {
                message: 'Success',
                success: true,
              };
            }
          }
        });
      },
</code>```

what i want to do is return from s3, but my problem is i think it returns without this resolving and returns null so emmage and success is not returned. how do i construct a function resolver using s3?

答:
You should return new Promise from your resolver, instead of making it async this way you can explicitly resolve() or reject() from within the nested callback.

resolve: (_root, args, { user, prisma }) => {
  return new Promise((resolve, reject) => {
    s3.putObject(params, async (error, data) => {

      if (error) {
        return reject({
          message: error.message,
          success: false
        });
      }

      try {
        await prisma.user.update();

        return resolve({
          message: "Success",
          success: true
        });
      } catch (e) {
        return reject({
          message: e.message,
          success: false
        });
      }

    });
  });
};
```

<p>If you wanted to stay in the <code>async/await</code> paradigm, make a utility/promise-wrapper around <code>s3.putObject</code>;</p>

<pre class="lang-js prettyprint-override"><code>function putObject(...params) {
  return new Promise((resolve, reject) => {
    s3.putObject(...params, async (error, data) => {
      if (error) {
        return reject(error);
      }

      return resolve(data);
    });
  });
}

resolve: async (_root, args, { user, prisma }) => {
  try {
    const response = await putObject(params);

    await prisma.user.update();

    return {
      message: "Success",
      success: true
    };
  } catch (error) {
    return {
      message: error.message,
      success: false
    };
  }
};
</code>```

Body:
what i want to do is upload the image first the save the link to a user in db.

This is my graphql resolver:

resolve: async (_root, args, { user, prisma }) => {

        ....

        const params = {
          Bucket: s3BucketName,
          Key: fileName,
          ACL: 'public-read',
          Body: file.createReadStream(),
          ContentType: file.mimetype,
        };
        return s3.putObject(params, async function (error, data) {
          if (error) {
            return {
              message: error,
              success: false,
            };
          } else {
            // user has updated
            if (user.profileImg)
              return prisma.user
                .update({
                  where: { id: Number(user.id) },
                  data: {
                    profileImg: fileName,
                  },
                })
                .then(
                  (response) => {
                    console.log('response: ', response);
                    return {
                      message: 'Success',
                      success: true,
                    };
                  },
                  (error) => {
                    return {
                      message: error,
                      success: false,
                    };
                  }
                );
            else {
              return {
                message: 'Success',
                success: true,
              };
            }
          }
        });
      },

what i want to do is return from s3, but my problem is i think it returns without this resolving and returns null so emmage and success is not returned. how do i construct a function resolver using s3?

Body:
You should return new Promise from your resolver, instead of making it async this way you can explicitly resolve() or reject() from within the nested callback.

resolve: (_root, args, { user, prisma }) => {
  return new Promise((resolve, reject) => {
    s3.putObject(params, async (error, data) => {

      if (error) {
        return reject({
          message: error.message,
          success: false
        });
      }

      try {
        await prisma.user.update();

        return resolve({
          message: "Success",
          success: true
        });
      } catch (e) {
        return reject({
          message: e.message,
          success: false
        });
      }

    });
  });
};

If you wanted to stay in the async/await paradigm, make a utility/promise-wrapper around s3.putObject;

function putObject(...params) {
  return new Promise((resolve, reject) => {
    s3.putObject(...params, async (error, data) => {
      if (error) {
        return reject(error);
      }

      return resolve(data);
    });
  });
}

resolve: async (_root, args, { user, prisma }) => {
  try {
    const response = await putObject(params);

    await prisma.user.update();

    return {
      message: "Success",
      success: true
    };
  } catch (error) {
    return {
      message: error.message,
      success: false
    };
  }
};


问:
Bootstrap 4 DateTimePicker not working. Icons not showing
I'm on Rails 5.2.0. I'm implementing bootstrap datetimepicker with below code:

```<code>  <div class="form-group">
    <div class='input-group date' id='datetimepicker1' data-target-input='nearest'>
      <input type='text' class="form-control datetimepicker-input" data-target="#datetimepicker1" name="params['start_time']" />
      <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
      </div>
    </div>
  </div>
</code>```

Gemfile:

```<code>gem 'momentjs-rails', '~> 2.20', '>= 2.20.1'
gem 'bootstrap', '~> 4.1.1'
gem 'bootstrap4-datetime-picker-rails'
gem 'jquery-rails'
</code>```

application.js

```<code>//= require jquery3
//= require jquery_ujs
//= require turbolinks
//= require popper
//= require moment
//= require bootstrap
//= require tempusdominus-bootstrap-4.js
//= require_tree .
</code>```

application.scss

```<code>@import "bootstrap";
@import "tempusdominus-bootstrap-4.css";
</code>```

I'm encoutering a problem where no icons are showing up on the page for the datetimepicker.

Attached is the screenshot for reference. Can anyone please point out any fault here?

Thanks in advance.

答:
I have updated the default setting of icons prop of DateTimePicker by below code, then it is working fine for me</p>

```<code>$.extend(true, $.fn.datetimepicker.defaults, {
                icons: {
                    time: 'far fa-clock',
                    date: 'far fa-calendar',
                    up: 'fas fa-arrow-up',
                    down: 'fas fa-arrow-down',
                    previous: 'fas fa-chevron-left',
                    next: 'fas fa-chevron-right',
                    today: 'fas fa-calendar-check',
                    clear: 'far fa-trash-alt',
                    close: 'far fa-times-circle'
                }
            });
</code>```

Body:
I'm on Rails 5.2.0. I'm implementing bootstrap datetimepicker with below code:

      <input type='text' class="form-control datetimepicker-input" data-target="#datetimepicker1" name="params['start_time']" />

Gemfile:

gem 'momentjs-rails', '~> 2.20', '>= 2.20.1'
gem 'bootstrap', '~> 4.1.1'
gem 'bootstrap4-datetime-picker-rails'
gem 'jquery-rails'

application.js

//= require jquery3
//= require jquery_ujs
//= require turbolinks
//= require popper
//= require moment
//= require bootstrap
//= require tempusdominus-bootstrap-4.js
//= require_tree .

application.scss

@import "bootstrap";
@import "tempusdominus-bootstrap-4.css";

I'm encoutering a problem where no icons are showing up on the page for the datetimepicker.

Attached is the screenshot for reference. Can anyone please point out any fault here?

Thanks in advance.

Body:
I have updated the default setting of icons prop of DateTimePicker by below code, then it is working fine for me

$.extend(true, $.fn.datetimepicker.defaults, {
                icons: {
                    time: 'far fa-clock',
                    date: 'far fa-calendar',
                    up: 'fas fa-arrow-up',
                    down: 'fas fa-arrow-down',
                    previous: 'fas fa-chevron-left',
                    next: 'fas fa-chevron-right',
                    today: 'fas fa-calendar-check',
                    clear: 'far fa-trash-alt',
                    close: 'far fa-times-circle'
                }
            });


问:
Syntax when pattern matching with tuples (Elixir)
I'm following a tutorial and there's a basic syntax issue that I'm not sure about.

Sometimes when we are pattern matching (in say function arguments), we use = and match the left to the right.

However, at times I see -> being used instead of =. For example this code:

receive do {:result, filename} -> filename do

I'm assuming this is wrong:

receive do {:result, filename} = filename do

Does this have to do with an anonymous function? Or maybe a special syntax for tuples(which are basically maps?).

答:
Does this have to do with an anonymous function?

Nope.

Or maybe a special syntax for tuples(which are basically maps?)

Not at all :)

= is a match operator, meaning RHO must match LHO, otherwise, MatchError is raised.

{:ok, _} = {:ok, 42}
#⇒ {:ok, 42}

{:ok, _} = :error
** (MatchError) no match of right hand side value: :error
```

<p><code>-></code> should be read as <em>“if somewhat from the outer scope, depending on context, is matched to LHO, evaluate RHO.”</em></p>

<pre class="lang-rb prettyprint-override"><code>case :error do
  {:ok, _} -> :never_reached
  _ -> :we_matched_error_through_match_all_clause
end
#⇒ :we_matched_error_through_match_all_clause
</code>```

¡NB! Please note (credits to Diego Echeverri for mentioning this in comments) that if no one clause succeeded to match in the -> example, MatchError is thrown. So = might be treated as match exactly this! and -> as match at least one of these and do what is stated on the right side of ->.

Sidenote: “tuples which are basically maps” tuples are by no mean maps.

Body:
Does this have to do with an anonymous function?

Nope.

Or maybe a special syntax for tuples(which are basically maps?)

Not at all :)

= is a match operator, meaning RHO must match LHO, otherwise, MatchError is raised.

{:ok, _} = {:ok, 42}
#⇒ {:ok, 42}

{:ok, _} = :error
** (MatchError) no match of right hand side value: :error

-> should be read as “if somewhat from the outer scope, depending on context, is matched to LHO, evaluate RHO.”

case :error do
  {:ok, _} -> :never_reached
  _ -> :we_matched_error_through_match_all_clause
end
#⇒ :we_matched_error_through_match_all_clause

¡NB! Please note (credits to Diego Echeverri for mentioning this in comments) that if no one clause succeeded to match in the -> example, MatchError is thrown. So = might be treated as match exactly this! and -> as match at least one of these and do what is stated on the right side of ->.

Sidenote: “tuples which are basically maps” tuples are by no mean maps.


问:
Sum values in a list of lists of dictionaries using common key-value pairs
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

```<code>data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]
</code>```

Expected output:

```<code>op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]
</code>```

答:
```<code>data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

keyname = "user"

all = []
for row in data:
    row_out = []
    for d in row:
        key = d[keyname]
        for d2 in row_out:
            if d2[keyname] == d[keyname]:
                break
        else:
            d2 = {keyname: key}
            row_out.append(d2)
        for k, v in d.items():
            if k == keyname:
                continue
            d2[k] = d2.get(k, 0) + v
    all.append(row_out)

print(all)
</code>```

gives:

```<code>[[{'user': 1, 'rating': 20}, {'user': 2, 'rating': 10}, {'user': 3, 'rating': 10}], [{'user': 4, 'rating': 4}, {'user': 2, 'rating': 80}, {'user': 1, 'rating': 30}]]
</code>```

Body:
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

Expected output:

op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]

Body:
data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

keyname = "user"

all = []
for row in data:
    row_out = []
    for d in row:
        key = d[keyname]
        for d2 in row_out:
            if d2[keyname] == d[keyname]:
                break
        else:
            d2 = {keyname: key}
            row_out.append(d2)
        for k, v in d.items():
            if k == keyname:
                continue
            d2[k] = d2.get(k, 0) + v
    all.append(row_out)

print(all)

gives:

[[{'user': 1, 'rating': 20}, {'user': 2, 'rating': 10}, {'user': 3, 'rating': 10}], [{'user': 4, 'rating': 4}, {'user': 2, 'rating': 80}, {'user': 1, 'rating': 30}]]


问:
Web scraping with R: web site has two drop down menus
I want to get grade data from the following web site using R's for loop function: https://www7.nau.edu/pair/reports/ClassDistribution

In order to get the table data I have to first choose year and then academic school. I need data for 2015-2019 and for all schools (ACC, ACM,...,WGS) within university. When I select year and school the url is not changing that is why I am getting no table data. I'd really appreciate your help and advice. I am able to create for loop, I just need to see how to pull first table.

I was using following code for a static web site:

```<code>library(XML)
library(RCurl)
url <- "https://www7.nau.edu/pair/reports/ClassDistribution"
url.parsed <- htmlParse(getURL(url), asText = TRUE)
tableNodes <- getNodeSet(url.parsed, '//*[@id="pp_table"]/table')
grade_data <- readHTMLTable(tableNodes[[1]], header=F, stringsAsFactors=F)
</code>```

答:
Here is a solution using RSelenium.

```<code>library(RSelenium)

rD <- rsDriver(browser = c("firefox")) #specify browser type you want Selenium to open
remDr <- rD$client
remDr$navigate("https://www7.nau.edu/pair/reports/ClassDistribution") # navigates to webpage

# select first dropdown list
option <- remDr$findElement(using='id', value="MainContent_TermList")

#get all option values from dropdown list
option_values <- option$getPageSource()[[1]] %>%
  str_extract_all("1[0-9]{3}")

#select second dropdown list
option2 <- remDr$findElement(using='id', value="MainContent_SubjectList")

#get all option values from dropdown list
option_values_2 <- option2$getElementText() %>%
  str_split("\\n") %>%
  unlist()

#### create loop to loop over all tables...

option <- remDr$findElement(using='id', value="MainContent_TermList")

option <- remDr$findElement(using = 'xpath', "//*/option[@value = '1194']") #change '1194' to values in option_values in loop
option$clickElement()

# change dropdown selection
option2 <- remDr$findElement(using='id', value="MainContent_SubjectList")
option2 <- remDr$findElement(using = 'xpath', "//*/option[@value = 'AHB']") #change 'AHB' to values in option_values_2 in loop
option2$clickElement()

# click submit
submit <- remDr$findElement(using='id', value="MainContent_Button1")
submit$clickElement()

#get table
tb <- remDr$findElement(using='id', value="MainContent_GridView1")

tb$getPageSource()[[1]] %>%
  read_html() %>%
  html_table(fill = TRUE)

</code>```

Now you just have to loop over option_values and option_values2 to get the tables.

Body:
I want to get grade data from the following web site using R's for loop function: https://www7.nau.edu/pair/reports/ClassDistribution

In order to get the table data I have to first choose year and then academic school. I need data for 2015-2019 and for all schools (ACC, ACM,...,WGS) within university. When I select year and school the url is not changing that is why I am getting no table data. I'd really appreciate your help and advice. I am able to create for loop, I just need to see how to pull first table.

I was using following code for a static web site:

library(XML)
library(RCurl)
url <- "https://www7.nau.edu/pair/reports/ClassDistribution"
url.parsed <- htmlParse(getURL(url), asText = TRUE)
tableNodes <- getNodeSet(url.parsed, '//*[@id="pp_table"]/table')
grade_data <- readHTMLTable(tableNodes[[1]], header=F, stringsAsFactors=F)

Body:
Here is a solution using RSelenium.

library(RSelenium)

rD <- rsDriver(browser = c("firefox")) #specify browser type you want Selenium to open
remDr <- rD$client
remDr$navigate("https://www7.nau.edu/pair/reports/ClassDistribution") # navigates to webpage

# select first dropdown list
option <- remDr$findElement(using='id', value="MainContent_TermList")

#get all option values from dropdown list
option_values <- option$getPageSource()[[1]] %>%
  str_extract_all("1[0-9]{3}")

#select second dropdown list
option2 <- remDr$findElement(using='id', value="MainContent_SubjectList")

#get all option values from dropdown list
option_values_2 <- option2$getElementText() %>%
  str_split("\\n") %>%
  unlist()

#### create loop to loop over all tables...

option <- remDr$findElement(using='id', value="MainContent_TermList")

option <- remDr$findElement(using = 'xpath', "//*/option[@value = '1194']") #change '1194' to values in option_values in loop
option$clickElement()

# change dropdown selection
option2 <- remDr$findElement(using='id', value="MainContent_SubjectList")
option2 <- remDr$findElement(using = 'xpath', "//*/option[@value = 'AHB']") #change 'AHB' to values in option_values_2 in loop
option2$clickElement()

# click submit
submit <- remDr$findElement(using='id', value="MainContent_Button1")
submit$clickElement()

#get table
tb <- remDr$findElement(using='id', value="MainContent_GridView1")

tb$getPageSource()[[1]] %>%
  read_html() %>%
  html_table(fill = TRUE)

Now you just have to loop over option_values and option_values2 to get the tables.


答:
Sorting should be avoided because each item can be processed in a single pass. Any hash based technique should be better.

Here's an alternate solution, that uses a defaultdict instead of expensive sort/groupby or pandas.

```<code>from collections import defaultdict
from functools import reduce

def reduce_func(state, item):
  new_obj = {
    "user": item["user"],
    "rating": state[item["user"]]["rating"] + item["rating"]}
  }
  state[item["user"]] = new_obj
  return state

output = [list(reduce(reduce_func, elem, defaultdict(lambda: {"rating": 0})).values())
          for elem in data]
</code>```

Title: Sum values in a list of lists of dictionaries using common key-value pairs

Body:
Sorting should be avoided because each item can be processed in a single pass. Any hash based technique should be better.

Here's an alternate solution, that uses a defaultdict instead of expensive sort/groupby or pandas.

from collections import defaultdict
from functools import reduce

def reduce_func(state, item):
  new_obj = {
    "user": item["user"],
    "rating": state[item["user"]]["rating"] + item["rating"]}
  }
  state[item["user"]] = new_obj
  return state

output = [list(reduce(reduce_func, elem, defaultdict(lambda: {"rating": 0})).values())
          for elem in data]


问:
Java Swing Help
I'm trying to create a grid of JButtons, with index values to the left and right of the button grid.

Here is my code, but I'm getting a NullPointerException.  What is the problem?

```<code>public class Test {
public static void main(String args[]) {
    JFrame myapp = new JFrame("test");
    myapp.setLayout(new FlowLayout());

    myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myapp.setSize(400,400);
    myapp.setVisible(true);

    myapp.getContentPane().add(Board());
}

private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];

    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            if ((j != 0) && (i != 0)) {
                //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                board.add(buttons[i-1][j-1]);
            }
            if (i == 0) {
                if (j != 0) {
                    // used to display row of numbers
                    k = new JTextField(columnlabels[j]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                } else {
                    // used to display column of numbers
                    k = new JTextField();
                    k.setEditable(false);
                }
                board.add(k);
            } else if (j == 0) {
                k = new JTextField(rowlabels[i]);
                k.setEditable(false);
                k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                board.add(k);
            }
        }
    }

    return board;
}
}
</code>```

I'm probably doing something obvious, but Swing is kind of new to me, so any help would be greatly appreciated.

答:
Swing GUIs should be constructed on the EDT.  That part is left as an exercise for the OP.

```<code>import java.awt.*;
import javax.swing.*;

public class Test {
    public static void main(String args[]) {
        JFrame myapp = new JFrame("test");
        myapp.setLayout(new FlowLayout());

        myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myapp.getContentPane().add(Board());

        // very important!
        myapp.pack();

        // do these last.
        myapp.setSize(400,400);
        myapp.setVisible(true);

    }

    private static JPanel Board() {
        JButton[][] buttons = new JButton [10][10];
        for(int x=0; x<buttons.length; x++) {
            for (int y=0; y<buttons[0].length; y++) {
                buttons[x][y] = new JButton();
            }
        }

        JPanel board = new JPanel(new GridLayout(11,11));

        String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
        String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
        JTextField k;

        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if ((j != 0) && (i != 0)) {
                    //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                    board.add(buttons[i-1][j-1]);
                }
                if (i == 0) {
                    if (j != 0) {
                        // used to display row of numbers
                        k = new JTextField(columnlabels[j]);
                        k.setEditable(false);
                        k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    } else {
                        // used to display column of numbers
                        k = new JTextField();
                        k.setEditable(false);
                    }
                    board.add(k);
                } else if (j == 0) {
                    k = new JTextField(rowlabels[i]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    board.add(k);
                }
            }
        }

        return board;
    }
}
</code>```

Given the nature of the GUI, I guess you are after something more like this.

```<code>import java.awt.*;
import javax.swing.*;

public class Test {
    public static void main(String args[]) {
        JFrame myapp = new JFrame("test");
        myapp.setLayout(new FlowLayout());

        myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myapp.getContentPane().add(Board());

        // very important!
        myapp.pack();

        // do this last.
        myapp.setVisible(true);
    }

    private static JPanel Board() {
        JButton[][] buttons = new JButton [10][10];
        for(int x=0; x<buttons.length; x++) {
            for (int y=0; y<buttons[0].length; y++) {
                JButton temp = new JButton();
                temp.setPreferredSize(new Dimension(30,30));
                buttons[x][y] = temp;
            }
        }

        JPanel board = new JPanel(new GridLayout(11,11));

        String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
        String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
        JTextField k;

        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if ((j != 0) && (i != 0)) {
                    //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                    board.add(buttons[i-1][j-1]);
                }
                if (i == 0) {
                    if (j != 0) {
                        // used to display row of numbers
                        k = new JTextField(columnlabels[j]);
                        k.setEditable(false);
                        k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    } else {
                        // used to display column of numbers
                        k = new JTextField();
                        k.setEditable(false);
                    }
                    board.add(k);
                } else if (j == 0) {
                    k = new JTextField(rowlabels[i]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    board.add(k);
                }
            }
        }

        return board;
    }
}
</code>```

Title: Java Swing Help

Body:
I'm trying to create a grid of JButtons, with index values to the left and right of the button grid.

Here is my code, but I'm getting a NullPointerException.  What is the problem?

public class Test {
public static void main(String args[]) {
    JFrame myapp = new JFrame("test");
    myapp.setLayout(new FlowLayout());

    myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myapp.setSize(400,400);
    myapp.setVisible(true);

    myapp.getContentPane().add(Board());
}

private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];

    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            if ((j != 0) && (i != 0)) {
                //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                board.add(buttons[i-1][j-1]);
            }
            if (i == 0) {
                if (j != 0) {
                    // used to display row of numbers
                    k = new JTextField(columnlabels[j]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                } else {
                    // used to display column of numbers
                    k = new JTextField();
                    k.setEditable(false);
                }
                board.add(k);
            } else if (j == 0) {
                k = new JTextField(rowlabels[i]);
                k.setEditable(false);
                k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                board.add(k);
            }
        }
    }

    return board;
}
}

I'm probably doing something obvious, but Swing is kind of new to me, so any help would be greatly appreciated.

Body:
Swing GUIs should be constructed on the EDT.  That part is left as an exercise for the OP.

import java.awt.*;
import javax.swing.*;

public class Test {
    public static void main(String args[]) {
        JFrame myapp = new JFrame("test");
        myapp.setLayout(new FlowLayout());

        myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myapp.getContentPane().add(Board());

        // very important!
        myapp.pack();

        // do these last.
        myapp.setSize(400,400);
        myapp.setVisible(true);

    }

    private static JPanel Board() {
        JButton[][] buttons = new JButton [10][10];
        for(int x=0; x<buttons.length; x++) {
            for (int y=0; y<buttons[0].length; y++) {
                buttons[x][y] = new JButton();
            }
        }

        JPanel board = new JPanel(new GridLayout(11,11));

        String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
        String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
        JTextField k;

        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if ((j != 0) && (i != 0)) {
                    //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                    board.add(buttons[i-1][j-1]);
                }
                if (i == 0) {
                    if (j != 0) {
                        // used to display row of numbers
                        k = new JTextField(columnlabels[j]);
                        k.setEditable(false);
                        k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    } else {
                        // used to display column of numbers
                        k = new JTextField();
                        k.setEditable(false);
                    }
                    board.add(k);
                } else if (j == 0) {
                    k = new JTextField(rowlabels[i]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    board.add(k);
                }
            }
        }

        return board;
    }
}

Given the nature of the GUI, I guess you are after something more like this.

import java.awt.*;
import javax.swing.*;

public class Test {
    public static void main(String args[]) {
        JFrame myapp = new JFrame("test");
        myapp.setLayout(new FlowLayout());

        myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myapp.getContentPane().add(Board());

        // very important!
        myapp.pack();

        // do this last.
        myapp.setVisible(true);
    }

    private static JPanel Board() {
        JButton[][] buttons = new JButton [10][10];
        for(int x=0; x<buttons.length; x++) {
            for (int y=0; y<buttons[0].length; y++) {
                JButton temp = new JButton();
                temp.setPreferredSize(new Dimension(30,30));
                buttons[x][y] = temp;
            }
        }

        JPanel board = new JPanel(new GridLayout(11,11));

        String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
        String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
        JTextField k;

        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if ((j != 0) && (i != 0)) {
                    //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                    board.add(buttons[i-1][j-1]);
                }
                if (i == 0) {
                    if (j != 0) {
                        // used to display row of numbers
                        k = new JTextField(columnlabels[j]);
                        k.setEditable(false);
                        k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    } else {
                        // used to display column of numbers
                        k = new JTextField();
                        k.setEditable(false);
                    }
                    board.add(k);
                } else if (j == 0) {
                    k = new JTextField(rowlabels[i]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                    board.add(k);
                }
            }
        }

        return board;
    }
}


问:
Continuous Async Ping inside a Windows Service
I need to monitor a list of hosts continuously. After N seconds, i need to check the list again. So, I tried to use the async ping inside a Windows Service.

I tried to follow tips from other posts related to the topic, but always my service stops shortly after starting it.

There are a problem with await in "OnElapsedTime" function.

Any one have an idea what is wrong? Bellow my code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net.NetworkInformation;

namespace PingAsyncService
{
    public partial class HyBrazil_Ping : ServiceBase

    {

        Timer timer = new Timer();
        List<string> IPList = new List<string>();  //List of IPs

        public HyBrazil_Ping()
        {
            IPList.Add("192.168.0.1");
            IPList.Add("192.168.0.254");

            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            WriteToFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000; //number in miliseconds
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            WriteToFile("Service is stopped at " + DateTime.Now);
        }

        private async void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            //WriteToFile("Service is recall at " + DateTime.Now);

            var ResultList = await PingAsync();
            foreach(PingReply reply in ResultList)
            {
                WriteToFile(reply.Address.ToString() + ";" + reply.Status.ToString());
            }
        }

        private async Task<PingReply> PingAndProcessAsync(Ping pingSender, string ip)
        {
            var result = await pingSender.SendPingAsync(ip, 2000);
            return result;
        }

        private async Task<List<PingReply>> PingAsync()
        {
            Ping pingSender = new Ping();
            var tasks = IPList.Select(ip => PingAndProcessAsync(pingSender, ip));
            var results = await Task.WhenAll(tasks);
            return results.ToList();
        }

        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}
</code>```

Thanks a lot!

答:
In one of the comments you mentioned the error message as
"An asynchronous call is already in progress. It must be completed or canceled before you can call this method."

Chances are, the Ping object does not let simultaneous asynchronous calls.
Using a new Ping object everytime, on each call, might help as below.

```<code>private async Task<List<PingReply>> PingAsync()
{
    // Ping pingSender = new Ping();
    var tasks = IPList.Select(ip =>
    {
        using (var p= new Ping())
        {
            return PingAndProcessAsync(p, ip);
        }
    });
    var results = await Task.WhenAll(tasks);
    return results.ToList();
}
</code>```

Body:
I need to monitor a list of hosts continuously. After N seconds, i need to check the list again. So, I tried to use the async ping inside a Windows Service.

I tried to follow tips from other posts related to the topic, but always my service stops shortly after starting it.

There are a problem with await in "OnElapsedTime" function.

Any one have an idea what is wrong? Bellow my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net.NetworkInformation;

namespace PingAsyncService
{
    public partial class HyBrazil_Ping : ServiceBase

    {

        Timer timer = new Timer();
        List<string> IPList = new List<string>();  //List of IPs

        public HyBrazil_Ping()
        {
            IPList.Add("192.168.0.1");
            IPList.Add("192.168.0.254");

            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            WriteToFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000; //number in miliseconds
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            WriteToFile("Service is stopped at " + DateTime.Now);
        }

        private async void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            //WriteToFile("Service is recall at " + DateTime.Now);

            var ResultList = await PingAsync();
            foreach(PingReply reply in ResultList)
            {
                WriteToFile(reply.Address.ToString() + ";" + reply.Status.ToString());
            }
        }

        private async Task<PingReply> PingAndProcessAsync(Ping pingSender, string ip)
        {
            var result = await pingSender.SendPingAsync(ip, 2000);
            return result;
        }

        private async Task<List<PingReply>> PingAsync()
        {
            Ping pingSender = new Ping();
            var tasks = IPList.Select(ip => PingAndProcessAsync(pingSender, ip));
            var results = await Task.WhenAll(tasks);
            return results.ToList();
        }

        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

Thanks a lot!

Body:
In one of the comments you mentioned the error message as
"An asynchronous call is already in progress. It must be completed or canceled before you can call this method."

Chances are, the Ping object does not let simultaneous asynchronous calls.
Using a new Ping object everytime, on each call, might help as below.

private async Task<List<PingReply>> PingAsync()
{
    // Ping pingSender = new Ping();
    var tasks = IPList.Select(ip =>
    {
        using (var p= new Ping())
        {
            return PingAndProcessAsync(p, ip);
        }
    });
    var results = await Task.WhenAll(tasks);
    return results.ToList();
}


问:
Error loading key "/root/.ssh/id_rsa": invalid format
I am building a CI/CD for my django project using GitLab. As part of my deploy stage, I have

```<code>deploy:
  stage: deploy
  script:
    - mkdir -p ~/.ssh
    - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
    - cat ~/.ssh/id_rsa
    - chmod 700 ~/.ssh/id_rsa
    - eval "$(ssh-agent -s)"
    - ssh-add ~/.ssh/id_rsa
    - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts
    - chmod +x ./deploy.sh
    - scp  -o StrictHostKeyChecking=no -r ./.env ./docker-compose.prod.yml ec2-user@$EC2_PUBLIC_IP_ADDRESS:/home/ec2-user/app
    - bash ./deploy.sh
  only:
    - master
</code>```

The build breaks down at ssh-add ~/.ssh/id_rsa with the error message Error loading key "/root/.ssh/id_rsa": invalid format.

I have checked people with questions with similar error messages and none seem related to what I am doing.

Notes

I am trying to deploy to amazon ec2

I am following this tutorial https://testdriven.io/blog/deploying-django-to-ec2-with-docker-and-gitlab/ and everything seems to work fine up until this last point.

答:
I managed to fix it with the help of guys from the ##aws irc channel

The Problem

I generated a PKCS#1 key format instead of a PKCS#8 format.
The PKCS#1 is represented as:

```<code>-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----
</code>```

The PKCS#8 is represented as:

```<code>-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----
</code>```

Solution

I simply copied the PRIVATE KEY and converted it here https://decoder.link/rsa_converter

You can also see a better elucidation here Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"

Edited
As indicated below, it is not a good idea to use websites to do the conversion. Especially when your private key is likely being
sent to their servers. Instead, do the conversion locally as indicated here
by @csgeek

Body:
I am building a CI/CD for my django project using GitLab. As part of my deploy stage, I have

deploy:
  stage: deploy
  script:
    - mkdir -p ~/.ssh
    - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
    - cat ~/.ssh/id_rsa
    - chmod 700 ~/.ssh/id_rsa
    - eval "$(ssh-agent -s)"
    - ssh-add ~/.ssh/id_rsa
    - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts
    - chmod +x ./deploy.sh
    - scp  -o StrictHostKeyChecking=no -r ./.env ./docker-compose.prod.yml ec2-user@$EC2_PUBLIC_IP_ADDRESS:/home/ec2-user/app
    - bash ./deploy.sh
  only:
    - master

The build breaks down at ssh-add ~/.ssh/id_rsa with the error message Error loading key "/root/.ssh/id_rsa": invalid format.

I have checked people with questions with similar error messages and none seem related to what I am doing.

Notes

I am trying to deploy to amazon ec2

I am following this tutorial https://testdriven.io/blog/deploying-django-to-ec2-with-docker-and-gitlab/ and everything seems to work fine up until this last point.

Body:
I managed to fix it with the help of guys from the ##aws irc channel

The Problem

I generated a PKCS#1 key format instead of a PKCS#8 format.
The PKCS#1 is represented as:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

The PKCS#8 is represented as:

-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----

Solution

I simply copied the PRIVATE KEY and converted it here https://decoder.link/rsa_converter

You can also see a better elucidation here Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"

Edited
As indicated below, it is not a good idea to use websites to do the conversion. Especially when your private key is likely being
sent to their servers. Instead, do the conversion locally as indicated here
by @csgeek


问:
Error connecting to TM-U220
I have downloaded 2 javascript SDK for Epson printer that supports TM-U220, and both of them won't connect to my printer and won't print. But when I tried to use other SDK such as QZ Tray, it worked, but the QZ Tray must be turned on, I want this to work in android, so I use the javascript SDK from Epson.

The problem is when I use the printer sample that Epson provided in the javascript SDK and input the ip: 192.168.1.98, port: 9100, and device id: local_printer, I got this error :

connected to ePOS Device Service Interface is failed. [ERROR_TIMEOUT]

.

But the printer did a small printing, letter that I can't read, and at the very end of the print : 2http/1.1. And in the console :

OPTIONS https://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000 net::ERR_CONNECTION_REFUSED

and

OPTIONS https://192.168.1.98/cgi-bin/eposDisp/service.cgi?devid=local_display&timeout=10000 net::ERR_CONNECTION_REFUSED

I've also created my own simple code.
This is my first code using epos-2.3.0.js :

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Print Test</title>

        <script type="text/javascript" src="epos-2.3.0.js"></script>

        <script type="text/javascript">
            // Retrieving Printer objects (printer selection)
            var printer = null;
            // Retrieving Printer objects (printer selection)

            // Creating ePOSDevice objects (device connection and communication)
            var ePosDev = new epson.ePOSDevice();

            function connect() {
                var ipAddress = '192.168.1.98'; var port = '9100';
                ePosDev.connect(ipAddress, port, callback_connect);
            }
            // Creating ePOSDevice objects (device connection and communication)

            // Retrieving Printer objects (printer selection)
            function callback_connect(resultConnect) {
                var deviceId = 'local_printer';
                var options = {'crypto' : false, 'buffer' : false};

                if ((resultConnect == 'OK') || (resultConnect == 'SSL_CONNECT_OK')) {
                    // Retrieves the printer object
                    alert("Success callback connect");
                    ePostDev.createDevice(deviceId, ePosDev.DEVICE_TYPE_PRINTER, options, callback_createDevice);
                }
                else {
                    // Displays error messages
                    alert("Error callback connect");
                }
            }

            function callback_createDevice(deviceObj, errorCode) {
                if (deviceObj === null) {
                    // Displays an error message if the system fails to retreive the printer object
                    return;
                }
                printer = deviceObj;

                // Registers the print complete event
                printer.onreceive = function(response) {
                    if (response.success) {
                        // Displays the successful print message
                        alert("Callback create device response success");
                    }
                    else {
                        // Displays error messages
                        alert("Callback create device response failed");
                    }
                }
            }
            // Retrieving Printer objects (printer selection)

            // Creating print data (data buffering)
            function createData() {
                printer.addTextAlign(printer.ALIGN_CENTER);
                printer.addText('Hello World\n');
            }
            // Creating print data (data buffering)

            // Sending print data (printing and disconnection)
            function send() {
                if (ePosDev.isConnected) {
                    printer.send();
                }
            }
            // Sending print data (printing and disconnection)
        </script>
    </head>
    <body>
        <input type="button" onclick="connect()" value="Connect" />
        <input type="button" onClick="send()" value="Print Hello World" />
    </body>
</html>
</code>```

And this one I'm using epos-print-3.2.0.js :

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Print Test 2</title>
        <script type="text/javascript" src="epos-print-3.2.0.js"></script>
        <script type="text/javascript">
            function buildMessage() {
                // Create a print document
                var builder = new epson.ePOSBuilder();
                builder.addTextLang('en');
                builder.addTextSmooth(true);
                builder.addTextFont(builder.FONT_A);
                builder.addTextSize(3, 3);
                builder.addText('Hello,\tWorld!\n');
                builder.addCut(builder.CUT_FEED);
                var request = builder.toString();

                var address = 'http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000';

                // Create an ePOS-Print object
                var epos = new epson.ePOSPrint(address);
                //Send the print document
                epos.send(request);
            }
        </script>
    </head>
    <body>
        <button onclick="buildMessage()">Run</button>
    </body>
</html>
</code>```

When I run the second code, I got this error in my console :

OPTIONS http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

and

XMLHttpRequest cannot load http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000. Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access. The response
  had HTTP status code 405.

But When I change the address from

http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

to

http://192.168.1.98:9100/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

it printed me this :

OPTIONS /cgi-bin/epos/service.cgi?devid=local-printer&timeout=10000
  HTTP/1.1
 Host: 192.168.1.98:9100
 Connection: keep-alive Access-Control-Request-Method: POST
 Origin: null

  User-Agent: Mizilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36
  (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

  Access-Control-Request-Headers: content-type, if-modified-since,
  soapaction
 Accept: */*
 Accept-Encoding: gzip,
  deflate,sdch
 Accept=Language: en-US, en;q=0.8

答: I had the same problem with a TM-T20III. You have to use the utility software from Epson for your printer. In the advanced network settings, there is a menu which call "Filters" and I add the IP address of my POS as accept address.</p>

Title: Error connecting to TM-U220

Body:
I have downloaded 2 javascript SDK for Epson printer that supports TM-U220, and both of them won't connect to my printer and won't print. But when I tried to use other SDK such as QZ Tray, it worked, but the QZ Tray must be turned on, I want this to work in android, so I use the javascript SDK from Epson.

The problem is when I use the printer sample that Epson provided in the javascript SDK and input the ip: 192.168.1.98, port: 9100, and device id: local_printer, I got this error :

connected to ePOS Device Service Interface is failed. [ERROR_TIMEOUT]

.

But the printer did a small printing, letter that I can't read, and at the very end of the print : 2http/1.1. And in the console :

OPTIONS https://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000 net::ERR_CONNECTION_REFUSED

and

OPTIONS https://192.168.1.98/cgi-bin/eposDisp/service.cgi?devid=local_display&timeout=10000 net::ERR_CONNECTION_REFUSED

I've also created my own simple code.
This is my first code using epos-2.3.0.js :

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Print Test</title>

        <input type="button" onclick="connect()" value="Connect" />
        <input type="button" onClick="send()" value="Print Hello World" />

And this one I'm using epos-print-3.2.0.js :

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Print Test 2</title>

        <button onclick="buildMessage()">Run</button>

When I run the second code, I got this error in my console :

OPTIONS http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

and

XMLHttpRequest cannot load http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000. Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access. The response
  had HTTP status code 405.

But When I change the address from

http://192.168.1.98/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

to

http://192.168.1.98:9100/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

it printed me this :

OPTIONS /cgi-bin/epos/service.cgi?devid=local-printer&timeout=10000
  HTTP/1.1
 Host: 192.168.1.98:9100
 Connection: keep-alive Access-Control-Request-Method: POST
 Origin: null

  User-Agent: Mizilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36
  (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

  Access-Control-Request-Headers: content-type, if-modified-since,
  soapaction
 Accept: */*
 Accept-Encoding: gzip,
  deflate,sdch
 Accept=Language: en-US, en;q=0.8


问:
Error Unexpected end of JSON input while parsing near '...ge-2.2.1.tgz"},"engin'
Command:

```<code>npm install -g @angular/cli@latest
</code>```

Exception:

verbose stack SyntaxError: Unexpected end of JSON input while parsing
  near '...ge-2.2.1.tgz"},"engin' 169 verbose stack     at JSON.parse
  () 169 verbose stack     at parseJson (C:\Program
  Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\node_modules\json-parse-better-errors\index.js:7:17)
  169 verbose stack     at consumeBody.call.then.buffer (C:\Program
  Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\src\body.js:96:50)
  169 verbose stack     at  169 verbose stack     at
  process._tickCallback (internal/process/next_tick.js:188:7)

Looking for help and support.
Thanks

答:
I am using :

node v12.17.0

npm 6.14.4

Windows 10

I was trying to install Amplify 4.21.0 when I faced:

Error Unexpected end of JSON input while parsing near ....

It worked for me after doing the following steps:

Uninstall and reinstall node.

Delete the files in C:\Users\username\AppData\Roaming\npm-cache

Using the command line as administrator, I run npm cache clean --force

I deleted the package.lock.json file in C:\Users\username.

Then installed Amplify using npm install -g @aws-amplify/cli

Body:
Command:

npm install -g @angular/cli@latest

Exception:

verbose stack SyntaxError: Unexpected end of JSON input while parsing
  near '...ge-2.2.1.tgz"},"engin' 169 verbose stack     at JSON.parse
  () 169 verbose stack     at parseJson (C:\Program
  Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\node_modules\json-parse-better-errors\index.js:7:17)
  169 verbose stack     at consumeBody.call.then.buffer (C:\Program
  Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\src\body.js:96:50)
  169 verbose stack     at  169 verbose stack     at
  process._tickCallback (internal/process/next_tick.js:188:7)

Looking for help and support.
Thanks


问:
@Enterprise Library Unity, How to inject to the List Property
The follows is my code snippet, and I want to deliver the List parameter to my construct.

```<code>public class  MyClass

{

    public MyClass(List<string> parmList)
    {
         this.MyList=parmList;
    }

    public List<string> MyList
    {
        get;set;
    }

}
</code>```

The config:

```<code>  <alias alias="List" type="System.Collections.Generic.List[[System.String,

   mscorlib],mscorlib]"/>

  <register>

     <constructor>
        <param name="paraList" type="List" />
     </constructor>

  </register>
</code>```

But when I resolve request to the container it throw out the exception:

The type List`1 has multiple constructors of length 1. Unable to disambiguate.

Is there any configuration error?

答: In order to resolve an instance of MyClass, Unity must Resolve an instance of List<string> to pass to your constructor - but it is unable to choose among the available constructors for List<string>. Here is some information on telling Unity which constructors to use when initializing a class.

Body:
The follows is my code snippet, and I want to deliver the List parameter to my construct.

public class  MyClass

{

    public MyClass(List<string> parmList)
    {
         this.MyList=parmList;
    }

    public List<string> MyList
    {
        get;set;
    }

}

The config:

  <alias alias="List" type="System.Collections.Generic.List[[System.String,

   mscorlib],mscorlib]"/>

  <register>

     <constructor>
        <param name="paraList" type="List" />
     </constructor>

  </register>

But when I resolve request to the container it throw out the exception:

The type List`1 has multiple constructors of length 1. Unable to disambiguate.

Is there any configuration error?