问:
Is it possible to load new Javascript files with AJAX?
I'm building a new AJAX powered website with distinct sections.  Each section requires a new set of Javascript functions to run.  I'd rather not load every script at the start, as there might be quite a few.

Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).

Thanks

Edit - JQuery is fine, it doesn't have to be old school Javascript

答:
jQuery makes it pretty simple.

```<code>$.getScript('myscript.js', function() {
  console.debug('Script loaded.');
});
</code>```

If you can't use jQuery, there's a few more lines to write.

```<code>var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');
script.src = 'myscript.js';
head.appendChild(script);
</code>```

Body:
jQuery makes it pretty simple.

$.getScript('myscript.js', function() {
  console.debug('Script loaded.');
});

If you can't use jQuery, there's a few more lines to write.

var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');
script.src = 'myscript.js';
head.appendChild(script);


来源: stackexchange

问:
Is it possible to do a sparse checkout without checking out the whole repository first?
I'm working with a repository with a very large number of files that takes hours to checkout. I'm looking into the possibility of whether Git would work well with this kind of repository now that it supports sparse checkouts but every example that I can find does the following:

```<code>git clone <path>
git config core.sparsecheckout true
echo <dir> > .git/info/sparse-checkout
git read-tree -m -u HEAD
</code>```

The problem with this sequence of commands is the original clone also does a checkout. If you add -n to the original clone command, then the read-tree command results in the following error:

error: Sparse checkout leaves no entry on working directory

How can do the sparse checkout without checking out all the files first?

答:
In my case, I want to skip the Pods folder when cloning the project. I did step by step like below and it works for me.
Hope it helps.

```<code>mkdir my_folder
cd my_folder
git init
git remote add origin -f <URL>
git config core.sparseCheckout true
echo '!Pods/*\n/*' > .git/info/sparse-checkout
git pull origin master
</code>```

Memo, If you want to skip more folders, just add more line in sparse-checkout file.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with a repository with a very large number of files that takes hours to checkout. I'm looking into the possibility of whether Git would work well with this kind of repository now that it supports sparse checkouts but every example that I can find does the following:

git clone <path>
git config core.sparsecheckout true
echo <dir> > .git/info/sparse-checkout
git read-tree -m -u HEAD

The problem with this sequence of commands is the original clone also does a checkout. If you add -n to the original clone command, then the read-tree command results in the following error:

error: Sparse checkout leaves no entry on working directory

How can do the sparse checkout without checking out all the files first?

Body:
In my case, I want to skip the Pods folder when cloning the project. I did step by step like below and it works for me.
Hope it helps.

mkdir my_folder
cd my_folder
git init
git remote add origin -f <URL>
git config core.sparseCheckout true
echo '!Pods/*\n/*' > .git/info/sparse-checkout
git pull origin master

Memo, If you want to skip more folders, just add more line in sparse-checkout file.

ContentLicense: CC BY-SA 4.0


问:
docker-compose: Can't connect application container with mysql container
I am having trouble to make the container that contains a python/bottle web app to reach the mysql server/container.

docker-compose build:

```<code>Step 8/9 : RUN python3 bin/initdb.py
 ---> Running in 30d963677711
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/lib/python3.7/socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "bin/initdb.py", line 18, in <module>
    password=config('MYSQL_PASSWORD', default='tspass')
  File "/usr/local/lib/python3.7/dist-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name or service not known)")
ERROR: Service 'web' failed to build: The command '/bin/sh -c python3 bin/initdb.py' returned a non-zero code: 1
</code>```

docker-compose.yml:

```<code>version: '3'

services:
  db:
    container_name: mysql
    image: mysql
    env_file: .env
    restart: always
    volumes:
      - ./init.sql:/app/init.sql
    networks:
      - "dock"
    expose:
      - "3306"
    # on host it's mapped on 33060

  web:
    container_name: app
    build: .
    env_file: .env
    restart: always
    depends_on:
      - db
    links:
      - db:db
    networks:
      - "dock"
    ports:
      - "8888:8888"

networks:
  dock:
</code>```

Dockerfile:

```<code>FROM debian:stable

EXPOSE 8888
# CMD ["./bin/run.sh"]

RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential python3 python3-dev python3-pip python3-setuptools
RUN pip3 install --upgrade pip && \
    rm -rf /var/lib/apt/lists/* && rm -rf /var/cache/apt/archives/*.deb

WORKDIR /app

COPY . /app/
RUN pip install --no-cache-dir -r /app/requirements.txt

RUN python3 bin/initdb.py
RUN python3 main.py 0.0.0.0 8888
</code>```

initdb.py:

```<code>#!/usr/bin/env python

import pymysql
from decouple import Config, RepositoryEnv

...

conn = pymysql.connect(
    host=config('DB_HOST', default='db'),  # NOT ACCESSIBLE?
    port=config('DB_PORT', default=3306, cast=int),
    db=config('MYSQL_DATABASE', default='db1'),
    user=config('MYSQL_USER', default='user'),
    password=config('MYSQL_PASSWORD', default='password')
)
</code>```

.env:

```<code># DEPLOYMENT
DB_HOST=db
DB_PORT=3306

# DOCKER MYSQL
MYSQL_HOST="0.0.0.0"
MYSQL_ROOT_HOST="%"
MYSQL_ROOT_USER=root
MYSQL_ROOT_PASSWORD=toor
MYSQL_DATABASE=db1
MYSQL_USER=user
MYSQL_PASSWORD=password
</code>```

Any thoughts how to debug this?

PS: The above setup works perfectly without docker, by changing DB_HOST=db to DB_HOST=localhost and running python main.py

答:
Modified files, based on both answers above, solving this particular issue are:

Dockerfile:

```<code>FROM debian:stable

EXPOSE 8888

RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential python3 python3-dev python3-pip python3-setuptools

RUN pip3 install --upgrade pip && \
    rm -rf /var/lib/apt/lists/* && rm -rf /var/cache/apt/archives/*.deb

WORKDIR /app

COPY . /app/
RUN pip install --no-cache-dir -r /app/requirements.txt
RUN chmod +x ./bin/*

CMD ["./bin/run.sh"]
</code>```

bin/wait-for-it.sh:
as is

bin/run.sh:

```<code>#!/usr/bin/env bash

./bin/wait-for-it.sh -h db -p 3306 -- python3 ./bin/initdb.py
./bin/wait-for-it.sh -h db -p 3306 -- python3 ./main.py 0.0.0.0 8888
</code>```

Body:
I am having trouble to make the container that contains a python/bottle web app to reach the mysql server/container.

docker-compose build:

Step 8/9 : RUN python3 bin/initdb.py
 ---> Running in 30d963677711
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/lib/python3.7/socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "bin/initdb.py", line 18, in <module>
    password=config('MYSQL_PASSWORD', default='tspass')
  File "/usr/local/lib/python3.7/dist-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name or service not known)")
ERROR: Service 'web' failed to build: The command '/bin/sh -c python3 bin/initdb.py' returned a non-zero code: 1

docker-compose.yml:

version: '3'

services:
  db:
    container_name: mysql
    image: mysql
    env_file: .env
    restart: always
    volumes:
      - ./init.sql:/app/init.sql
    networks:
      - "dock"
    expose:
      - "3306"
    # on host it's mapped on 33060

  web:
    container_name: app
    build: .
    env_file: .env
    restart: always
    depends_on:
      - db
    links:
      - db:db
    networks:
      - "dock"
    ports:
      - "8888:8888"

networks:
  dock:

Dockerfile:

FROM debian:stable

EXPOSE 8888
# CMD ["./bin/run.sh"]

RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential python3 python3-dev python3-pip python3-setuptools
RUN pip3 install --upgrade pip && \
    rm -rf /var/lib/apt/lists/* && rm -rf /var/cache/apt/archives/*.deb

WORKDIR /app

COPY . /app/
RUN pip install --no-cache-dir -r /app/requirements.txt

RUN python3 bin/initdb.py
RUN python3 main.py 0.0.0.0 8888

initdb.py:

#!/usr/bin/env python

import pymysql
from decouple import Config, RepositoryEnv

...

conn = pymysql.connect(
    host=config('DB_HOST', default='db'),  # NOT ACCESSIBLE?
    port=config('DB_PORT', default=3306, cast=int),
    db=config('MYSQL_DATABASE', default='db1'),
    user=config('MYSQL_USER', default='user'),
    password=config('MYSQL_PASSWORD', default='password')
)

.env:

# DEPLOYMENT
DB_HOST=db
DB_PORT=3306

# DOCKER MYSQL
MYSQL_HOST="0.0.0.0"
MYSQL_ROOT_HOST="%"
MYSQL_ROOT_USER=root
MYSQL_ROOT_PASSWORD=toor
MYSQL_DATABASE=db1
MYSQL_USER=user
MYSQL_PASSWORD=password

Any thoughts how to debug this?

PS: The above setup works perfectly without docker, by changing DB_HOST=db to DB_HOST=localhost and running python main.py

Body:
Modified files, based on both answers above, solving this particular issue are:

Dockerfile:

FROM debian:stable

EXPOSE 8888

RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential python3 python3-dev python3-pip python3-setuptools

RUN pip3 install --upgrade pip && \
    rm -rf /var/lib/apt/lists/* && rm -rf /var/cache/apt/archives/*.deb

WORKDIR /app

COPY . /app/
RUN pip install --no-cache-dir -r /app/requirements.txt
RUN chmod +x ./bin/*

CMD ["./bin/run.sh"]

bin/wait-for-it.sh:
as is

bin/run.sh:

#!/usr/bin/env bash

./bin/wait-for-it.sh -h db -p 3306 -- python3 ./bin/initdb.py
./bin/wait-for-it.sh -h db -p 3306 -- python3 ./main.py 0.0.0.0 8888


问:
How can I batch/sequentially download m3u8 files using ffmpeg?
I'm currently downloading m38u playlists individually using the following on Mac:

```<code>ffmpeg -i <"URL with m3u8"> -codec copy output.ts
</code>```

If I want to do multiple files, I currently do it from separate Terminal windows.

What I would like to do is, in a single instance, tell ffmpeg to e.g. take URLs from a .txt file and download them in sequence, with a sequential output name for each (fine for them to all go in same output folder).

Sample code from m3u8 file:

```<code>#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:9
#EXTINF:8.333333,
segment00000.ts
#EXTINF:8.333333,
segment00001.ts
#EXTINF:8.333333,
segment00002.ts
#EXTINF:5.000000,
segment00003.ts
#EXTINF:8.333333,
segment00004.ts
#EXTINF:8.333333,
segment00005.ts
</code>```

I certainly have homebrew installed - I'm a novice, so unsure whether that means I'm actively 'using' it to manage packages

The file with the list of of m3u8 addresses is currently located at /Users/username/Downloads/m38u hold list.txt and looks like this:

```<code>https://streaming.imvbox.com/media/2825/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2298/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2822/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2821/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2820/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2088/1280x800/1280x800.m3u8
</code>```

But so far this file is simply a place to store the links - I haven't used it anything other than to copy the links from.

答:
So, I would save the following in your HOME directory as grabAll:

```<code>#!/bin/bash

HoldList="/Users/username/Downloads/m38u hold list.txt"

index=0
while read line ; do
    echo ffmpeg -i $line -codec copy output-${index}.ts
    ((index=index+1))
done < "$HoldList"
</code>```

Note: If you use TextEdit, make sure to click menu option Format->Make Plain Text

Then you can start Terminal and run:

```<code>bash grabAll
</code>```

and see if it is generating the type of commands you want. It doesn't currently do anything, it just says on the screen what it would do. If it looks good, you just need to remove the word echo from the 3rd to last line and run it again.

Sample Output

```<code>ffmpeg -i https://streaming.imvbox.com/media/2825/1280x800/1280x800.m3u8 -codec copy output-0.ts
ffmpeg -i https://streaming.imvbox.com/media/2298/1280x800/1280x800.m3u8 -codec copy output-1.ts
ffmpeg -i https://streaming.imvbox.com/media/2822/1280x800/1280x800.m3u8 -codec copy output-2.ts
ffmpeg -i https://streaming.imvbox.com/media/2821/1280x800/1280x800.m3u8 -codec copy output-3.ts
ffmpeg -i https://streaming.imvbox.com/media/2820/1280x800/1280x800.m3u8 -codec copy output-4.ts
ffmpeg -i https://streaming.imvbox.com/media/2088/1280x800/1280x800.m3u8 -codec copy output-5.ts
</code>```

Body:
I'm currently downloading m38u playlists individually using the following on Mac:

ffmpeg -i <"URL with m3u8"> -codec copy output.ts

If I want to do multiple files, I currently do it from separate Terminal windows.

What I would like to do is, in a single instance, tell ffmpeg to e.g. take URLs from a .txt file and download them in sequence, with a sequential output name for each (fine for them to all go in same output folder).

Sample code from m3u8 file:

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:9
#EXTINF:8.333333,
segment00000.ts
#EXTINF:8.333333,
segment00001.ts
#EXTINF:8.333333,
segment00002.ts
#EXTINF:5.000000,
segment00003.ts
#EXTINF:8.333333,
segment00004.ts
#EXTINF:8.333333,
segment00005.ts

I certainly have homebrew installed - I'm a novice, so unsure whether that means I'm actively 'using' it to manage packages

The file with the list of of m3u8 addresses is currently located at /Users/username/Downloads/m38u hold list.txt and looks like this:

https://streaming.imvbox.com/media/2825/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2298/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2822/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2821/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2820/1280x800/1280x800.m3u8
https://streaming.imvbox.com/media/2088/1280x800/1280x800.m3u8

But so far this file is simply a place to store the links - I haven't used it anything other than to copy the links from.

Body:
So, I would save the following in your HOME directory as grabAll:

#!/bin/bash

HoldList="/Users/username/Downloads/m38u hold list.txt"

index=0
while read line ; do
    echo ffmpeg -i $line -codec copy output-${index}.ts
    ((index=index+1))
done < "$HoldList"

Note: If you use TextEdit, make sure to click menu option Format->Make Plain Text

Then you can start Terminal and run:

bash grabAll

and see if it is generating the type of commands you want. It doesn't currently do anything, it just says on the screen what it would do. If it looks good, you just need to remove the word echo from the 3rd to last line and run it again.

Sample Output

ffmpeg -i https://streaming.imvbox.com/media/2825/1280x800/1280x800.m3u8 -codec copy output-0.ts
ffmpeg -i https://streaming.imvbox.com/media/2298/1280x800/1280x800.m3u8 -codec copy output-1.ts
ffmpeg -i https://streaming.imvbox.com/media/2822/1280x800/1280x800.m3u8 -codec copy output-2.ts
ffmpeg -i https://streaming.imvbox.com/media/2821/1280x800/1280x800.m3u8 -codec copy output-3.ts
ffmpeg -i https://streaming.imvbox.com/media/2820/1280x800/1280x800.m3u8 -codec copy output-4.ts
ffmpeg -i https://streaming.imvbox.com/media/2088/1280x800/1280x800.m3u8 -codec copy output-5.ts


问:
Assign a unique 4 digit number to a list of ids using python
I have a list of ids that i want to give a 4 digit unique number for each of them .

For example :

```<code>driver id = ['5c73d1238472750067e86c6d','5a0d5513494c09001491c118']
unique id = ['1234' , '5897']
</code>```

Is there a package i can use for this?

答:
Most of the answers are on how to generate them, assuming 4 digit number are used as string.
Let us examine the problem and come up with design, constraints and manage them.

If you are using numbers as numbers, not strings, then non zero numbers starting with non zero(s) are,
1000 to 9999, you can only address 8999 elements (drivers in your case). -Constraint

Example:  If you consider 0123  as a number is actually 3 digit number, 123.

Design:

Generate the numbers in a for loop using range(1000,10000) and keep them in a list(code below):
Complexity : is constant O(c), happens only once.

```<code>>>>
>>> four_digit_pool = []
>>> for i in range(1000, 10000):
...     four_digit_pool.append(i)
...
>>>
</code>```

```<code>four_digit_pool = [1000, 1001, ..., 9999]
</code>```

when you encounter a an element, look up if key exists and add it to driver_id_map.

Add it to map and pop element from list (pool of ids). Do not use remove, use pop, pop is ALWAYS O(1).
Note: In this case remove also is O(1), because it is sorted and you are removing from left one by one. But use pop, for surety.

```<code>driver_id_map = {
1000 : '5c73d1238472750067e86c6d'
1001 : '5a0d5513494c09001491c118'
...
}
</code>```

You can also have above map reversed, if you want to look-up if driver is already in list.

```<code>driver_id_map = {
'5c73d1238472750067e86c6d' : 1000
'5a0d5513494c09001491c118' : 1001
...
}
</code>```

Look-up is O(1) for maps.

If you loop through all drivers and assign it, Complexity is O(N)

Note:
If you are using numbers as strings and considering non zero numbers which are starting with zero(s) are 1108 numbers. You get additional ~1000 more drivers can be addressed.

These numbers also get into the four_digit_pool. Complexity won't change much.

numbers starting with 0 - 999 possibilities, example: 0123

numbers starting with 00 - 99 possibilities, example: 0023

numbers starting with 000 - 9 possibilities, example: 0003

numbers starting with 0000 - 1 possibilities, example: 0000 (the only one)

Body:
I have a list of ids that i want to give a 4 digit unique number for each of them .

For example :

driver id = ['5c73d1238472750067e86c6d','5a0d5513494c09001491c118']
unique id = ['1234' , '5897']

Is there a package i can use for this?

Body:
Most of the answers are on how to generate them, assuming 4 digit number are used as string.
Let us examine the problem and come up with design, constraints and manage them.

If you are using numbers as numbers, not strings, then non zero numbers starting with non zero(s) are,
1000 to 9999, you can only address 8999 elements (drivers in your case). -Constraint

Example:  If you consider 0123  as a number is actually 3 digit number, 123.

Design:

Generate the numbers in a for loop using range(1000,10000) and keep them in a list(code below):
Complexity : is constant O(c), happens only once.

>>>
>>> four_digit_pool = []
>>> for i in range(1000, 10000):
...     four_digit_pool.append(i)
...
>>>

four_digit_pool = [1000, 1001, ..., 9999]

when you encounter a an element, look up if key exists and add it to driver_id_map.

Add it to map and pop element from list (pool of ids). Do not use remove, use pop, pop is ALWAYS O(1).
Note: In this case remove also is O(1), because it is sorted and you are removing from left one by one. But use pop, for surety.

driver_id_map = {
1000 : '5c73d1238472750067e86c6d'
1001 : '5a0d5513494c09001491c118'
...
}

You can also have above map reversed, if you want to look-up if driver is already in list.

driver_id_map = {
'5c73d1238472750067e86c6d' : 1000
'5a0d5513494c09001491c118' : 1001
...
}

Look-up is O(1) for maps.

If you loop through all drivers and assign it, Complexity is O(N)

Note:
If you are using numbers as strings and considering non zero numbers which are starting with zero(s) are 1108 numbers. You get additional ~1000 more drivers can be addressed.

These numbers also get into the four_digit_pool. Complexity won't change much.

numbers starting with 0 - 999 possibilities, example: 0123

numbers starting with 00 - 99 possibilities, example: 0023

numbers starting with 000 - 9 possibilities, example: 0003

numbers starting with 0000 - 1 possibilities, example: 0000 (the only one)


问:
Thingworx client for windows 10
I want to gather some information from a windows 10 machine over the internet using the thingworx platform.
Here's a scenario:

Admin logs into thingworx app

Exisiting or new computer (windows 10 ) is added (serial number computer)

Thingworx platform creates a thing based on a created template

User receives application key which will be entered on a client which is installed on the computer

Client is started based on event and sends data to thingworx platform

Communication is secured

Is there a best practice or even a client available / open source or Licence based which relieves the headache of security etc.?

答:
If you want to use for Demo/Academic Purpose then use Thingworx Academic Simulator. I have been using it for Testing many scenarios.

Download Link - http://apps.ptc.com/schools/software/ThingWorxAcademicSimulatorSetup.exe

Title: Thingworx client for windows 10


问:
Is it possible to pass in a file as part of the request body using WireMock?
I am currently writing an integration test using Wiremock. At the moment I am defining the id and organization id as parameters. Instead of repeating this process for say 50 fields, is it possible to pass in a JSON file as the request instead? ie use this file as the requestBody.</p>

```<code>stubFor(post(urlEqualTo("/v1/transaction"))
            .withRequestBody(
                    matchingJsonPath("$.data.id", containing("1")))
            .withRequestBody(matchingJsonPath("$.data.organisation_id", containing("2")))
            .willReturn(aResponse()
                    .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)
                    .withStatus(HttpStatus.CREATED.value())
                    .withBodyFile("create_successful_response.json")));
</code>```

答:
You might find that the placeholders feature added in 2.26.0 is a better fit for what you want here.

Placeholders allow you to use equalToJson(...) with looser matching of specific fields e.g.

```<code>{
  "data": {
    "id": "${json-unit.any-string}",
    "organisation_id": "${json-unit.regex}.*1.*}"
  }
}
</code>```

More details here: http://wiremock.org/docs/request-matching/#placeholders

Body:
I am currently writing an integration test using Wiremock. At the moment I am defining the id and organization id as parameters. Instead of repeating this process for say 50 fields, is it possible to pass in a JSON file as the request instead? ie use this file as the requestBody.

stubFor(post(urlEqualTo("/v1/transaction"))
            .withRequestBody(
                    matchingJsonPath("$.data.id", containing("1")))
            .withRequestBody(matchingJsonPath("$.data.organisation_id", containing("2")))
            .willReturn(aResponse()
                    .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)
                    .withStatus(HttpStatus.CREATED.value())
                    .withBodyFile("create_successful_response.json")));

Body:
You might find that the placeholders feature added in 2.26.0 is a better fit for what you want here.

Placeholders allow you to use equalToJson(...) with looser matching of specific fields e.g.

{
  "data": {
    "id": "${json-unit.any-string}",
    "organisation_id": "${json-unit.regex}.*1.*}"
  }
}

More details here: http://wiremock.org/docs/request-matching/#placeholders


问:
Why my state does not change on click event with setState
I'm learning React, and actually don't understand why my state does not change immediately when I press a button, with a click event. I mean, I created a state "test: false", but when I click on my button, I just want to change the state, so I used setState. But the console still shows me the "false" when I click for the first time.

Here's a Codesandbox to illustrate my example.

```<code>import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: false
    };
    this.display.bind(this);
  }
  display() {
    this.setState({
      test: true
    });
    console.log(this.state.test)
  }
  render() {
    return (
      <div className="App">
        <button onClick={() => this.display()}>Click me!</button>
      </div>
    );
  }
}

export default App;
</code>```

I also want to show  "Hello" if state is true and "Goodbye" if the state is false.
Can anyone help me, please?

答:
make display an asynchronous function and you can also use es6 for your function deceleration not compulsory though

```<code>const display = async _ => {
    await this.setState({
      test: !this.state.test
    });
    await console.log(this.state.test)
  }
</code>```

//now your button should appear like this

```<code><button onClick={_ => display()}>Click me!</button>
</code>```

Body:
I'm learning React, and actually don't understand why my state does not change immediately when I press a button, with a click event. I mean, I created a state "test: false", but when I click on my button, I just want to change the state, so I used setState. But the console still shows me the "false" when I click for the first time.

Here's a Codesandbox to illustrate my example.

import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: false
    };
    this.display.bind(this);
  }
  display() {
    this.setState({
      test: true
    });
    console.log(this.state.test)
  }
  render() {
    return (

        <button onClick={() => this.display()}>Click me!</button>

    );
  }
}

export default App;

I also want to show  "Hello" if state is true and "Goodbye" if the state is false.
Can anyone help me, please?

Body:
make display an asynchronous function and you can also use es6 for your function deceleration not compulsory though

const display = async _ => {
    await this.setState({
      test: !this.state.test
    });
    await console.log(this.state.test)
  }

//now your button should appear like this

<button onClick={_ => display()}>Click me!</button>


问:
Stubbing/mocking/spying methods of target test class
I need to test a method in a angular class. This method invokes another method in same class, so I need to stub/mock that invoked method.

I tried spyOn with callFake, but that doesn't work.

Whats the correct way of doing it?

答: jasmine.createSpy worked for me.</p>

Body: jasmine.createSpy worked for me.


问:
How do I manually initialize a Spring Boot repository without using beans or annotations? (Kotlin)
I want to initialize a repository object in Spring Boot without having to make it a bean or an Autowired property.

I just want to do feedRepository = FeedRepository() in Kotlin. Why won't Spring Boot allow me to do this? Why does it have to be autowired or a bean?

here's my code:

```<code>@Component
class UriParser() {
    @Autowired
    lateinit var uriRepository: UriRepository

    @Autowired
    lateinit var hostRepository: HostRepository

    @Autowired
    lateinit var feedRepository: FeedRepository

    fun parseUri(uri: String) : Feed {
        val urlRepository = UriRepository()
        val uri = URI(uri)

        val uriRecord = uriRepository.save(Uri(scheme = uri.scheme, host = uri.host, port = uri.port))
        hostRepository.save(Host(host = uri.host))

        return feedRepository.save(Feed(uriId = uriRecord.id))
    }
}
</code>```

Edit: ok so here's better context as to why I can't autowire things. Basically I'm doing this within a static function so I have absolutely no access to beans or autowired properties:

```<code>@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
     KafkaScheduler().init()
}
</code>```

The Kafka scheduler basically executes several threads which all listen to kafka topics:

```<code>class KafkaScheduler() {
    // this doesn't work....
    @Autowired
    lateinit var feedRepository: FeedRepository

    fun init() {
        val threads = arrayOf(
            {
                QueueListener().init()
            },
            {
                PrefetchListener().init()
            },
            {
                FetchListener().init()
            }
        )

        val service = Executors.newFixedThreadPool(threads.size)

        for (thread in threads) {
            service.submit(thread)
        }
    }
}
</code>```

however, I can't autowire the KafkaScheduler class as a bean within a static method so I can't really make that a component or autowire any repositories, as far as I know.

答:
Well I figured it out. A simple @PostConstruct annotation solves everything I need for this. Essentially, I just mark KafkaScheduler as a @Component, autowire everything I need within it, the only difference is I added @PostConstruct to the init method so I have access to the autowired properties. Then I can autowire the repositories wherever I need them (in this case within QueueListener which uses UriParser)

```<code>@Component
class KafkaScheduler() {
    @Autowired
    lateinit var queueListener: QueueListener

    @Autowired
    lateinit var prefetchListener: PrefetchListener

    @Autowired
    lateinit var fetchListener: FetchListener

    @PostConstruct
    fun init() {
        val threads = arrayOf(
            {
                queueListener.init()
            },
            {
                prefetchListener.init()
            },
            {
                fetchListener.init()
            }
        )

        val service = Executors.newFixedThreadPool(threads.size)

        for (thread in threads) {
            service.submit(thread)
        }
    }
}
</code>```

Body:
I want to initialize a repository object in Spring Boot without having to make it a bean or an Autowired property.

I just want to do feedRepository = FeedRepository() in Kotlin. Why won't Spring Boot allow me to do this? Why does it have to be autowired or a bean?

here's my code:

@Component
class UriParser() {
    @Autowired
    lateinit var uriRepository: UriRepository

    @Autowired
    lateinit var hostRepository: HostRepository

    @Autowired
    lateinit var feedRepository: FeedRepository

    fun parseUri(uri: String) : Feed {
        val urlRepository = UriRepository()
        val uri = URI(uri)

        val uriRecord = uriRepository.save(Uri(scheme = uri.scheme, host = uri.host, port = uri.port))
        hostRepository.save(Host(host = uri.host))

        return feedRepository.save(Feed(uriId = uriRecord.id))
    }
}

Edit: ok so here's better context as to why I can't autowire things. Basically I'm doing this within a static function so I have absolutely no access to beans or autowired properties:

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
     KafkaScheduler().init()
}

The Kafka scheduler basically executes several threads which all listen to kafka topics:

class KafkaScheduler() {
    // this doesn't work....
    @Autowired
    lateinit var feedRepository: FeedRepository

    fun init() {
        val threads = arrayOf(
            {
                QueueListener().init()
            },
            {
                PrefetchListener().init()
            },
            {
                FetchListener().init()
            }
        )

        val service = Executors.newFixedThreadPool(threads.size)

        for (thread in threads) {
            service.submit(thread)
        }
    }
}

however, I can't autowire the KafkaScheduler class as a bean within a static method so I can't really make that a component or autowire any repositories, as far as I know.

Body:
Well I figured it out. A simple @PostConstruct annotation solves everything I need for this. Essentially, I just mark KafkaScheduler as a @Component, autowire everything I need within it, the only difference is I added @PostConstruct to the init method so I have access to the autowired properties. Then I can autowire the repositories wherever I need them (in this case within QueueListener which uses UriParser)

@Component
class KafkaScheduler() {
    @Autowired
    lateinit var queueListener: QueueListener

    @Autowired
    lateinit var prefetchListener: PrefetchListener

    @Autowired
    lateinit var fetchListener: FetchListener

    @PostConstruct
    fun init() {
        val threads = arrayOf(
            {
                queueListener.init()
            },
            {
                prefetchListener.init()
            },
            {
                fetchListener.init()
            }
        )

        val service = Executors.newFixedThreadPool(threads.size)

        for (thread in threads) {
            service.submit(thread)
        }
    }
}


问:
Site search in asp .net application
May I know what are the best practices for implementing a site search in ASP .net web app. The user should be able to enter some keywords and get related links with the keyword. I have just started researching. It would be great if you put  on your ideas.</p>

答:
Here is C# Code

protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    GridView2.PageIndex = e.NewPageIndex;
    this.Searchmyform();
}

protected void Search(object sender, EventArgs e)
{
    this.Searchmyform();
}

private void Searchmyform()
{
    using (SqlCommand cmd = new SqlCommand())
    {
        string sql = "SELECT * FROM [test].[dbo].[myform]";

        if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
        {
            sql += "  where name like '" + txtSearch.Text + "%' or contact like '" + txtSearch.Text + "%'" +
                   " or email like '" + txtSearch.Text + "%' ";
        }

        cmd.CommandText = sql;
        cmd.Connection = conn;
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();
            sda.Fill(dt);
            GridView2.DataSource = dt;
            GridView2.DataBind();
        }
    }
}
```

<p>Aspx code is such that</p>

<pre class="lang-html prettyprint-override"><code><div class="topnav card-body">
    <div class="search-container-lg float-right">
        <asp:TextBox ID="txtSearch" runat="server"
                  OnTextChanged="Search"
                  AutoPostBack="true"
                  placeholder="Search.."
                  CssClass="">
        </asp:TextBox>
...
</code>```

ContentLicense: CC BY-SA 2.5

Title: Site search in asp .net application

Body:
Here is C# Code

protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    GridView2.PageIndex = e.NewPageIndex;
    this.Searchmyform();
}

protected void Search(object sender, EventArgs e)
{
    this.Searchmyform();
}

private void Searchmyform()
{
    using (SqlCommand cmd = new SqlCommand())
    {
        string sql = "SELECT * FROM [test].[dbo].[myform]";

        if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
        {
            sql += "  where name like '" + txtSearch.Text + "%' or contact like '" + txtSearch.Text + "%'" +
                   " or email like '" + txtSearch.Text + "%' ";
        }

        cmd.CommandText = sql;
        cmd.Connection = conn;
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();
            sda.Fill(dt);
            GridView2.DataSource = dt;
            GridView2.DataBind();
        }
    }
}

Aspx code is such that

<div class="topnav card-body">
    <div class="search-container-lg float-right">
        <asp:TextBox ID="txtSearch" runat="server"
                  OnTextChanged="Search"
                  AutoPostBack="true"
                  placeholder="Search.."
                  CssClass="">
        </asp:TextBox>
...


问:
Loop in Firebase Recycler Adapter
I'm getting the list of user ids from database. And its getting the values correctly. I'm using FirebaseRecyclerAdapter and when I iterate that list in onBindViewHolder the loops runs as the size of list. For example over here  :

```<code> adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
            @Override
            protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {
               for (int i = 0 ; i<list.size() ; i++){
                  Toast.makeText(List.this,"List :" +list.get(i), Toast.LENGTH_SHORT).show();
               }
            }
 }
</code>```

Over here I have 5 item in list and while iterating I'm toasting each item . So in here the loop run for 25 time, its shows each item 5 time in sequence. First it shows 5 items orderly after showing last item it start toasting from first one again and continues till 5 time as the size of list.
So how do I cater this and make it only iterate the whole items for once only?

答:
onBindViewHolder is called by RecyvlerView to display the data at the specified position. Since you have all the data in a List, their corresponding index will be the same as the position of the itemView.

In your function, you are iterating over all the items in the list for each itemView which the ViewHolder is generating.

You have to remove the for loop from your code and simply use the position as the index to retrieve data from your list, whose index is same as position.

Try this code:

```<code>adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
            @Override
            protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {

                  Toast.makeText(List.this,"List :" +list.get(position), Toast.LENGTH_SHORT).show();

            }
 }
</code>```

For this method, every time an itemView is generated, it will be at a position and with this as an index, you can easily get the data from the list.

For your scenario, since you are already inside each itemView being generated inside the onBindViewHolder, and then you are iterating for each element in your list, hence every item is being displayed exactly the same number of times, as the size of the list.

Title: Loop in Firebase Recycler Adapter

Body:
I'm getting the list of user ids from database. And its getting the values correctly. I'm using FirebaseRecyclerAdapter and when I iterate that list in onBindViewHolder the loops runs as the size of list. For example over here  :

 adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
            @Override
            protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {
               for (int i = 0 ; i<list.size() ; i++){
                  Toast.makeText(List.this,"List :" +list.get(i), Toast.LENGTH_SHORT).show();
               }
            }
 }

Over here I have 5 item in list and while iterating I'm toasting each item . So in here the loop run for 25 time, its shows each item 5 time in sequence. First it shows 5 items orderly after showing last item it start toasting from first one again and continues till 5 time as the size of list.
So how do I cater this and make it only iterate the whole items for once only?

Body:
onBindViewHolder is called by RecyvlerView to display the data at the specified position. Since you have all the data in a List, their corresponding index will be the same as the position of the itemView.

In your function, you are iterating over all the items in the list for each itemView which the ViewHolder is generating.

You have to remove the for loop from your code and simply use the position as the index to retrieve data from your list, whose index is same as position.

Try this code:

adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
            @Override
            protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {

                  Toast.makeText(List.this,"List :" +list.get(position), Toast.LENGTH_SHORT).show();

            }
 }

For this method, every time an itemView is generated, it will be at a position and with this as an index, you can easily get the data from the list.

For your scenario, since you are already inside each itemView being generated inside the onBindViewHolder, and then you are iterating for each element in your list, hence every item is being displayed exactly the same number of times, as the size of the list.


问:
Plotting a dictionary of counters as a multi bar graph in Python
I have a python dictionary of Counters as an output as shown below:

```<code>{0:Counter({1:100}),1:Counter({1:100,2:30,3:50},2:Counter({2:70,4:10})}
</code>```

How do I plot this as a multi bar graph with key being the X-axis and frequency of each element in the Counter as the Y-axis?.

答:
IIUC:

```<code>from collections import Counter
pd.DataFrame({0:Counter({1:100}),1:Counter({1:100,2:30,3:50}),2:Counter({2:70,4:10})}).T.plot.bar()
</code>```

Body:
I have a python dictionary of Counters as an output as shown below:

{0:Counter({1:100}),1:Counter({1:100,2:30,3:50},2:Counter({2:70,4:10})}

How do I plot this as a multi bar graph with key being the X-axis and frequency of each element in the Counter as the Y-axis?.

Body:
IIUC:

from collections import Counter
pd.DataFrame({0:Counter({1:100}),1:Counter({1:100,2:30,3:50}),2:Counter({2:70,4:10})}).T.plot.bar()


问:
Clear Ref in useEffect Cleanup
I've a hook called useInitial defined as

```<code>
function useInitial(value) {

  const ref = useRef();

  // Store current value in ref

  useEffect(() => {
    ref.current = value;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Return previous value (happens before update in useEffect above)

  return ref.current;
}
</code>```

I use it in a function component to store an initial value for a field

```<code>
const Calculator = ({ current_field }) => {
  const previousField = usePrevious(current_field);
  const intialContent = useInitial(current_field.content);
  useEffect(() => {
    calculateTotals();
    if (previousField) {
      console.log({ intialContent });
      console.log(previousField.content);
    }
    return () => {
     //DO something here to clear and reset the value stored in intialContent.
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current_field]);
  return null;
};
</code>```

If the CurrentField changes I want the intialValue for the new field and not the 1st one.

答:
I thought it through and found the solution.

useInitial hook can be modified to have a deps array as inupt like

```<code>function useInitial(value, deps) {

  const ref = useRef();

  // Store current value in ref

  useEffect(() => {
    ref.current = value;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  // Return previous value (happens before update in useEffect above)

  return ref.current;
}
</code>```

And then usage of this could be to send current_field in deps array.

```<code>const Calculator = ({ current_field }) => {
  const previousField = usePrevious(current_field);
  const intialContent = useInitial(current_field.content);
  useEffect(() => {
    calculateTotals();
    if (previousField) {
      console.log({ intialContent });
      console.log(previousField.content);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current_field]);
  return null;
};
</code>```

This will re-trigger the useEffect inside useInitial after field change and new field's initial value will be stored.

Title: Clear Ref in useEffect Cleanup

Body:
I've a hook called useInitial defined as

function useInitial(value) {

  const ref = useRef();

  // Store current value in ref

  useEffect(() => {
    ref.current = value;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Return previous value (happens before update in useEffect above)

  return ref.current;
}

I use it in a function component to store an initial value for a field

const Calculator = ({ current_field }) => {
  const previousField = usePrevious(current_field);
  const intialContent = useInitial(current_field.content);
  useEffect(() => {
    calculateTotals();
    if (previousField) {
      console.log({ intialContent });
      console.log(previousField.content);
    }
    return () => {
     //DO something here to clear and reset the value stored in intialContent.
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current_field]);
  return null;
};

If the CurrentField changes I want the intialValue for the new field and not the 1st one.

Body:
I thought it through and found the solution.

useInitial hook can be modified to have a deps array as inupt like

function useInitial(value, deps) {

  const ref = useRef();

  // Store current value in ref

  useEffect(() => {
    ref.current = value;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  // Return previous value (happens before update in useEffect above)

  return ref.current;
}

And then usage of this could be to send current_field in deps array.

const Calculator = ({ current_field }) => {
  const previousField = usePrevious(current_field);
  const intialContent = useInitial(current_field.content);
  useEffect(() => {
    calculateTotals();
    if (previousField) {
      console.log({ intialContent });
      console.log(previousField.content);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current_field]);
  return null;
};

This will re-trigger the useEffect inside useInitial after field change and new field's initial value will be stored.


问:
SharePoint : are programmatic copy/move operations on folders and document sets guaranteed to be atomic?
Just wondering if programmatic operations in SharePoint that allow moving or copying folders (and their content) and document sets (and their content) are guaranteed to be atomic, so they fail or succeed as a whole ?

Examples of calls are SPFolder.Copy, DocumentSet.Import, SP.MoveCopyUtil, CreateCopyJobs, etc

答: I think so, they should be atmoic so they fail or succeed as a whole. </p>


问:
How to make autofill into add/remove field dynamically using jquery?
I am doing a program using laravel. I use add/remove field with jquery. The first field grab the data from database to list out the person's name.

```<code>     <div class="container table-responsive col-lg-10">
          <form method="post" id="dynamic_form">
            <span id="result"></span>
             <table class="table table-hover table-responsive table-bordered" id="user_table">
           <thead>
            <tr>
                <td class="text-center col-lg-3">Nama</th>
                <td class="text-center col-lg-2">No Personal</th>
                <td class="text-center col-lg-1">Jabatan</th>
                <td class="text-center col-lg-1">Telefon</th>
                <td class="text-center col-lg-1">Ext</th>
                <td class="text-center col-lg-1">Action</th>
            </tr>
           </thead>
           <tbody>

           </tbody>
           <tfoot>
            <tr>
              <td colspan="2" align="right"> </td>
              <td></td>
            </tr>
           </tfoot>
       </table>
    </div>
    <script>
      $(document).ready(function(){

      var count = 1;

      dynamic_field(count);

      function dynamic_field(number)
      {
      html = '<tr>';
     html += '<td><select id="nama" name="nama[]" class="form-control"><option value="">--Pilih--</option><?php foreach($staff as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
    html += '<td><input type="text" name="no_personal[]" class="form-control" /></td>';
    html += '<td><input type="text" name="jabatan[]" class="form-control" /></td>';
    html += '<td><input type="text" name="telefon[]" class="form-control" /></td>';
    html += '<td><input type="text" name="ext[]" class="form-control" /></td>';
    if(number > 1)
    {
        html += '<td class="text-center"><button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button></td></tr>';
        $('tbody').append(html);
    }
    else
    {
        html += '<td class="text-center"><button type="button" name="add" id="add" class="btn btn-success">Tambah Pegawai</button></td></tr>';
        $('tbody').html(html);
    }
}

   $(document).on('change', '.nama', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_staff/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#no_personal').val(data.Nobadan);
                $('#jabatan').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);
          }
      });
    }
    else
    {
      $('#no_personal').empty();
      $('#jabatan').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });

 $(document).on('click', '#add', function(){
  count++;
  dynamic_field(count);
  });

 $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
 });

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

I had edited the js code:

```<code>    function dynamic_field(number)
 {
  html = '<tr>';
     html += '<td><select id="nama_'+ count +'" name="nama[]" class="form-control"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
    html += '<td><input id="nb_'+ count +'" type="text" name="no_badan[]" class="form-control"  value="nb_'+ count +'" /></td>';
    html += '<td><input id="sek_'+ count +'" type="text" name="seksyen[]" class="form-control" /></td>';
    html += '<td><input id="tel_'+ count +'" type="text" name="telefon[]" class="form-control" /></td>';
    html += '<td><input id="ext_'+ count +'" type="text" name="ext[]" class="form-control" /></td>';
    if(number > 1)
    {
        html += '<td class="text-center"><button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button></td></tr>';
        $('tbody').append(html);
    }
    else
    {
        html += '<td class="text-center"><button type="button" name="add" id="add" class="btn btn-success">Tambah</button></td></tr>';
        $('tbody').html(html);
    }
 }

 $(document).on('change', '.nama_'+ count +'', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_sta/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#nb_'+ count +'').val(data.Nobadan);
                $('#seksyen').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);
          }
      });
    }
    else
    {
      $('#nb_'+ count +'').empty();
      $('#seksyen').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });

  $(document).on('click', '#add', function(){
   count++;
   dynamic_field(count);
 });

  $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
  });

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

When the first field（staff name）selected，the information  about no_personal, jabatan, telefon and ext will be filled automatically into the field. The information grabbed using this ajax url:

```<code> url : 'add_demo/get_staff/'+staffID,
</code>```

The controller for that is:

```<code>$data = staffs::where('staffID', $staffID)
            ->select('staffs.No_pers', 'staffs.JabID', 'staffs.notel', 'staffs.ext')
            ->first();

return json_encode($data);
</code>```

I can list out the staff name in the selection box. But when I selected the staff name, the information is not filled into the fields.

The field had been given an id like this:

```<code> html += '<td><input id="nb_'+ count++ +'" type="text" name="no_badan[]" class="form-control" /></td>';
</code>```

How to improvised the code? I tried to put id in the added fields, but it gives error of same id name for added fields.

答:
There is the easiest way to create a component like this. Please look at my given below snippets code.

$(document).on('click','.add',function(){
        var clonned = $(this).parents('.clonable:last-child').clone();
        parentId = clonned.attr('parentId');
        clonned.attr('parentId',parseInt(parentId)+1);
        clonned.find('input[type="text"]').each(function(){
            return $(this).val('');
        })
        $('.clonable').parents('tbody').append(clonned);
    });
    $(document).on('click','.remove',function(){
        $(this).parents('.clonable').remove();
    });

   $(document).on('change', '.nama', function(){
        var staffID = $(this).val();
        var parentId = $(this).parents('.clonable').attr('parentId');
        if(staffID){
            jQuery.ajax({
                url : 'add_demo/get_staff/'+staffID,
                type : "GET",
                dataType : "json",
                success:function(data){
                    console.log(data);
                    $('tr[parentId="'+parentId+'"] input[name="no_personal[]"]').val(data.Nobadan);
                    $('tr[parentId="'+parentId+'"] input[name="jabatan[]"]').val(data.SectionID);
                    $('tr[parentId="'+parentId+'"] input[name="telefon[]"]').val(data.notelttp);
                    $('tr[parentId="'+parentId+'"] input[name="ext[]"]').val(data.ext);
                }
            });
        }else{
            $('tr[parentId="'+parentId+'"] input[name="no_personal[]"]').val('');
            $('tr[parentId="'+parentId+'"] input[name="jabatan[]"]').val('');
            $('tr[parentId="'+parentId+'"] input[name="telefon[]"]').val('');
            $('tr[parentId="'+parentId+'"] input[name="ext[]"]').val('');
        }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.clonable .add{
  display: none;
}
.clonable:last-child .add{
  display: inline-block !important;
}
.clonable:only-child .remove{
  display: none !important;
}</code>```

        <form method="post" id="dynamic_form">

                        Nama
                        No Personal
                        Jabatan
                        Telefon
                        Ext
                        Action

                            <select id="nama" name="nama[]" class="form-control nama">
                                <option value="">--Pilih--</option>
                                <?php foreach($staff as $key => $value){?>
                                    <option value="<?=$key?>"><?=addslashes($value)?></option>
                                <?php }?>
                            </select>

                        <input type="text" id="no_personal" name="no_personal[]" class="form-control" />
                        <input type="text" id="jabatan" name="jabatan[]" class="form-control" />
                        <input type="text" id="telefon" name="telefon[]" class="form-control" />
                        <input type="text" id="ext" name="ext[]" class="form-control" />

                            <button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button>
                            <button type="button" name="add" id="add" class="btn btn-success add">Tambah Pegawai</button>

        </form>

```

Body:
I am doing a program using laravel. I use add/remove field with jquery. The first field grab the data from database to list out the person's name.

          <form method="post" id="dynamic_form">

                Nama
                No Personal
                Jabatan
                Telefon
                Ext
                Action

I had edited the js code:

    function dynamic_field(number)
 {
  html = '
';
     html += '<select id="nama_'+ count +'" name="nama[]" class="form-control"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select>	';
    html += '<input id="nb_'+ count +'" type="text" name="no_badan[]" class="form-control"  value="nb_'+ count +'" />	';
    html += '<input id="sek_'+ count +'" type="text" name="seksyen[]" class="form-control" />	';
    html += '<input id="tel_'+ count +'" type="text" name="telefon[]" class="form-control" />	';
    html += '<input id="ext_'+ count +'" type="text" name="ext[]" class="form-control" />	';
    if(number > 1)
    {
        html += '<button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button>
';
        $('tbody').append(html);
    }
    else
    {
        html += '<button type="button" name="add" id="add" class="btn btn-success">Tambah</button>
';
        $('tbody').html(html);
    }
 }

 $(document).on('change', '.nama_'+ count +'', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_sta/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#nb_'+ count +'').val(data.Nobadan);
                $('#seksyen').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);
          }
      });
    }
    else
    {
      $('#nb_'+ count +'').empty();
      $('#seksyen').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });

  $(document).on('click', '#add', function(){
   count++;
   dynamic_field(count);
 });

  $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
  });

  });
 </script>

When the first field（staff name）selected，the information  about no_personal, jabatan, telefon and ext will be filled automatically into the field. The information grabbed using this ajax url:

 url : 'add_demo/get_staff/'+staffID,

The controller for that is:

$data = staffs::where('staffID', $staffID)
            ->select('staffs.No_pers', 'staffs.JabID', 'staffs.notel', 'staffs.ext')
            ->first();

return json_encode($data);

I can list out the staff name in the selection box. But when I selected the staff name, the information is not filled into the fields.

The field had been given an id like this:

 html += '<input id="nb_'+ count++ +'" type="text" name="no_badan[]" class="form-control" />	';

How to improvised the code? I tried to put id in the added fields, but it gives error of same id name for added fields.

Body:
There is the easiest way to create a component like this. Please look at my given below snippets code.

$(document).on('click','.add',function(){
        var clonned = $(this).parents('.clonable:last-child').clone();
        parentId = clonned.attr('parentId');
        clonned.attr('parentId',parseInt(parentId)+1);
        clonned.find('input[type="text"]').each(function(){
            return $(this).val('');
        })
        $('.clonable').parents('tbody').append(clonned);
    });
    $(document).on('click','.remove',function(){
        $(this).parents('.clonable').remove();
    });

   $(document).on('change', '.nama', function(){
        var staffID = $(this).val();
        var parentId = $(this).parents('.clonable').attr('parentId');
        if(staffID){
            jQuery.ajax({
                url : 'add_demo/get_staff/'+staffID,
                type : "GET",
                dataType : "json",
                success:function(data){
                    console.log(data);
                    $('tr[parentId="'+parentId+'"] input[name="no_personal[]"]').val(data.Nobadan);
                    $('tr[parentId="'+parentId+'"] input[name="jabatan[]"]').val(data.SectionID);
                    $('tr[parentId="'+parentId+'"] input[name="telefon[]"]').val(data.notelttp);
                    $('tr[parentId="'+parentId+'"] input[name="ext[]"]').val(data.ext);
                }
            });
        }else{
            $('tr[parentId="'+parentId+'"] input[name="no_personal[]"]').val('');
            $('tr[parentId="'+parentId+'"] input[name="jabatan[]"]').val('');
            $('tr[parentId="'+parentId+'"] input[name="telefon[]"]').val('');
            $('tr[parentId="'+parentId+'"] input[name="ext[]"]').val('');
        }
    });

.clonable .add{
  display: none;
}
.clonable:last-child .add{
  display: inline-block !important;
}
.clonable:only-child .remove{
  display: none !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container table-responsive col-lg-10">
        <form method="post" id="dynamic_form">
            <span id="result"></span>
            <table class="table table-hover table-responsive table-bordered" id="user_table">
                <thead>
                    <tr>
                        <th class="text-center col-lg-3">Nama</th>
                        <th class="text-center col-lg-2">No Personal</th>
                        <th class="text-center col-lg-1">Jabatan</th>
                        <th class="text-center col-lg-1">Telefon</th>
                        <th class="text-center col-lg-1">Ext</th>
                        <th class="text-center col-lg-1">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="clonable" parentId="1">
                        <td>
                            <select id="nama" name="nama[]" class="form-control nama">
                                <option value="">--Pilih--</option>
                                <?php foreach($staff as $key => $value){?>
                                    <option value="<?=$key?>"><?=addslashes($value)?></option>
                                <?php }?>
                            </select>
                        </td>
                        <td><input type="text" id="no_personal" name="no_personal[]" class="form-control" /></td>
                        <td><input type="text" id="jabatan" name="jabatan[]" class="form-control" /></td>
                        <td><input type="text" id="telefon" name="telefon[]" class="form-control" /></td>
                        <td><input type="text" id="ext" name="ext[]" class="form-control" /></td>
                        <td class="text-center">
                            <button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button>
                            <button type="button" name="add" id="add" class="btn btn-success add">Tambah Pegawai</button>
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="6" align="right">&nbsp;</td>
                    </tr>
                </tfoot>
            </table>
        </form>
    </div>


问:
Use volatile class members for interrupt handling
Lets suppose it is embedded development of some ARM controller. Lets suppose we have some variable, which can be assigned from an interrupt or "mainThread" - (is it a "main loop" or RTOS thread). In C world volatile keyword should be used in this case and code may look like this:

```<code>/* Some subsystem .C file */
static volatile uint8_t state;

void on_main_thread(void) {
    state = 1;     /* Changing state in this context */
}

void on_interrupt(void) {
    state = 0;     /* Changing state from interrupt */
}

uint8_t get_state(void) {
    return state;  /* Getting the state in whatever context */
}
</code>```

volatile keyword is essential in this situation. Now our company rewrites some code to C++ and the same subsystem example looks like this (I use enum here to emphasize the problem)

```<code>class SomeSubsystem
{
public:
    enum class States
    {
        Off,
        Idle,
        Up,
        Down,
    };

    States getState() const { return mState; }

    void onMainThread(void) {
           mState = States::Idle;     // Changing state in this context
    }

    // Somehow this function is called from the interrupt
    void onInterrupt(void) {
           mState = States::Up;     // Changing state from interrupt
    }
private:
    States mState;   // <-- Here! Volatile?
//...
};
</code>```

Now States mState should be volatile because it is shared among different contexts. But If one sets it as volatile... Then volatile works like plague for C++ class and one have to volatilize everything around. Like volatile enum class States, getState() volatile etc. Which doesn't look good for me (am I wrong?)

So. What is the right way to handle this situation in C++?

P.S. I would try to define "this situation" as: "possible usage of a class members from different contexts like interrupts and normal code execution"

答:
This could work if you only need a single instance of SomeSubsystem in your program (which I assume as per the c code you posted.

If you need multiple instances, then maybe you could modify mState to be a States array or some similar structure instead.

```<code>class SomeSubsystem
{
public:
    enum class States
    {
        Off,
        Idle,
        Up,
        Down,
    };

    States getState() const { return mState; }

    void onMainThread(void) {
           mState = States::Idle;     // Changing state in this context
    }

    // Somehow this function is called from the interrupt
    void onInterrupt(void) {
           mState = States::Up;     // Changing state from interrupt
    }
// Make mState public in order to access it from the rest of your code
// Otherwise, keep it private and create static set/get functions
public:
    static volatile States mState;   // <-- Here! Volatile?
//...
};
</code>```

Then define mState somewhere (eg. in SomeSubsystem.cpp)

```<code>volatile SomeSubsystem::States SomeSubsystem::mState = SomeSubsystem::States::Off;
</code>```

Now you are able to access mState from anywhere in your code like this

```<code>SomeSubsystem::mState = SomeSubsystem::States::Off;
</code>```

Body:
Lets suppose it is embedded development of some ARM controller. Lets suppose we have some variable, which can be assigned from an interrupt or "mainThread" - (is it a "main loop" or RTOS thread). In C world volatile keyword should be used in this case and code may look like this:

/* Some subsystem .C file */
static volatile uint8_t state;

void on_main_thread(void) {
    state = 1;     /* Changing state in this context */
}

void on_interrupt(void) {
    state = 0;     /* Changing state from interrupt */
}

uint8_t get_state(void) {
    return state;  /* Getting the state in whatever context */
}

volatile keyword is essential in this situation. Now our company rewrites some code to C++ and the same subsystem example looks like this (I use enum here to emphasize the problem)

class SomeSubsystem
{
public:
    enum class States
    {
        Off,
        Idle,
        Up,
        Down,
    };

    States getState() const { return mState; }

    void onMainThread(void) {
           mState = States::Idle;     // Changing state in this context
    }

    // Somehow this function is called from the interrupt
    void onInterrupt(void) {
           mState = States::Up;     // Changing state from interrupt
    }
private:
    States mState;   // <-- Here! Volatile?
//...
};

Now States mState should be volatile because it is shared among different contexts. But If one sets it as volatile... Then volatile works like plague for C++ class and one have to volatilize everything around. Like volatile enum class States, getState() volatile etc. Which doesn't look good for me (am I wrong?)

So. What is the right way to handle this situation in C++?

P.S. I would try to define "this situation" as: "possible usage of a class members from different contexts like interrupts and normal code execution"

Body:
This could work if you only need a single instance of SomeSubsystem in your program (which I assume as per the c code you posted.

If you need multiple instances, then maybe you could modify mState to be a States array or some similar structure instead.

class SomeSubsystem
{
public:
    enum class States
    {
        Off,
        Idle,
        Up,
        Down,
    };

    States getState() const { return mState; }

    void onMainThread(void) {
           mState = States::Idle;     // Changing state in this context
    }

    // Somehow this function is called from the interrupt
    void onInterrupt(void) {
           mState = States::Up;     // Changing state from interrupt
    }
// Make mState public in order to access it from the rest of your code
// Otherwise, keep it private and create static set/get functions
public:
    static volatile States mState;   // <-- Here! Volatile?
//...
};

Then define mState somewhere (eg. in SomeSubsystem.cpp)

volatile SomeSubsystem::States SomeSubsystem::mState = SomeSubsystem::States::Off;

Now you are able to access mState from anywhere in your code like this

SomeSubsystem::mState = SomeSubsystem::States::Off;


问:
jQuery how to select options by values?
How to select options which are not in 'restrictedIds', for example, selector should select the options with values 24 and 31.
Also I know how it could be done with using '.inArray' and '.each()' but it would be good to look at yours solutions. Thank you.</p>

```<code>...
var restrictedIds='0,38,23';
...
<select class="text4" size="1" name="drivers">
        <option value="0"></option>
        <option value="24">test1</option>
        <option value="31">test2</option>
        <option value="38">test3</option>
        <option value="23">test4</option>
</select>
</code>```

答:
The simplest thing to do is use the val function http://api.jquery.com/val/. It has support to read and write values to select having multiple options.

Here is an example that may work for you.

```<code><!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p></p>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>

  </select>
  <select id="multiple" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
  </select>
<script>
    function displayVals() {
    $("#multiple").val([1,3]);
      var singleValues = $("#single").val();
      var multipleValues = $("#multiple").val() || [];
      $("p").html("<b>Single:</b> " +
                  singleValues +
                  " <b>Multiple:</b> " +
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);
    displayVals();

</script>

</body>
</html>
</code>```

Title: jQuery how to select options by values?

Body:
How to select options which are not in 'restrictedIds', for example, selector should select the options with values 24 and 31.
Also I know how it could be done with using '.inArray' and '.each()' but it would be good to look at yours solutions. Thank you.

...
var restrictedIds='0,38,23';
...
<select class="text4" size="1" name="drivers">
        <option value="0"></option>
        <option value="24">test1</option>
        <option value="31">test2</option>
        <option value="38">test3</option>
        <option value="23">test4</option>
</select>

Body:
The simplest thing to do is use the val function http://api.jquery.com/val/. It has support to read and write values to select having multiple options.

Here is an example that may work for you.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p></p>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>

  </select>
  <select id="multiple" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
  </select>
<script>
    function displayVals() {
    $("#multiple").val([1,3]);
      var singleValues = $("#single").val();
      var multipleValues = $("#multiple").val() || [];
      $("p").html("<b>Single:</b> " +
                  singleValues +
                  " <b>Multiple:</b> " +
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);
    displayVals();

</script>

</body>
</html>


问:
Why dows exec() function work in raw code but not within a function or a class in Python 3.7?
Below I show 2 usage examples of exec() function in Python 3.7, one in a class, and one in raw code. Only the latter works properly. Could someone explain to me possible reasons and suggest solutions?

```<code>#!/usr/bin/env python

import pandas as pd

################################# exec() WITHIN A CLASS ###################################
class Test:

    def __init__(self):
        pass

    def f(self):
        pose, frame, min_complexE, min_lEfree, best_structvar, best_conf, complexE, ligandE_bound, proteinE_bound, \
        min_lEfree = [None] * 10
        table = pd.read_table("sample_scores.txt", delim_whitespace=True, skiprows=[0])  # 1st line is a comment
        table_columns = table.columns
        for i, row in table.iterrows():
            # Variable assignemnt
            for varname in ["pose", "frame", "min_complexE", "min_lEfree", "best_structvar", "best_conf",
                            "complexE", "ligandE_bound", "proteinE_bound", "min_lEfree", "Eint"]:
                if varname in table_columns:
                    exec("%s = %s" % (varname, row[varname]), globals(), globals())
                else:
                    exec("%s = None" % (varname), globals(), globals())

            print("proteinE_bound within class =", proteinE_bound)

    def caller1(self):
        self.f()

    def caller2(self):
        self.caller1()

Test().caller2()

################################# exec() IN RAW CODE ###################################
pose, frame, min_complexE, min_lEfree, best_structvar, best_conf, complexE, ligandE_bound, proteinE_bound, \
min_lEfree = [None] * 10
table = pd.read_table("sample_scores.txt", delim_whitespace=True, skiprows=[0])  # 1st line is a comment
table_columns = table.columns
for i, row in table.iterrows():
    # Variable assignemnt
    for varname in ["pose", "frame", "min_complexE", "min_lEfree", "best_structvar", "best_conf",
                    "complexE", "ligandE_bound", "proteinE_bound", "min_lEfree", "Eint"]:
        if varname in table_columns:
            exec("%s = %s" % (varname, row[varname]), globals(), globals())
        else:
            exec("%s = None" % (varname), globals(), globals())
    print("proteinE_bound as raw code =", proteinE_bound)
</code>```

The contents of the "sample_scores.txt" file are:

```<code># Contains all results. For the best result for each compound please refer to file BEST_RESULTS.
molname Eint    complexE    ligandE_bound   proteinE_bound  stereoisomer    ionstate    tautomer    pose    frame
LEM00001847 -63.000496 -17406.593934 -84.868633 -17258.724804 1 1 1 1 571
LEM00001847 -62.412897 -17474.918135 -64.778724 -17347.726515 1 1 1 1 171
LEM00001847 -61.249384 -17423.452346 -82.875735 -17279.327226 1 1 1 1 531
</code>```

答:
I found the answer although there are still some obscure points in it. Basically, I had to remove the line

```<code>pose, frame, min_complexE, min_lEfree, best_structvar, best_conf, complexE, ligandE_bound, proteinE_bound, \
        min_lEfree = [None] * 10
</code>```

where I initialized the variables to be assigned by exec(). If these variables do not pre-exist, then they are successfully added to the globals() and are accessible within the function as individual variables.

Now the obscure points:

1) Even if I initialize these 10 variables to None, in every iteration of the for loop their values are updated in globals() dictionary but not when I call then with their names as individual variables.

2) According to docs.python.org exec(__object, __globals=..., __locals=...). It seems that only the given '__globals' dictionary is updated with the new variables. So although in my code above I use

```<code>exec("%s = %s" % (varname, row[varname]), globals(), globals())
</code>```

this works as well

```<code>exec("%s = %s" % (varname, row[varname]), locals(), globals())
</code>```

In my understanding, the latter is the right way, because you want these variables to be created within the context of the function, namely as local variables. But then why exec() updates the given '__globals' and not the given '__locals'?

Body:
Below I show 2 usage examples of exec() function in Python 3.7, one in a class, and one in raw code. Only the latter works properly. Could someone explain to me possible reasons and suggest solutions?

#!/usr/bin/env python

import pandas as pd

################################# exec() WITHIN A CLASS ###################################
class Test:

    def __init__(self):
        pass

    def f(self):
        pose, frame, min_complexE, min_lEfree, best_structvar, best_conf, complexE, ligandE_bound, proteinE_bound, \
        min_lEfree = [None] * 10
        table = pd.read_table("sample_scores.txt", delim_whitespace=True, skiprows=[0])  # 1st line is a comment
        table_columns = table.columns
        for i, row in table.iterrows():
            # Variable assignemnt
            for varname in ["pose", "frame", "min_complexE", "min_lEfree", "best_structvar", "best_conf",
                            "complexE", "ligandE_bound", "proteinE_bound", "min_lEfree", "Eint"]:
                if varname in table_columns:
                    exec("%s = %s" % (varname, row[varname]), globals(), globals())
                else:
                    exec("%s = None" % (varname), globals(), globals())

            print("proteinE_bound within class =", proteinE_bound)

    def caller1(self):
        self.f()

    def caller2(self):
        self.caller1()

Test().caller2()

################################# exec() IN RAW CODE ###################################
pose, frame, min_complexE, min_lEfree, best_structvar, best_conf, complexE, ligandE_bound, proteinE_bound, \
min_lEfree = [None] * 10
table = pd.read_table("sample_scores.txt", delim_whitespace=True, skiprows=[0])  # 1st line is a comment
table_columns = table.columns
for i, row in table.iterrows():
    # Variable assignemnt
    for varname in ["pose", "frame", "min_complexE", "min_lEfree", "best_structvar", "best_conf",
                    "complexE", "ligandE_bound", "proteinE_bound", "min_lEfree", "Eint"]:
        if varname in table_columns:
            exec("%s = %s" % (varname, row[varname]), globals(), globals())
        else:
            exec("%s = None" % (varname), globals(), globals())
    print("proteinE_bound as raw code =", proteinE_bound)

The contents of the "sample_scores.txt" file are:

# Contains all results. For the best result for each compound please refer to file BEST_RESULTS.
molname Eint    complexE    ligandE_bound   proteinE_bound  stereoisomer    ionstate    tautomer    pose    frame
LEM00001847 -63.000496 -17406.593934 -84.868633 -17258.724804 1 1 1 1 571
LEM00001847 -62.412897 -17474.918135 -64.778724 -17347.726515 1 1 1 1 171
LEM00001847 -61.249384 -17423.452346 -82.875735 -17279.327226 1 1 1 1 531

Body:
I found the answer although there are still some obscure points in it. Basically, I had to remove the line

pose, frame, min_complexE, min_lEfree, best_structvar, best_conf, complexE, ligandE_bound, proteinE_bound, \
        min_lEfree = [None] * 10

where I initialized the variables to be assigned by exec(). If these variables do not pre-exist, then they are successfully added to the globals() and are accessible within the function as individual variables.

Now the obscure points:

1) Even if I initialize these 10 variables to None, in every iteration of the for loop their values are updated in globals() dictionary but not when I call then with their names as individual variables.

2) According to docs.python.org exec(__object, __globals=..., __locals=...). It seems that only the given '__globals' dictionary is updated with the new variables. So although in my code above I use

exec("%s = %s" % (varname, row[varname]), globals(), globals())

this works as well

exec("%s = %s" % (varname, row[varname]), locals(), globals())

In my understanding, the latter is the right way, because you want these variables to be created within the context of the function, namely as local variables. But then why exec() updates the given '__globals' and not the given '__locals'?


问:
Sticky Posts on Top of Category Query
I use this query on the Frontpage to display three posts from specific categories in a wp_query. The articles in the query are displayed randomly.

Now the posts that are sticky would like to stay on top and the remaining two articles would still be randomly distributed. Is this possible with a wp_query?

This snippet only returns the one sticky post and the remaining articles are not displayed. Why?

```<code>
           <?php

$args = array(
      'cat'=>'11, 12,20,24',
       'posts_per_page'=> '3',
       'post__in' => get_option( 'sticky_posts' ),
       'ignore_sticky_posts' => 1,
       'orderby'=> 'rand'
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        // Contents of the queried post results go here.

    }

}

// Restore original post data.
wp_reset_postdata();

?>
</code>```

答:
Here you can use two query

1) for sticky post

```<code>$args = array(
   'cat'=>'11, 12,20,24',
   'posts_per_page'=> '1',
   'post__in' => get_option( 'sticky_posts' ),
   'ignore_sticky_posts' => 1,
   'orderby'=> 'rand'
);
</code>```

2) Other posts

```<code>$args = array(
   'cat'=>'11, 12,20,24',
   'posts_per_page'=> '2',
   'ignore_sticky_posts' => 1,
   'orderby'=> 'rand'
);
</code>```

3) Set counter

```<code> $count = 0;
 if ( $query->have_posts() ) {
   while ( $query->have_posts() ) {
   // added if condition here if($count == 1){}else{}
   $count++;
   }
}
</code>```

Title: Sticky Posts on Top of Category Query

Body:
I use this query on the Frontpage to display three posts from specific categories in a wp_query. The articles in the query are displayed randomly.

Now the posts that are sticky would like to stay on top and the remaining two articles would still be randomly distributed. Is this possible with a wp_query?

This snippet only returns the one sticky post and the remaining articles are not displayed. Why?

           <?php

$args = array(
      'cat'=>'11, 12,20,24',
       'posts_per_page'=> '3',
       'post__in' => get_option( 'sticky_posts' ),
       'ignore_sticky_posts' => 1,
       'orderby'=> 'rand'
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        // Contents of the queried post results go here.

    }

}

// Restore original post data.
wp_reset_postdata();

?>

Body:
Here you can use two query

1) for sticky post

$args = array(
   'cat'=>'11, 12,20,24',
   'posts_per_page'=> '1',
   'post__in' => get_option( 'sticky_posts' ),
   'ignore_sticky_posts' => 1,
   'orderby'=> 'rand'
);

2) Other posts

$args = array(
   'cat'=>'11, 12,20,24',
   'posts_per_page'=> '2',
   'ignore_sticky_posts' => 1,
   'orderby'=> 'rand'
);

3) Set counter

 $count = 0;
 if ( $query->have_posts() ) {
   while ( $query->have_posts() ) {
   // added if condition here if($count == 1){}else{}
   $count++;
   }
}


问:
How to feature-detect whether a browser supports dynamic ES6 module loading?

Background

The JavaScript ES6 specification supports module imports aka ES6 modules.

The static imports are quite obvious to use and do already have quite a good browser support, but dynamic import is still lacking behind.

So it is reasonably possible that your code uses static modules (when these would be not supported the code would not even execute), but the browser may miss support for dynamic import. Thus, detecting whether dynamic loading works (before trying to actually load code) may be useful. And as browser detection is frowned upon, of course I'd like to use feature detection.

Use cases may be to show an error, fallback to some other data/default/loading algorithm, provide developers with the advantages of dynamic loading (of data e.g. in a lazy-mode style) in a module, while allowing a fallback to passing the data directly etc. Basically, all the usual use cases where feature detection may be used.

Problem

Now, as dynamic modules are imported with import('/modules/my-module.js') one would obviously try to just detect whether the function is there, like this:

// this code does NOT work
if (import) {
    console.log("dynamic import supported")
}
```

I guess, for every(?) other function this would work, but the problem seems to be: As import is, respectively was, a reserved keyword in ECMAScript, and is now obviously also used for indicating the static import, it is not a real function. As MDN says it, it is "function-like".

Tries

import() results in a syntax error, so this is not really usable and import("") results in a Promise that rejects, which may be useful, but looks really hackish/like a workaround. Also, it requires an async context (await etc.) just for feature-detecting, which is not really nice.

typeeof import also fails directly, causing a syntax error, because of the keyword ("unexpected token: keyword 'import'").

So what is the best way to reliably feature-detect that a browser does support dynamic ES6 modules?

Edit: As I see some answers, please note that the solution should of course be as generally usable as possible, i.e. e.g. CSPs may prevent the use of eval and in PWAs you shall not assume you are always online, so just trying a request for some abitrary file may cause incorrect results.

答:
During more research I've found this gist script, with this essential piece of JS for dynamic feature detection:

function supportsDynamicImport() {
  try {
    new Function('import("")');
    return true;
  } catch (err) {
    return false;
  }
}
document.body.textContent = `supports dynamic loading: ${supportsDynamicImport()}`;```

All credit for this goes to @ebidel from GitHub!

Anyway, this has two problems:

it uses eval, which is evil, especially for websites that use a CSP.

according to the comments in the gist, it does have false-positives in (some version of) Chrome and Edge. (i.e. it returns true altghough these browser do not actually support it)

Body:
Background

The JavaScript ES6 specification supports module imports aka ES6 modules.

The static imports are quite obvious to use and do already have quite a good browser support, but dynamic import is still lacking behind.

So it is reasonably possible that your code uses static modules (when these would be not supported the code would not even execute), but the browser may miss support for dynamic import. Thus, detecting whether dynamic loading works (before trying to actually load code) may be useful. And as browser detection is frowned upon, of course I'd like to use feature detection.

Use cases may be to show an error, fallback to some other data/default/loading algorithm, provide developers with the advantages of dynamic loading (of data e.g. in a lazy-mode style) in a module, while allowing a fallback to passing the data directly etc. Basically, all the usual use cases where feature detection may be used.

Problem

Now, as dynamic modules are imported with import('/modules/my-module.js') one would obviously try to just detect whether the function is there, like this:

// this code does NOT work
if (import) {
    console.log("dynamic import supported")
}

I guess, for every(?) other function this would work, but the problem seems to be: As import is, respectively was, a reserved keyword in ECMAScript, and is now obviously also used for indicating the static import, it is not a real function. As MDN says it, it is "function-like".

Tries

import() results in a syntax error, so this is not really usable and import("") results in a Promise that rejects, which may be useful, but looks really hackish/like a workaround. Also, it requires an async context (await etc.) just for feature-detecting, which is not really nice.

typeeof import also fails directly, causing a syntax error, because of the keyword ("unexpected token: keyword 'import'").

So what is the best way to reliably feature-detect that a browser does support dynamic ES6 modules?

Edit: As I see some answers, please note that the solution should of course be as generally usable as possible, i.e. e.g. CSPs may prevent the use of eval and in PWAs you shall not assume you are always online, so just trying a request for some abitrary file may cause incorrect results.

Body:
During more research I've found this gist script, with this essential piece of JS for dynamic feature detection:

function supportsDynamicImport() {
  try {
    new Function('import("")');
    return true;
  } catch (err) {
    return false;
  }
}
document.body.textContent = `supports dynamic loading: ${supportsDynamicImport()}`;

All credit for this goes to @ebidel from GitHub!

Anyway, this has two problems:

it uses eval, which is evil, especially for websites that use a CSP.

according to the comments in the gist, it does have false-positives in (some version of) Chrome and Edge. (i.e. it returns true altghough these browser do not actually support it)


问:
How to redirect back and refresh the parent view
Hello everyone I am new to react-native.

React native V 0.61
React navigation V 5.x

I have a search bar for a weather API once it is clicked you arrive to the temperature list.

If you type an invalid city, I want to be redirected back with an error message. My problem is that I do not know how to do this because my parent component is not getting updated!

SEARCH.JS

```<code>export default class Search extends React.Component {
constructor(props){
    super(props)
    this.state = {
        city: 'Liège',
        error: ''
    }
}

setCity(city){
    this.setState({city})
}

submit(){
    Keyboard.dismiss();
    this.props.navigation.navigate('Result', {state: this.state});
}

render(){
    if (this.state.error != '') {
        var error = this.state.error;
    } else {
        var error = 'hello world';
    }

    return (
        <View style={GlobalStyle.container}>
            <TextInput
                onChangeText={(text) => this.setCity(text)}
                onSubmitEditing={() => this.submit()}
                style={GlobalStyle.input}
                value={this.state.city}
            />
            <Button color={GlobalStyle.color} onPress={() => this.submit()} title="Lancé recherche"/>
            <Text>{error}</Text>
        </View>
    );
}}
</code>```

LIST.JS

```<code>export default class List extends React.Component {
constructor (props){
    super(props)
    this.state={
        city: this.props.route.params.state.city,
        result: null
    }
    this.fetchWeather();
}

fetchWeather(){
    axios.get('http://api.openweathermap.org/data/2.5/forecast?q='+this.state.city+'&appid=MYKEY&units=metric&lang=fr')
        .then((response) => {
            this.props.route.params.state.error = '';
            this.setState({result: response.data})
        })
        .catch(error => {
            // console.log(error.response.data.message);
            // console.log(this.props.navigation.setOptions());
            // this.props.navigation.setParams.onReturn({city: this.props.route.params.state, error: error.response.data.message});
            // this.props.state.error = 'errror';
            this.props.route.params.state.error = error.response.data.message;
            // console.log(this.props.route.params.state.error);
            this.props.navigation.goBack();
            // this.props.navigation.navigate('Search', {error: error.response.data.message});

        });
}

render(){
    if(this.state.result === null){
        return (
            <ActivityIndicator color={GlobalStyle.color} size="large"/>
        );
    }else{
        return (
            <FlatList
                data={this.state.result.list}
                renderItem={({item}) => <WeatherRow day={item}/>}
                keyExtractor={item => item.dt.toString()}
            />
        );
    }

}}
</code>```

Thank you for your help and have a good day.

答:
In Search.js add

```<code>onBackToHome =() => {

this.setState({
        city: 'Liège',
        error: ''
    })
}

submit(){
    Keyboard.dismiss();
    this.props.navigation.navigate('Result', {state: this.state, backToRefresh: this.onBackToHome});
}
</code>```

Then in List.js

```<code>//Add this line just above this.props.navigation.goBack()

this.props.navigation.state.params.backToRefresh();
</code>```

Body:
Hello everyone I am new to react-native.

React native V 0.61
React navigation V 5.x

I have a search bar for a weather API once it is clicked you arrive to the temperature list.

If you type an invalid city, I want to be redirected back with an error message. My problem is that I do not know how to do this because my parent component is not getting updated!

SEARCH.JS

export default class Search extends React.Component {
constructor(props){
    super(props)
    this.state = {
        city: 'Liège',
        error: ''
    }
}

setCity(city){
    this.setState({city})
}

submit(){
    Keyboard.dismiss();
    this.props.navigation.navigate('Result', {state: this.state});
}

render(){
    if (this.state.error != '') {
        var error = this.state.error;
    } else {
        var error = 'hello world';
    }

    return (
        <View style={GlobalStyle.container}>
            <TextInput
                onChangeText={(text) => this.setCity(text)}
                onSubmitEditing={() => this.submit()}
                style={GlobalStyle.input}
                value={this.state.city}
            />
            <Button color={GlobalStyle.color} onPress={() => this.submit()} title="Lancé recherche"/>
            <Text>{error}</Text>
        </View>
    );
}}

LIST.JS

export default class List extends React.Component {
constructor (props){
    super(props)
    this.state={
        city: this.props.route.params.state.city,
        result: null
    }
    this.fetchWeather();
}

fetchWeather(){
    axios.get('http://api.openweathermap.org/data/2.5/forecast?q='+this.state.city+'&appid=MYKEY&units=metric&lang=fr')
        .then((response) => {
            this.props.route.params.state.error = '';
            this.setState({result: response.data})
        })
        .catch(error => {
            // console.log(error.response.data.message);
            // console.log(this.props.navigation.setOptions());
            // this.props.navigation.setParams.onReturn({city: this.props.route.params.state, error: error.response.data.message});
            // this.props.state.error = 'errror';
            this.props.route.params.state.error = error.response.data.message;
            // console.log(this.props.route.params.state.error);
            this.props.navigation.goBack();
            // this.props.navigation.navigate('Search', {error: error.response.data.message});

        });
}

render(){
    if(this.state.result === null){
        return (
            <ActivityIndicator color={GlobalStyle.color} size="large"/>
        );
    }else{
        return (
            <FlatList
                data={this.state.result.list}
                renderItem={({item}) => <WeatherRow day={item}/>}
                keyExtractor={item => item.dt.toString()}
            />
        );
    }

}}

Thank you for your help and have a good day.

Body:
In Search.js add

onBackToHome =() => {

this.setState({
        city: 'Liège',
        error: ''
    })
}

submit(){
    Keyboard.dismiss();
    this.props.navigation.navigate('Result', {state: this.state, backToRefresh: this.onBackToHome});
}

Then in List.js

//Add this line just above this.props.navigation.goBack()

this.props.navigation.state.params.backToRefresh();