问:
How to run one-off job?
I've found 2 different ways to run a one-off command in my kubernetes cluster:

Method 1

```<code>kubectl apply -f kubernetes/migrate.job.yaml
kubectl wait --for=condition=complete --timeout=600s job/migrate-job
kubectl delete job/migrate-job
</code>```

The problem with this is (a) it doesn't show me the output which I like to see, and (b) it's 3 commands

Method 2

```<code>kubectl run migrate --stdin --tty --rm --restart=Never --image=example.org/app/php:v-$(VERSION) --command -- ./artisan -vvv migrate
</code>```

This almost works except I also need a volume mount to run this command, which AFAIK would require a rather lengthy --overrides arg. If I could pull the override in from a file instead it'd probably work well. Can I do that?

I also need to to return the exit code if the command fails.

答:
There's an open ticket for this: https://github.com/kubernetes/kubernetes/issues/63214

A short term solution is to run your job like this:

```<code>kubectl run migrate --stdin --tty --rm --restart=Never --image=example.org/app/php:v-$(VERSION) --overrides="$(cat kubernetes/migrate.pod.yaml | y2j)"
</code>```

Using y2j to convert YAML to JSON so that I can use a standard pod manifest.

migrate.pod.yaml looks like:

apiVersion: v1
kind: Pod
metadata:
    name: migrate-pod
spec:
    volumes:
        -   name: migrate-secrets-volume
            secret:
                secretName: google-service-account
    containers:
        -   name: migrate-container
            image: example.org/app/php
            command: ["./artisan",  "-vvv", "migrate"]
            stdin: true
            stdinOnce: true
            tty: true
            envFrom:
                -   secretRef:
                        name: dev-env
            volumeMounts:
                -   name: migrate-secrets-volume
                    mountPath: /app/secrets
                    readOnly: true
    restartPolicy: Never
    imagePullSecrets:
        -   name: regcred
```

Title: How to run one-off job?

Body:
I've found 2 different ways to run a one-off command in my kubernetes cluster:

Method 1

kubectl apply -f kubernetes/migrate.job.yaml
kubectl wait --for=condition=complete --timeout=600s job/migrate-job
kubectl delete job/migrate-job

The problem with this is (a) it doesn't show me the output which I like to see, and (b) it's 3 commands

Method 2

kubectl run migrate --stdin --tty --rm --restart=Never --image=example.org/app/php:v-$(VERSION) --command -- ./artisan -vvv migrate

This almost works except I also need a volume mount to run this command, which AFAIK would require a rather lengthy --overrides arg. If I could pull the override in from a file instead it'd probably work well. Can I do that?

I also need to to return the exit code if the command fails.

Body:
There's an open ticket for this: https://github.com/kubernetes/kubernetes/issues/63214

A short term solution is to run your job like this:

kubectl run migrate --stdin --tty --rm --restart=Never --image=example.org/app/php:v-$(VERSION) --overrides="$(cat kubernetes/migrate.pod.yaml | y2j)"

Using y2j to convert YAML to JSON so that I can use a standard pod manifest.

migrate.pod.yaml looks like:

apiVersion: v1
kind: Pod
metadata:
    name: migrate-pod
spec:
    volumes:
        -   name: migrate-secrets-volume
            secret:
                secretName: google-service-account
    containers:
        -   name: migrate-container
            image: example.org/app/php
            command: ["./artisan",  "-vvv", "migrate"]
            stdin: true
            stdinOnce: true
            tty: true
            envFrom:
                -   secretRef:
                        name: dev-env
            volumeMounts:
                -   name: migrate-secrets-volume
                    mountPath: /app/secrets
                    readOnly: true
    restartPolicy: Never
    imagePullSecrets:
        -   name: regcred


来源: stackexchange

问:
How to initialize an instance attribute as a numpy array?
I am trying to initialize a 10 by 5 binary matrix of random binary values as a instance attribute. At the moment I simply initialize it as a list and convert it to a numpy array in a separate function. Is there a better way to do this?

```<code>self.pop = np.random.randint(2, size=args)
self.pop = self.pop.astype(int)
</code>```

This is how I do it in the function

答:
As others said, np.random.randint already creates an int array, so you're set. However if you want true binary values you can specificy the datatype as bool:

```<code>self.pop = np.random.randint(2, size=args, dtype=bool)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to initialize a 10 by 5 binary matrix of random binary values as a instance attribute. At the moment I simply initialize it as a list and convert it to a numpy array in a separate function. Is there a better way to do this?

self.pop = np.random.randint(2, size=args)
self.pop = self.pop.astype(int)

This is how I do it in the function

Body:
As others said, np.random.randint already creates an int array, so you're set. However if you want true binary values you can specificy the datatype as bool:

self.pop = np.random.randint(2, size=args, dtype=bool)


问:
REST API url design
I have a REST API that has a database with table with two columns, product_id and server_id, that it serves product_ids to specific servers which request the data(based on the server_id from table).
Let's say I have three servers with server_ids 1,2 and 3.

My design is like this: /products/server_id/1 and with GET request I get json list of product_ids with server_id = 1, similarly /products/server_id/2 would output list of product_ids for server_id = 2.

Should I remove these routes and make a requirement to send POST request with instructions to receive product_ids for specific server_id in /products route only?

For example sending payload {"server_id":1} would yield a response of list of product_ids for server_id = 1.

答:
Should I remove these routes and make a requirement to send POST request with instructions to receive product_ids for specific server_id in /products route only?

Not usually, no.

GET communicates to general purpose components that the semantics of the request message are effectively read only (see "safe").  That affordance alone makes a number of things possible; for instance, spiders can crawl and index your API, just as they would for a web site.  User agents can "pre-fetch" resources, and so on.

All of that goes right out the window when you decide to use POST.

Furthermore, the URI itself serves a number of useful purposes - caches use the URI as the primary key for matching a request.  Therefore we can reduce the load on the origin server by re-using representations have have been stored using a specific identifier.  We can also perform magic like sticking that URI into an email message, without the context of any specific HTTP request, and the receiver of the message will be able to GET that identifier and fetch the resource we intend.

Again, we lose all of that when the identifying information is in the request payload, rather than in the identifier metadata where it belongs.

That said, we sometimes do use the payload for identifying information, as a work around: for example, if we need so much identifying information that we start seeing 414 URI Too Long responses, then we may need to change our interaction protocol to use a POST request with the identifying information in the payload (losing, as above, the advantages of using GET).

An online example of this might be something like an HTML validator, that accepts a candidate document and returns a representation of the problems found.  That's effectively a read only action, but in the general case an HTML document is too long to comfortably fit in the target-uri of an HTTP request.

So we punt.

In a hypermedia api, like those used on the world wide web, we can get away with it, because the HTTP method to use is provided by the server as part of the metadata of the form itself.  You as the client don't need to know the server's preferred semantics, you just need to know how to process the form data.

For instance, as I type this answer into my browser, I don't need to know what the target URI is, or what HTTP method is going to be used, because the browser already knows what to do (based on the HTML and whatever scripts are running "on demand").

Title: REST API url design


问:
Auto-starting Twonky Server on Ubuntu 18.04 using systemd
I was trying to set up a Twonky Server on Ubuntu. The server works fine, but I could not get systemd to autostart the server (using a service file I created at /etc/systemd/system/twonkyserver.service). Sometimes I got the cryptic error message that some PID-file (/var/run/mediaserver.pid) is not accessible, the exit code of the service is 13, which apparently is a EACCES Permission denied error . The service runs as root.

I finally managed to fix the problem by setting PIDFile in the twonkyserver.service file to /var/run/mediaserver.pid. For reference, find the service file below:

[Unit]
Description=Twonky Server Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/twonky/twonky.sh start
ExecStop=/usr/local/twonky/twonky.sh stop
ExecReload=/usr/local/twonky/twonky.sh reload
ExecRestart=/usr/local/twonky/twonky.sh restart
PIDFile=/var/run/mediaserver.pid
Restart=on-failure

[Install]
WantedBy=multi-user.target
```

答:
I would slightly amend the start and stop commands from twonky.sh and put them directly into the twonky.service file for systemd:

```<code>[Unit]
Description=Twonky Server Service
After=network.target

[Service]
Type=simple

#Systemd will ensure RuntimeDirectory for the PID file is created under /var/run
RuntimeDirectory=twonky
PIDFile=/var/run/twonky/mediaserver.pid
# use the -mspid argument for twonkystarter to put the pid file in the right place
ExecStart=/usr/local/twonky/twonkystarter -mspid /var/run/twonky/mediaserver.pid -inifile /usr/local/twonky/twonkyserver.ini -logfile /usr/local/twonky/twonky.log -appdata /usr/local/twonky
ExecStop=kill -s TERM $MAINPID
ExecStopPost=-killall -s TERM twonkystarter
ExecStopPost=-killall -s TERM twonky
# Twonky 8.5.1 doesn't reload, it stops instead (on arm at least)
# ExecReload=kill -s HUP $MAINPID

Restart=on-failure

[Install]
WantedBy=multi-user.target
</code>```

You need to be sure the paths in the ExecStart command match where you unpacked twonky, and also where you want the .pid file, configuration, logfile and runtime appdataunless you are happy with their default locations.

After putting that all into/etc/systemd/system/twonky.server, run

```<code>sudo systemctl daemon-reload
sudo systemctl start twonky
sudo systemctl enable twonky
</code>```

Body:
I would slightly amend the start and stop commands from twonky.sh and put them directly into the twonky.service file for systemd:

[Unit]
Description=Twonky Server Service
After=network.target

[Service]
Type=simple

#Systemd will ensure RuntimeDirectory for the PID file is created under /var/run
RuntimeDirectory=twonky
PIDFile=/var/run/twonky/mediaserver.pid
# use the -mspid argument for twonkystarter to put the pid file in the right place
ExecStart=/usr/local/twonky/twonkystarter -mspid /var/run/twonky/mediaserver.pid -inifile /usr/local/twonky/twonkyserver.ini -logfile /usr/local/twonky/twonky.log -appdata /usr/local/twonky
ExecStop=kill -s TERM $MAINPID
ExecStopPost=-killall -s TERM twonkystarter
ExecStopPost=-killall -s TERM twonky
# Twonky 8.5.1 doesn't reload, it stops instead (on arm at least)
# ExecReload=kill -s HUP $MAINPID

Restart=on-failure

[Install]
WantedBy=multi-user.target

You need to be sure the paths in the ExecStart command match where you unpacked twonky, and also where you want the .pid file, configuration, logfile and runtime appdataunless you are happy with their default locations.

After putting that all into/etc/systemd/system/twonky.server, run

sudo systemctl daemon-reload
sudo systemctl start twonky
sudo systemctl enable twonky


问:
How to add a search function to my JavaScript?
I am developing a music player using JavaScript and I am trying to add a search bar to my page but every tutorial I have seen so far uses a list created in the HTML page, whereas I have created a list using JavaScript code like this:

```<code>const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp3",
    "DontStartNow.mp3",
    "Intentions.mp3",
    "Physical"
]

const createSongList = () => {
    const list = document.createElement('ol')

    for(let i = 0; i<songs.length; i++){
        const item = document.createElement('li')
        item.appendChild(document.createTextNode(songs[i]))

        list.appendChild(item)
    }

    return list
}

document.getElementById('songList').appendChild(createSongList())
</code>```

Is there a way I can use the 'songs' array or to develop a search function? Any advice would be appreciated. Thanks! :)

Edit for clarity:

So I have an input tag on my html that I want to use for a search bar, then I want what the user types in to return any matching songs from the songs array. For example if they type in 'Bli' I want it to show the Blinding Lights song.
The code snippet above is how I am currently displaying a list of songs using the array.

This is my input tag:

```<code><input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">
</code>```

答:
Assuming that you want to filter songs array from a search string, you can use this function :

const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp3",
    "DontStartNow.mp3",
    "Intentions.mp3",
    "Physical"
];

const searchSong = (value) => {
  return songs.filter(song => song.includes(value));
};

console.log(searchSong('B'));```

Body:
I am developing a music player using JavaScript and I am trying to add a search bar to my page but every tutorial I have seen so far uses a list created in the HTML page, whereas I have created a list using JavaScript code like this:

const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp3",
    "DontStartNow.mp3",
    "Intentions.mp3",
    "Physical"
]

const createSongList = () => {
    const list = document.createElement('ol')

    for(let i = 0; i<songs.length; i++){
        const item = document.createElement('li')
        item.appendChild(document.createTextNode(songs[i]))

        list.appendChild(item)
    }

    return list
}

document.getElementById('songList').appendChild(createSongList())

Is there a way I can use the 'songs' array or to develop a search function? Any advice would be appreciated. Thanks! :)

Edit for clarity:

So I have an input tag on my html that I want to use for a search bar, then I want what the user types in to return any matching songs from the songs array. For example if they type in 'Bli' I want it to show the Blinding Lights song.
The code snippet above is how I am currently displaying a list of songs using the array.

This is my input tag:

<input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">


Title: Python3 List Comprehension for n lists

Body:
I have a way of iterating through my lists as I wish as follows:

a = ["1","2","3","4","5","6","7","8","9","10"]
b = ['A','B','C','D','E','F','G','H','I','J']
c = ["11","12","13","14","15","16","17","18","19","20"]

for x, y, z in [(x,y,z) for x in a for y in b for z in c]:
    print(x,y,z)

Output:

1 A 11
1 A 12
1 A 13
1 A 14
1 A 15
1 A 16
1 A 17
1 A 18
1 A 19
1 A 20
1 B 11
1 B 12
1 B 13
1 B 14
...etc

But how can I achieve the same result if my lists are stored in a list and there are n lists? e.g.

main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]

Thanks in advance.

Body:
Look at itertools.product:

a = ["1","2","3","4","5","6","7","8","9","10"]
b = ['A','B','C','D','E','F','G','H','I','J']
c = ["11","12","13","14","15","16","17","18","19","20"]

from itertools import product

all_lists = [a, b, c]
for c in product(*all_lists):
    print(c)

Prints:

('1', 'A', '11')
('1', 'A', '12')
('1', 'A', '13')
('1', 'A', '14')
('1', 'A', '15')
('1', 'A', '16')
('1', 'A', '17')
('1', 'A', '18')
('1', 'A', '19')
('1', 'A', '20')
('1', 'B', '11')

... and so on.


问:
unresolved external symbol on pcre visual studio
Hello i want to use pcre on my visual studio 2015. i got all pcre libs (i compiled it) and i set pcre lib dir on Linker/ General/Additional library Dir
and this is my source

```<code>#include <iostream>
#include <string>
#include <stdlib.h>
#include <map>
#include "pcrecpp.h"

using namespace std;
using namespace pcrecpp;

void main()
{

    RE_Options Regex_Options;

    // Set options
    Regex_Options.set_caseless(true);
    Regex_Options.set_multiline(true);
    Regex_Options.set_dotall(true);

    RE Regex("h.*o", Regex_Options);

    Regex.FullMatch("hello");

    system("pause");
}
</code>```

when i want to compile this project, i get this errors

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "public: bool __thiscall pcrecpp::RE::FullMatch(class pcrecpp::StringPiece const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &)const " (?FullMatch@RE@pcrecpp@@QBE_NABVStringPiece@2@ABVArg@2@111111111111111@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "public: __thiscall pcrecpp::RE::~RE(void)" (??1RE@pcrecpp@@QAE@XZ) referenced in function _main TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "private: void __thiscall pcrecpp::RE::Init(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class pcrecpp::RE_Options const *)" (?Init@RE@pcrecpp@@AAEXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PBVRE_Options@2@@Z) referenced in function "public: __thiscall pcrecpp::RE::RE(char const *,class pcrecpp::RE_Options const &)" (??0RE@pcrecpp@@QAE@PBDABVRE_Options@1@@Z)    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2001 unresolved external symbol "public: static class pcrecpp::Arg pcrecpp::RE::no_arg" (?no_arg@RE@pcrecpp@@2VArg@2@A)  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK1120 4 unresolved externals  TestProg    D:\Visual Studio Projects\TestProg\Debug\TestProg.exe   1
</code>```

What is the problem !!! ??

i put all libs into link / input /additional ...
and this is new errors

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::RE::RE(char const *,class pcrecpp::RE_Options const &)" (__imp_??0RE@pcrecpp@@QAE@PBDABVRE_Options@1@@Z) referenced in function _main TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::StringPiece::StringPiece(char const *)" (__imp_??0StringPiece@pcrecpp@@QAE@PBD@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::RE_Options::RE_Options(void)" (__imp_??0RE_Options@pcrecpp@@QAE@XZ) referenced in function _main  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class pcrecpp::RE_Options & __thiscall pcrecpp::RE_Options::set_caseless(bool)" (__imp_?set_caseless@RE_Options@pcrecpp@@QAEAAV12@_N@Z) referenced in function _main  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class pcrecpp::RE_Options & __thiscall pcrecpp::RE_Options::set_multiline(bool)" (__imp_?set_multiline@RE_Options@pcrecpp@@QAEAAV12@_N@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class pcrecpp::RE_Options & __thiscall pcrecpp::RE_Options::set_dotall(bool)" (__imp_?set_dotall@RE_Options@pcrecpp@@QAEAAV12@_N@Z) referenced in function _main  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::RE::~RE(void)" (__imp_??1RE@pcrecpp@@QAE@XZ) referenced in function _main TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: bool __thiscall pcrecpp::RE::FullMatch(class pcrecpp::StringPiece const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &)const " (__imp_?FullMatch@RE@pcrecpp@@QBE_NABVStringPiece@2@ABVArg@2@111111111111111@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2001 unresolved external symbol "__declspec(dllimport) public: static class pcrecpp::Arg pcrecpp::RE::no_arg" (__imp_?no_arg@RE@pcrecpp@@2VArg@2@A)  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK1120 9 unresolved externals  TestProg    D:\Visual Studio Projects\TestProg\Debug\TestProg.exe   1
</code>```

答: So, I assume you compiled it with BUILD_SHARED_LIBS=OFF option by default. Then you need to add PCRE_STATIC to preprocessor definitions of your app. With this define pcrecpp::RE class won't have __declspec(dllimport) in front of it, thus not trying to find an import library, which you don't have, because all the code is in a static library.

ContentLicense: CC BY-SA 3.0

Body:
Hello i want to use pcre on my visual studio 2015. i got all pcre libs (i compiled it) and i set pcre lib dir on Linker/ General/Additional library Dir
and this is my source

#include <iostream>
#include <string>
#include <stdlib.h>
#include <map>
#include "pcrecpp.h"

using namespace std;
using namespace pcrecpp;

void main()
{

    RE_Options Regex_Options;

    // Set options
    Regex_Options.set_caseless(true);
    Regex_Options.set_multiline(true);
    Regex_Options.set_dotall(true);

    RE Regex("h.*o", Regex_Options);

    Regex.FullMatch("hello");

    system("pause");
}

when i want to compile this project, i get this errors

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "public: bool __thiscall pcrecpp::RE::FullMatch(class pcrecpp::StringPiece const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &)const " (?FullMatch@RE@pcrecpp@@QBE_NABVStringPiece@2@ABVArg@2@111111111111111@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "public: __thiscall pcrecpp::RE::~RE(void)" (??1RE@pcrecpp@@QAE@XZ) referenced in function _main TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "private: void __thiscall pcrecpp::RE::Init(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class pcrecpp::RE_Options const *)" (?Init@RE@pcrecpp@@AAEXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PBVRE_Options@2@@Z) referenced in function "public: __thiscall pcrecpp::RE::RE(char const *,class pcrecpp::RE_Options const &)" (??0RE@pcrecpp@@QAE@PBDABVRE_Options@1@@Z)    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2001 unresolved external symbol "public: static class pcrecpp::Arg pcrecpp::RE::no_arg" (?no_arg@RE@pcrecpp@@2VArg@2@A)  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK1120 4 unresolved externals  TestProg    D:\Visual Studio Projects\TestProg\Debug\TestProg.exe   1

What is the problem !!! ??

i put all libs into link / input /additional ...
and this is new errors

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::RE::RE(char const *,class pcrecpp::RE_Options const &)" (__imp_??0RE@pcrecpp@@QAE@PBDABVRE_Options@1@@Z) referenced in function _main TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::StringPiece::StringPiece(char const *)" (__imp_??0StringPiece@pcrecpp@@QAE@PBD@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::RE_Options::RE_Options(void)" (__imp_??0RE_Options@pcrecpp@@QAE@XZ) referenced in function _main  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class pcrecpp::RE_Options & __thiscall pcrecpp::RE_Options::set_caseless(bool)" (__imp_?set_caseless@RE_Options@pcrecpp@@QAEAAV12@_N@Z) referenced in function _main  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class pcrecpp::RE_Options & __thiscall pcrecpp::RE_Options::set_multiline(bool)" (__imp_?set_multiline@RE_Options@pcrecpp@@QAEAAV12@_N@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class pcrecpp::RE_Options & __thiscall pcrecpp::RE_Options::set_dotall(bool)" (__imp_?set_dotall@RE_Options@pcrecpp@@QAEAAV12@_N@Z) referenced in function _main  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall pcrecpp::RE::~RE(void)" (__imp_??1RE@pcrecpp@@QAE@XZ) referenced in function _main TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: bool __thiscall pcrecpp::RE::FullMatch(class pcrecpp::StringPiece const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &,class pcrecpp::Arg const &)const " (__imp_?FullMatch@RE@pcrecpp@@QBE_NABVStringPiece@2@ABVArg@2@111111111111111@Z) referenced in function _main    TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK2001 unresolved external symbol "__declspec(dllimport) public: static class pcrecpp::Arg pcrecpp::RE::no_arg" (__imp_?no_arg@RE@pcrecpp@@2VArg@2@A)  TestProg    D:\Visual Studio Projects\TestProg\TestProg\Source.obj  1
Error   LNK1120 9 unresolved externals  TestProg    D:\Visual Studio Projects\TestProg\Debug\TestProg.exe   1


问:
TADOQuery - Edit mode inserts new record rather than editing
I'm puzzled at the behavior of the TADOQuery, let's just call Q. When I use Q.Edit, populate some fields, then Post, it ends up actually inserting a new record.

The code is simple, and reading the ID from an object:

```<code>Q.SQL.Text := 'select * from SomeTable where ID = :id';
Q.Parameters.ParamValues['id'] := MyObject.ID;
Q.Open;
try
  Q.Edit;
  try
    Q['SomeField']:= MyObject.SomeField;
  finally
    Q.Post;
  end;
finally
  Q.Close;
end;
</code>```

To my surprise, rather than updating the intended record, it decided to insert a new record. Stepping through the code, immediately after Q.Edit, the query is actually in Insert mode.

What could I be doing wrong here?

答:
I think the comments that this behaviour is documented are off the point.  What the docs don't make clear (possibly because the point never occurred to the author) is that this behaviour is not guaranteed to be deterministic.

The innards of TDataSet.Edit have scarcely changed in decades.  Here is the Seattle version:

```<code>procedure TDataSet.Edit;
begin
  if not (State in [dsEdit, dsInsert]) then
    if FRecordCount = 0 then Insert else
    begin
      CheckBrowseMode;
      CheckCanModify;
      DoBeforeEdit;
      CheckParentState;
      CheckOperation(InternalEdit, FOnEditError);
      GetCalcFields(ActiveBuffer);
      SetState(dsEdit);
      DataEvent(deRecordChange, 0);
      DoAfterEdit;
    end;
end;
</code>```

Now, notice that the if .. then .. is predicated on the value of FRecordCount, which at various points in the TDataSet code is forced to have a given assumed value (variously 1, 0 or something else) by code such as in SetBufferCount and that behaviour isn't documented at all.  So on reflection I think Jerry was probably right to expect that attempting to edit a non-existent record should be treated as an error condition, and not be fudged around by silently calling Insert whether or not it is documented.

Body:
I'm puzzled at the behavior of the TADOQuery, let's just call Q. When I use Q.Edit, populate some fields, then Post, it ends up actually inserting a new record.

The code is simple, and reading the ID from an object:

Q.SQL.Text := 'select * from SomeTable where ID = :id';
Q.Parameters.ParamValues['id'] := MyObject.ID;
Q.Open;
try
  Q.Edit;
  try
    Q['SomeField']:= MyObject.SomeField;
  finally
    Q.Post;
  end;
finally
  Q.Close;
end;

To my surprise, rather than updating the intended record, it decided to insert a new record. Stepping through the code, immediately after Q.Edit, the query is actually in Insert mode.

What could I be doing wrong here?

Body:
I think the comments that this behaviour is documented are off the point.  What the docs don't make clear (possibly because the point never occurred to the author) is that this behaviour is not guaranteed to be deterministic.

The innards of TDataSet.Edit have scarcely changed in decades.  Here is the Seattle version:

procedure TDataSet.Edit;
begin
  if not (State in [dsEdit, dsInsert]) then
    if FRecordCount = 0 then Insert else
    begin
      CheckBrowseMode;
      CheckCanModify;
      DoBeforeEdit;
      CheckParentState;
      CheckOperation(InternalEdit, FOnEditError);
      GetCalcFields(ActiveBuffer);
      SetState(dsEdit);
      DataEvent(deRecordChange, 0);
      DoAfterEdit;
    end;
end;

Now, notice that the if .. then .. is predicated on the value of FRecordCount, which at various points in the TDataSet code is forced to have a given assumed value (variously 1, 0 or something else) by code such as in SetBufferCount and that behaviour isn't documented at all.  So on reflection I think Jerry was probably right to expect that attempting to edit a non-existent record should be treated as an error condition, and not be fudged around by silently calling Insert whether or not it is documented.


问:
Writing a parser in C++ to parse the given HTML entities
Recently, I faced a coding question in which we had to parse the mention HTML entities. These following entities needed to be parsed -

" to "

' to - '

> to >

< to <

& to &

⁄ to ⁄

There will be a string txt given which has to be parsed as per above rules. Following is my approach which works fine.

```<code>string parse(string txt){
    int n=txt.size();
    for(int i=0;i<n;i++){             //edit : why don't I get an error even though I loop for full length after erasing some elements of string?
            if(txt[i]=='&'){
                if(i+5<n&&txt.substr(i,6)=="""){
                    txt[i]='"';
                    txt.erase(i+1,5);
                }
                else if(i+5<n&&txt.substr(i,6)=="'"){
                    txt[i]=(char)(39);            //I also wasn't able to do like this -txt[i]='\''; would be nice if someone tells why this gave error
                    txt.erase(i+1,5);
                }
                else if(i+4<n&&txt.substr(i,5)=="&"){
                    txt[i]='&';
                    txt.erase(i+1,4);
                }
                else if(i+3<n&&txt.substr(i,4)==">"){
                    txt[i]='>';
                    txt.erase(i+1,3);
                }
                else if(i+3<n&&txt.substr(i,4)=="<"){
                    txt[i]='<';
                    txt.erase(i+1,3);
                }
                else if(i+6<n&&txt.substr(i,7)=="⁄"){
                    txt[i]='/';
                    txt.erase(i+1,6);
                }
            }
        }
    return txt;
}
</code>```

I feel I did it in the most brute way possible. But I wonder if there is another approach which is simpler(probably, shorter) than my code.

Any help or approach is appreciated !

EDIT : As brought to my notice by a comment, my looping actually uses the originally string length n but I am erasing some elements when looping reducing the txt string length. Suprisingly, I don't get any error and it would be helpful if someone explains why?

答:
Here's how I would suggest approaching this problem:

0) firstly I would just create a new string with the correctly formatted output. This is easier than having to modify the string in-place - you just build the string up bit by bit. Plus I don't know if modifying it in-place is beneficial anyway, every time you erase some characters I imagine elements are being copied along the elements along to keep the memory together (contiguous).

1) use std::string::find to find the next occurrence of each character
2) of the strings that you are looking for, pick the one that occurs next (smallest string::find value)
3) append the characters up to this point to the output string
4) append the replacement text instead of the original text
5) repeat - std::string::find has an optional pos argument indicating where to start the search
6) loop ends when all find results are == std::string::npos

There are probably many ways to solve this, and probably something using regexes would be more elegant, but this is how I would do it.

As an aside, relating to your edit, there might not be any errors if you are running without debugging. I think if you have an access violation the console app will just exit without any related output of you're not attached to a debugger. This is why it is good idea to run stuff in a debug environment if you can.

EDIT: Using std::string::replace is another function that you could use here

Body:
Recently, I faced a coding question in which we had to parse the mention HTML entities. These following entities needed to be parsed -

" to "

' to - '

> to >

< to <

& to &

⁄ to ⁄

There will be a string txt given which has to be parsed as per above rules. Following is my approach which works fine.

string parse(string txt){
    int n=txt.size();
    for(int i=0;i<n;i++){             //edit : why don't I get an error even though I loop for full length after erasing some elements of string?
            if(txt[i]=='&'){
                if(i+5<n&&txt.substr(i,6)=="""){
                    txt[i]='"';
                    txt.erase(i+1,5);
                }
                else if(i+5<n&&txt.substr(i,6)=="'"){
                    txt[i]=(char)(39);            //I also wasn't able to do like this -txt[i]='\''; would be nice if someone tells why this gave error
                    txt.erase(i+1,5);
                }
                else if(i+4<n&&txt.substr(i,5)=="&"){
                    txt[i]='&';
                    txt.erase(i+1,4);
                }
                else if(i+3<n&&txt.substr(i,4)==">"){
                    txt[i]='>';
                    txt.erase(i+1,3);
                }
                else if(i+3<n&&txt.substr(i,4)=="<"){
                    txt[i]='<';
                    txt.erase(i+1,3);
                }
                else if(i+6<n&&txt.substr(i,7)=="⁄"){
                    txt[i]='/';
                    txt.erase(i+1,6);
                }
            }
        }
    return txt;
}

I feel I did it in the most brute way possible. But I wonder if there is another approach which is simpler(probably, shorter) than my code.

Any help or approach is appreciated !

EDIT : As brought to my notice by a comment, my looping actually uses the originally string length n but I am erasing some elements when looping reducing the txt string length. Suprisingly, I don't get any error and it would be helpful if someone explains why?


答:
For the example, the below gives the required combinations. </p>

```<code>import itertools

list(itertools.product(*(a,b,c)))

</code>```

<p>For the mainlist - </p>

```<code>
main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]

combintns = list(itertools.product(*main_list))

# in case you're specific about output format/appearance
for i in combintns:
  print(i[0],i[1],i[2],i[3])
</code>```

Title: Python3 List Comprehension for n lists

Body:
For the example, the below gives the required combinations.

import itertools

list(itertools.product(*(a,b,c)))

For the mainlist -

main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]

combintns = list(itertools.product(*main_list))

# in case you're specific about output format/appearance
for i in combintns:
  print(i[0],i[1],i[2],i[3])


问:
How to copy particular lines below particular text?
Suppose I have long text files output1, output2, and output3. In all output files, somewhere is "My Name is Rock (static)"
and below that text some values like

```<code>"My Name is Rock (static)"
10 20 30
-10 0.5 00
3.0 0.0 0.0 (different for all output file)
</code>```

How can I copy the second column of the third line below the line ("My Name is Rock (static)") to a new file?

Remember line numbers are different for all output file.

答:
```<code>awk 'c{c--;if(!c) print $2}/My Name is Rock \(static\)/{c=3}' ./output1 ./output2 ./output3
</code>```

Explanation

/My Name is Rock \(static\)/{c=3}: When "My Name is Rock (static)" is seen, set c to 3

c{...}: If the counter c is non-zero, do ... (note, c starts off at 0)

c--;if(!c) print $2: Decrement counter, if counter is now zero, print 2nd field of current line

Body:
Suppose I have long text files output1, output2, and output3. In all output files, somewhere is "My Name is Rock (static)"
and below that text some values like

"My Name is Rock (static)"
10 20 30
-10 0.5 00
3.0 0.0 0.0 (different for all output file)

How can I copy the second column of the third line below the line ("My Name is Rock (static)") to a new file?

Remember line numbers are different for all output file.

Body:
awk 'c{c--;if(!c) print $2}/My Name is Rock \(static\)/{c=3}' ./output1 ./output2 ./output3

Explanation

/My Name is Rock \(static\)/{c=3}: When "My Name is Rock (static)" is seen, set c to 3

c{...}: If the counter c is non-zero, do ... (note, c starts off at 0)

c--;if(!c) print $2: Decrement counter, if counter is now zero, print 2nd field of current line


问:
Linked List Queue in C: Exception thrown: read access violation. temp was 0x740069
I was making simple Linked list Queue program using C and i get this exception from my print function.

Exception thrown: read access violation. temp was 0x740069.

I'm still a beginner when it comes to C language so I don't getting use to managing memory and using pointers yet. So I'm not sure if the cause comes from my push function or my print function.

So i would like to ask what is the cause of this exception and how to fix it.

My code are as follow

```<code>struct node_struct {
    char *data;
    struct node_struct *next;
};

typedef struct node_struct Node;

struct queue_struct {
    Node *head, *tail;
};

typedef struct queue_struct Queue;

void push(Queue *q, char *word)
{
    // IMPLEMENT
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = (char*)malloc(sizeof(char));
    temp->data = word;
    temp->next = NULL;
    if (q->head == NULL )
    {
        q->head= temp;
    }
    else
    {
        q->tail->next = temp;
    }
    q->tail = temp;
    q->tail->next = q->head;
}

char *pop(Queue *q)
{
    // IMPLEMENT
    Node* temp = q->head;
    char n = q->head->data;
    q->head = q->head->next;
    free(temp);
    return(n);
}

void print(Queue *q)
{
    // IMPLEMENT
    if (q == NULL)
    {
        printf("No Items\n");
    }
    else
    {
        //Node* temp = (Node*)malloc(sizeof(Node));
        Node* temp = q->head;
        while (temp != NULL)
        {
            printf("%c\n", temp->data);
            temp = temp->next;
        }
    }
}

void print(Queue *q)
{
    // IMPLEMENT
    if (q == NULL || isEmpty(q))
    {
        printf("No Items\n");
    }
    else
    {
        //Node* temp = (Node*)malloc(sizeof(Node));
        Node* temp = q->head;
        while (temp != NULL)
        {
            printf("%c\n", temp->data);
            temp = temp->next;
        }
    }
}

int isEmpty(Queue *q)
{
    // IMPLEMENT
    if (q->head == NULL)
        return 1;
    return 0;
}

void delete(Queue *q)
{
    // IMPLEMENT
    Node* temp;
    while (q->head != NULL)
    {
        temp = q->head;
        q->head = q->head->next;
        delete(temp);
    }
    q->tail = NULL;
}

int main(int argc, char **argv)
{
    Queue *q = NULL;

    // print the queue
    print(q);

    // push items
    push(&q, "a");
    push(&q, "b");
    push(&q, "c");
    print(q);
}
</code>```

And the output is in image below

Current output of my Queue

答:
Well in my case I use a field to store the size of the list, but it can be done without it, here is my implementation for a queue, I have added some comments for clarity, maybe you will find it useful. and i have added just few functions, you can add more if you like, it's just for giving you a startup :)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// make an alias for better readability
typedef char * String;

typedef struct node_struct {
  String data;
  struct node_struct *next;
} Node;

typedef struct queue_struct {
  Node *head, *tail;
} Queue;

// create a new node, allocating the memory and copying the value...
Node * Node_create(String str) {
  Node *node = (Node *)malloc(sizeof(Node));
  if(node == NULL) return NULL;
  node->data = (String)malloc(strlen(str) + 1);
  if(node->data == NULL) return NULL;
  strcpy(node->data, str);
  node->next = NULL;
  return node;
}

// delete the node
void Node_delete(Node *node) {
  free(node->data);
  free(node);
}

// create a new Queue and set the head and tail to NULL(empty)
Queue * Queue_create() {
  Queue *queue = (Queue *)malloc(sizeof(Queue));
  if(queue == NULL) return NULL;
  queue->head = queue->tail = NULL;
  return queue;
}

// add a new node to the queue
bool Queue_push(Queue *q, String str) {
  Node* node = Node_create(str);
  if(node == NULL) return false;
  // empty queue
  if(q->head == NULL) {
    q->head = q->tail = node;
  // has only one element
  }else if(q->head == q->tail) {
    q->head->next = q->tail = node;
  // has more than one element
  }else {
    q->tail->next = node;
    q->tail = q->tail->next;
  }
  return true;
}

// print the elements of the queue
void Queue_print(Queue *q) {
  Node *tmpNode = q->head;
  printf("{");
  // loop over the queue
  while(tmpNode != NULL) {
    printf("%s", tmpNode->data);
    // don't print ',' if its the last element
    tmpNode != q->tail && printf(", ");
    tmpNode = tmpNode->next;
  }
  printf("}");
}

// get the size of the queue
int Queue_size(Queue *q) {
  Node *tmpNode = q->head;
  int size = 0;
  while(tmpNode != NULL) {
    tmpNode = tmpNode->next;
    size++;
  }
  return size;
}

// remove the last element in the queue
String Queue_pop(Queue *q) {
  String s = NULL;
  // empty queue
  if(q->head == NULL) return s;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has two elements
  }else if(q->head->next == q->tail) {
    s = q->tail->data;
    Node_delete(q->tail);
    q->tail = q->head;
    q->head->next = q->tail;
    q->tail->next = NULL;
  // has more than two
  }else {
    s = q->tail->data;
    Node *tmpNode = q->head, *lastNode;
    // loop over the queue and get the element before the last one
    while(tmpNode != NULL) {
      lastNode = tmpNode;
      tmpNode = tmpNode->next;
      // delete the last element and replace it with the previous element
      if(tmpNode == q->tail) {
        Node_delete(q->tail);
        q->tail = lastNode;
        q->tail->next = NULL;
        return s;
      }
    }
  }
  return s;
}

// remove the first element in the queue
String Queue_shift(Queue *q) {
  String s = NULL;
  // empty queue
  if(q->head == NULL) return NULL;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has more than one
  } else {
    // just delete the first element and replace it with the next one
    Node *tmpNode = q->head->next;
    s = q->head->data;
    Node_delete(q->head);
    q->head = tmpNode;
  }
  return s;
}

// remove all the elements in the queue
void Queue_clear(Queue *q) {
  Node *tmpNode = q->head;
  for(int i = 0, n = Queue_size(q);i < n; i++) {
    tmpNode = tmpNode->next;
    // using the Queue_shift instead of Queue_pop because it's faster(low processing cost)
    Queue_shift(q);
  }
}

// remove all the elements in the queue and free the memory of the queue
void Queue_delete(Queue *q) {
  Queue_clear(q);
  free(q);
}

// check if the queue is empty
bool Queue_isEmpty(Queue *q) {
  return q->head == NULL;
}

int main(void) {
  Queue *a = Queue_create();
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(a, "txt1");
  printf("Size: %d\n", Queue_size(a));
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(a, "txt2");
  Queue_push(a, "txt3");
  Queue_print(a);
  Queue_shift(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_pop(a);
  Queue_push(a, "txt4");
  Queue_push(a, "txt5");
  printf("Size: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_clear(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_push(a, "txt");
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_delete(a);
  return 0;
}

```

<p><strong>output</strong></p>

```Is empty: true
Size: 1
Is empty: false
{txt1, txt2, txt3}
Size: 2
Size: 3
{txt2, txt4, txt5}
Size: 0
{}
Size: 1
{txt}
```

<hr>

<p>Ok according to your comment:</p>

<blockquote>
  <p>I currently experiment with your version right now i want to ask if i don't want to use Queue *a = Queue_create(); in the main function but instead i want to made Queue *a = NULL; and then allocate space for it in push function how would you do it?</p>
</blockquote>

<p>You can do it this way, note that you can still use the other functions the same way with no modifications. and even you still can use Queue_create Directly like <code>Queue *q = Queue_create();</code> like in the first part.</p>

```#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// make an alias for better readability
typedef char * String;

typedef struct node_struct {
  String data;
  struct node_struct *next;
} Node;

typedef struct queue_struct {
  Node *head, *tail;
} Queue;

// create a new node, allocating the memory and copying the value...
Node * Node_create(String str) {
  Node *node = (Node *)malloc(sizeof(Node));
  if(node == NULL) return NULL;
  node->data = (String)malloc(strlen(str) + 1);
  if(node->data == NULL) return NULL;
  strcpy(node->data, str);
  node->next = NULL;
  return node;
}

// delete the node
void Node_delete(Node *node) {
  free(node->data);
  free(node);
}

// create a new Queue and set the head and tail to NULL(empty)
Queue * Queue_create() {
  Queue *queue = (Queue *)malloc(sizeof(Queue));
  if(queue == NULL) return NULL;
  queue->head = queue->tail = NULL;
  return queue;
}

// add a new node to the queue
bool Queue_push(Queue **q, String str) {
  // if there is no allocated Queue then we need to allocate one using the Queue_create() we already have
  if(*q == NULL) {
    *q = Queue_create();
    if(*q == NULL) return false;
  }
  Node* node = Node_create(str);
  if(node == NULL) return false;
  // empty queue
  if((*q)->head == NULL) {
    (*q)->head = (*q)->tail = node;
  // has only one element
  }else if((*q)->head == (*q)->tail) {
    (*q)->head->next = (*q)->tail = node;
  // has more than one element
  }else {
    (*q)->tail->next = node;
    (*q)->tail = (*q)->tail->next;
  }
  return true;
}

// print the elements of the queue
void Queue_print(Queue *q) {
  if(q != NULL) {
    Node *tmpNode = q->head;
    printf("{");
    // loop over the queue
    while(tmpNode != NULL) {
      printf("%s", tmpNode->data);
      // don't print ',' if its the last element
      tmpNode != q->tail && printf(", ");
      tmpNode = tmpNode->next;
    }
    printf("}");
  }
}

// get the size of the queue
int Queue_size(Queue *q) {
  if(q == NULL) return 0;
  Node *tmpNode = q->head;
  int size = 0;
  while(tmpNode != NULL) {
    tmpNode = tmpNode->next;
    size++;
  }
  return size;
}

// remove the last element in the queue
String Queue_pop(Queue *q) {
  if(q == NULL) return NULL;
  String s = NULL;
  // empty queue
  if(q->head == NULL) return s;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has two elements
  }else if(q->head->next == q->tail) {
    s = q->tail->data;
    Node_delete(q->tail);
    q->tail = q->head;
    q->head->next = q->tail;
    q->tail->next = NULL;
  // has more than two
  }else {
    s = q->tail->data;
    Node *tmpNode = q->head, *lastNode;
    // loop over the queue and get the element before the last one
    while(tmpNode != NULL) {
      lastNode = tmpNode;
      tmpNode = tmpNode->next;
      // delete the last element and replace it with the previous element
      if(tmpNode == q->tail) {
        Node_delete(q->tail);
        q->tail = lastNode;
        q->tail->next = NULL;
        return s;
      }
    }
  }
  return s;
}

// remove the first element in the queue
String Queue_shift(Queue *q) {
  if(q == NULL) return NULL;
  String s = NULL;
  // empty queue
  if(q->head == NULL) return NULL;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has more than one
  } else {
    // just delete the first element and replace it with the next one
    Node *tmpNode = q->head->next;
    s = q->head->data;
    Node_delete(q->head);
    q->head = tmpNode;
  }
  return s;
}

// remove all the elements in the queue
void Queue_clear(Queue *q) {
  if(q != NULL) {
    Node *tmpNode = q->head;
    for(int i = 0, n = Queue_size(q);i < n; i++) {
      tmpNode = tmpNode->next;
      // using the Queue_shift instead of Queue_pop because it's faster(low processing cost)
      Queue_shift(q);
    }
  }
}

// remove all the elements in the queue and free the memory of the queue
void Queue_delete(Queue *q) {
  if(q != NULL) {
    Queue_clear(q);
    free(q);
  }
}

// check if the queue is empty
bool Queue_isEmpty(Queue *q) {
  return q == NULL || q->head == NULL;
}

int main(void) {
  Queue *a = NULL;
  Queue_print(a);
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(&a, "txt1");
  printf("Size: %d\n", Queue_size(a));
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(&a, "txt2");
  Queue_push(&a, "txt3");
  Queue_print(a);
  Queue_shift(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_pop(a);
  Queue_push(&a, "txt4");
  Queue_push(&a, "txt5");
  printf("Size: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_clear(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_push(&a, "txt");
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_delete(a);
  return 0;
}
```

<p><strong>output</strong></p>

```Is empty: true
Size: 1
Is empty: false
{txt1, txt2, txt3}
Size: 2
Size: 3
{txt2, txt4, txt5}
Size: 0
{}
Size: 1
{txt}
```

Body:
I was making simple Linked list Queue program using C and i get this exception from my print function.

Exception thrown: read access violation. temp was 0x740069.

I'm still a beginner when it comes to C language so I don't getting use to managing memory and using pointers yet. So I'm not sure if the cause comes from my push function or my print function.

So i would like to ask what is the cause of this exception and how to fix it.

My code are as follow

struct node_struct {
    char *data;
    struct node_struct *next;
};

typedef struct node_struct Node;

struct queue_struct {
    Node *head, *tail;
};

typedef struct queue_struct Queue;

void push(Queue *q, char *word)
{
    // IMPLEMENT
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = (char*)malloc(sizeof(char));
    temp->data = word;
    temp->next = NULL;
    if (q->head == NULL )
    {
        q->head= temp;
    }
    else
    {
        q->tail->next = temp;
    }
    q->tail = temp;
    q->tail->next = q->head;
}

char *pop(Queue *q)
{
    // IMPLEMENT
    Node* temp = q->head;
    char n = q->head->data;
    q->head = q->head->next;
    free(temp);
    return(n);
}

void print(Queue *q)
{
    // IMPLEMENT
    if (q == NULL)
    {
        printf("No Items\n");
    }
    else
    {
        //Node* temp = (Node*)malloc(sizeof(Node));
        Node* temp = q->head;
        while (temp != NULL)
        {
            printf("%c\n", temp->data);
            temp = temp->next;
        }
    }
}

void print(Queue *q)
{
    // IMPLEMENT
    if (q == NULL || isEmpty(q))
    {
        printf("No Items\n");
    }
    else
    {
        //Node* temp = (Node*)malloc(sizeof(Node));
        Node* temp = q->head;
        while (temp != NULL)
        {
            printf("%c\n", temp->data);
            temp = temp->next;
        }
    }
}

int isEmpty(Queue *q)
{
    // IMPLEMENT
    if (q->head == NULL)
        return 1;
    return 0;
}

void delete(Queue *q)
{
    // IMPLEMENT
    Node* temp;
    while (q->head != NULL)
    {
        temp = q->head;
        q->head = q->head->next;
        delete(temp);
    }
    q->tail = NULL;
}

int main(int argc, char **argv)
{
    Queue *q = NULL;

    // print the queue
    print(q);

    // push items
    push(&q, "a");
    push(&q, "b");
    push(&q, "c");
    print(q);
}

And the output is in image below

Current output of my Queue

Body:
Well in my case I use a field to store the size of the list, but it can be done without it, here is my implementation for a queue, I have added some comments for clarity, maybe you will find it useful. and i have added just few functions, you can add more if you like, it's just for giving you a startup :)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// make an alias for better readability
typedef char * String;

typedef struct node_struct {
  String data;
  struct node_struct *next;
} Node;

typedef struct queue_struct {
  Node *head, *tail;
} Queue;

// create a new node, allocating the memory and copying the value...
Node * Node_create(String str) {
  Node *node = (Node *)malloc(sizeof(Node));
  if(node == NULL) return NULL;
  node->data = (String)malloc(strlen(str) + 1);
  if(node->data == NULL) return NULL;
  strcpy(node->data, str);
  node->next = NULL;
  return node;
}

// delete the node
void Node_delete(Node *node) {
  free(node->data);
  free(node);
}

// create a new Queue and set the head and tail to NULL(empty)
Queue * Queue_create() {
  Queue *queue = (Queue *)malloc(sizeof(Queue));
  if(queue == NULL) return NULL;
  queue->head = queue->tail = NULL;
  return queue;
}

// add a new node to the queue
bool Queue_push(Queue *q, String str) {
  Node* node = Node_create(str);
  if(node == NULL) return false;
  // empty queue
  if(q->head == NULL) {
    q->head = q->tail = node;
  // has only one element
  }else if(q->head == q->tail) {
    q->head->next = q->tail = node;
  // has more than one element
  }else {
    q->tail->next = node;
    q->tail = q->tail->next;
  }
  return true;
}

// print the elements of the queue
void Queue_print(Queue *q) {
  Node *tmpNode = q->head;
  printf("{");
  // loop over the queue
  while(tmpNode != NULL) {
    printf("%s", tmpNode->data);
    // don't print ',' if its the last element
    tmpNode != q->tail && printf(", ");
    tmpNode = tmpNode->next;
  }
  printf("}");
}

// get the size of the queue
int Queue_size(Queue *q) {
  Node *tmpNode = q->head;
  int size = 0;
  while(tmpNode != NULL) {
    tmpNode = tmpNode->next;
    size++;
  }
  return size;
}

// remove the last element in the queue
String Queue_pop(Queue *q) {
  String s = NULL;
  // empty queue
  if(q->head == NULL) return s;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has two elements
  }else if(q->head->next == q->tail) {
    s = q->tail->data;
    Node_delete(q->tail);
    q->tail = q->head;
    q->head->next = q->tail;
    q->tail->next = NULL;
  // has more than two
  }else {
    s = q->tail->data;
    Node *tmpNode = q->head, *lastNode;
    // loop over the queue and get the element before the last one
    while(tmpNode != NULL) {
      lastNode = tmpNode;
      tmpNode = tmpNode->next;
      // delete the last element and replace it with the previous element
      if(tmpNode == q->tail) {
        Node_delete(q->tail);
        q->tail = lastNode;
        q->tail->next = NULL;
        return s;
      }
    }
  }
  return s;
}

// remove the first element in the queue
String Queue_shift(Queue *q) {
  String s = NULL;
  // empty queue
  if(q->head == NULL) return NULL;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has more than one
  } else {
    // just delete the first element and replace it with the next one
    Node *tmpNode = q->head->next;
    s = q->head->data;
    Node_delete(q->head);
    q->head = tmpNode;
  }
  return s;
}

// remove all the elements in the queue
void Queue_clear(Queue *q) {
  Node *tmpNode = q->head;
  for(int i = 0, n = Queue_size(q);i < n; i++) {
    tmpNode = tmpNode->next;
    // using the Queue_shift instead of Queue_pop because it's faster(low processing cost)
    Queue_shift(q);
  }
}

// remove all the elements in the queue and free the memory of the queue
void Queue_delete(Queue *q) {
  Queue_clear(q);
  free(q);
}

// check if the queue is empty
bool Queue_isEmpty(Queue *q) {
  return q->head == NULL;
}

int main(void) {
  Queue *a = Queue_create();
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(a, "txt1");
  printf("Size: %d\n", Queue_size(a));
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(a, "txt2");
  Queue_push(a, "txt3");
  Queue_print(a);
  Queue_shift(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_pop(a);
  Queue_push(a, "txt4");
  Queue_push(a, "txt5");
  printf("Size: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_clear(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_push(a, "txt");
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_delete(a);
  return 0;
}

output

Is empty: true
Size: 1
Is empty: false
{txt1, txt2, txt3}
Size: 2
Size: 3
{txt2, txt4, txt5}
Size: 0
{}
Size: 1
{txt}

Ok according to your comment:

I currently experiment with your version right now i want to ask if i don't want to use Queue *a = Queue_create(); in the main function but instead i want to made Queue *a = NULL; and then allocate space for it in push function how would you do it?

You can do it this way, note that you can still use the other functions the same way with no modifications. and even you still can use Queue_create Directly like Queue *q = Queue_create(); like in the first part.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// make an alias for better readability
typedef char * String;

typedef struct node_struct {
  String data;
  struct node_struct *next;
} Node;

typedef struct queue_struct {
  Node *head, *tail;
} Queue;

// create a new node, allocating the memory and copying the value...
Node * Node_create(String str) {
  Node *node = (Node *)malloc(sizeof(Node));
  if(node == NULL) return NULL;
  node->data = (String)malloc(strlen(str) + 1);
  if(node->data == NULL) return NULL;
  strcpy(node->data, str);
  node->next = NULL;
  return node;
}

// delete the node
void Node_delete(Node *node) {
  free(node->data);
  free(node);
}

// create a new Queue and set the head and tail to NULL(empty)
Queue * Queue_create() {
  Queue *queue = (Queue *)malloc(sizeof(Queue));
  if(queue == NULL) return NULL;
  queue->head = queue->tail = NULL;
  return queue;
}

// add a new node to the queue
bool Queue_push(Queue **q, String str) {
  // if there is no allocated Queue then we need to allocate one using the Queue_create() we already have
  if(*q == NULL) {
    *q = Queue_create();
    if(*q == NULL) return false;
  }
  Node* node = Node_create(str);
  if(node == NULL) return false;
  // empty queue
  if((*q)->head == NULL) {
    (*q)->head = (*q)->tail = node;
  // has only one element
  }else if((*q)->head == (*q)->tail) {
    (*q)->head->next = (*q)->tail = node;
  // has more than one element
  }else {
    (*q)->tail->next = node;
    (*q)->tail = (*q)->tail->next;
  }
  return true;
}

// print the elements of the queue
void Queue_print(Queue *q) {
  if(q != NULL) {
    Node *tmpNode = q->head;
    printf("{");
    // loop over the queue
    while(tmpNode != NULL) {
      printf("%s", tmpNode->data);
      // don't print ',' if its the last element
      tmpNode != q->tail && printf(", ");
      tmpNode = tmpNode->next;
    }
    printf("}");
  }
}

// get the size of the queue
int Queue_size(Queue *q) {
  if(q == NULL) return 0;
  Node *tmpNode = q->head;
  int size = 0;
  while(tmpNode != NULL) {
    tmpNode = tmpNode->next;
    size++;
  }
  return size;
}

// remove the last element in the queue
String Queue_pop(Queue *q) {
  if(q == NULL) return NULL;
  String s = NULL;
  // empty queue
  if(q->head == NULL) return s;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has two elements
  }else if(q->head->next == q->tail) {
    s = q->tail->data;
    Node_delete(q->tail);
    q->tail = q->head;
    q->head->next = q->tail;
    q->tail->next = NULL;
  // has more than two
  }else {
    s = q->tail->data;
    Node *tmpNode = q->head, *lastNode;
    // loop over the queue and get the element before the last one
    while(tmpNode != NULL) {
      lastNode = tmpNode;
      tmpNode = tmpNode->next;
      // delete the last element and replace it with the previous element
      if(tmpNode == q->tail) {
        Node_delete(q->tail);
        q->tail = lastNode;
        q->tail->next = NULL;
        return s;
      }
    }
  }
  return s;
}

// remove the first element in the queue
String Queue_shift(Queue *q) {
  if(q == NULL) return NULL;
  String s = NULL;
  // empty queue
  if(q->head == NULL) return NULL;
  // has one element
  if(q->head == q->tail) {
    s = q->head->data;
    Node_delete(q->head);
    q->head = q->tail = NULL;
  // has more than one
  } else {
    // just delete the first element and replace it with the next one
    Node *tmpNode = q->head->next;
    s = q->head->data;
    Node_delete(q->head);
    q->head = tmpNode;
  }
  return s;
}

// remove all the elements in the queue
void Queue_clear(Queue *q) {
  if(q != NULL) {
    Node *tmpNode = q->head;
    for(int i = 0, n = Queue_size(q);i < n; i++) {
      tmpNode = tmpNode->next;
      // using the Queue_shift instead of Queue_pop because it's faster(low processing cost)
      Queue_shift(q);
    }
  }
}

// remove all the elements in the queue and free the memory of the queue
void Queue_delete(Queue *q) {
  if(q != NULL) {
    Queue_clear(q);
    free(q);
  }
}

// check if the queue is empty
bool Queue_isEmpty(Queue *q) {
  return q == NULL || q->head == NULL;
}

int main(void) {
  Queue *a = NULL;
  Queue_print(a);
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(&a, "txt1");
  printf("Size: %d\n", Queue_size(a));
  printf("Is empty: %s\n", Queue_isEmpty(a) ? "true" : "false");
  Queue_push(&a, "txt2");
  Queue_push(&a, "txt3");
  Queue_print(a);
  Queue_shift(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_pop(a);
  Queue_push(&a, "txt4");
  Queue_push(&a, "txt5");
  printf("Size: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_clear(a);
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_push(&a, "txt");
  printf("\nSize: %d\n", Queue_size(a));
  Queue_print(a);
  Queue_delete(a);
  return 0;
}

output

Is empty: true
Size: 1
Is empty: false
{txt1, txt2, txt3}
Size: 2
Size: 3
{txt2, txt4, txt5}
Size: 0
{}
Size: 1
{txt}


问:
How do I solve a function for a given x?
I have been browsing through quite some help pages, but I did not find the solution for my - probably - simple problem.
I defined a function

```<code>funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))
</code>```

and would like to solve it for a given x (say, x = 0.2).
How do I do that? I have looked at uniroot() and polyroot(), but they did not seem to fit my function.

Body:
I have been browsing through quite some help pages, but I did not find the solution for my - probably - simple problem.
I defined a function

funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))

and would like to solve it for a given x (say, x = 0.2).
How do I do that? I have looked at uniroot() and polyroot(), but they did not seem to fit my function.

Body:
funB <- function(x) (0.8042851 + ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))

# call the function with desired input
funB(0.2)

...and the output:

> funB(0.2)
[1] 1.087758
>


问:
get id attribute of selected items in drop down box
I have many drop down boxes with the name emp .so in the below code i am trying to print the id of the boxes but some how it is printing empty what am i doing wrong here</p>

```<code>  var selected_emp = $('select[name="emp"]');
     selected_emp.children('option:selected').each(function() {
        if($(this).val() != '' && $(this).val() != null)
        {
           alert($(this).attr('id'));
        }
     });
</code>```

答:
Do your option elements have an id attribute?  Typically, option elements just have a value and the included text.  You could do something like this to print the id of the box and the selected value in the box:

```<code> var selected_emp = $('select[name="emp"]');
 selected_emp.children('option:selected').each(function() {
    if($(this).val() != '' && $(this).val() != null)
    {
       alert($(this).parent().attr('id') + ":" + $(this).val());
    }
 });
</code>```

Or, to just iterate through the select boxes themselves:

```<code>$('select[name="emp"]').each(function() {
    alert(this.Id);
}
</code>```

Body:
I have many drop down boxes with the name emp .so in the below code i am trying to print the id of the boxes but some how it is printing empty what am i doing wrong here

  var selected_emp = $('select[name="emp"]');
     selected_emp.children('option:selected').each(function() {
        if($(this).val() != '' && $(this).val() != null)
        {
           alert($(this).attr('id'));
        }
     });

Body:
Do your option elements have an id attribute?  Typically, option elements just have a value and the included text.  You could do something like this to print the id of the box and the selected value in the box:

 var selected_emp = $('select[name="emp"]');
 selected_emp.children('option:selected').each(function() {
    if($(this).val() != '' && $(this).val() != null)
    {
       alert($(this).parent().attr('id') + ":" + $(this).val());
    }
 });

Or, to just iterate through the select boxes themselves:

$('select[name="emp"]').each(function() {
    alert(this.Id);
}


问:
Sometimes Unable to Import NumPy
When I work in Jupyter Notebooks everything works fine, and I can import numpy and pandas successfully. However, when I try to download the script and then run it in an editor such as PyCharm or Atom, I get an import error: no module named numpy, and the same for pandas. How do I fix this? Is this due to the packages being installed in a different location than where I am downloading the code? Everything is installed with Anaconda, and when I try to do ```conda install numpy`` it tells me that all packages have already been installed.</p>

答:
This may be because Pycharm and Atom are using your default python install rather than your anaconda python environment.

You can configure Pycharm to use your conda environment via (https://www.jetbrains.com/help/pycharm/conda-support-creating-conda-virtual-environment.html).

Title: Sometimes Unable to Import NumPy


问:
Cron not running shell program stored on desktop
I am trying to run a shell (.sh file) program that will then run a python script making requests from a website. The python program outputs a file containing json data to my desktop and I would like this to run at 10AM Monday-Friday.

This is my .sh shell file. It runs correctly when executed manually from from terminal:

```<code>#!/bin/sh
python tester.py
</code>```

This is what I have been using to test the shell. This would run every minute and produce my output file but it is not working:

```<code>* * * * * /path/to/file/test.sh && ./test.sh
</code>```

I have tried a couple other syntax combinations as follows:

```<code>* * * * * sh /path/to/file
* * * * * sh /path/to/file/test.sh && sh test.sh
</code>```

I am aware the correct notation for a program running at 10am mon-fri would be:

```<code>0 10 * * 1-5
</code>```

Nothing seems to be working and I am at a complete loss.. Any help would be greatly appreciated.

答: Just use a line for /path/to/file/test.sh in the crontab.  As furas mentioned in their comment you shouldn't need to use the &&. It shouldn't matter if the script is on your desktop if the path is correct.  You can also check the syslog to see if there are any errors.</p>

Body:
I am trying to run a shell (.sh file) program that will then run a python script making requests from a website. The python program outputs a file containing json data to my desktop and I would like this to run at 10AM Monday-Friday.

This is my .sh shell file. It runs correctly when executed manually from from terminal:

#!/bin/sh
python tester.py

This is what I have been using to test the shell. This would run every minute and produce my output file but it is not working:

* * * * * /path/to/file/test.sh && ./test.sh

I have tried a couple other syntax combinations as follows:

* * * * * sh /path/to/file
* * * * * sh /path/to/file/test.sh && sh test.sh

I am aware the correct notation for a program running at 10am mon-fri would be:

0 10 * * 1-5

Nothing seems to be working and I am at a complete loss.. Any help would be greatly appreciated.


问:
Python. How to convert a sqlite3 database into an Excel file
I have a database sqlite3 and use Python

Question: How to convert my sqlite3 database in excel file on Python. And if I call this function again for conversion, then how to overwrite this excel file.

I think that the Excel file will look like this: column names in Excel = column names in the database, and each new order on a new line.

Also i have screen of my database (if it help u))

Code:

```<code>        CREATE TABLE IF NOT EXISTS order_info (
            id                  INTEGER PRIMARY KEY,
            name                TEXT NOT NULL,
            surname             TEXT NOT NULL,
            email               TEXT NOT NULL,
            date                TEXT NOT NULL,
            time                TEXT NOT NULL,
            phone               TEXT NOT NULL,
            contact             TEXT NOT NULL,
            idd                 TEXT NOT NULL,
            doc                 TEXT NOT NULL,
            problem             TEXT NOT NULL,
            status              TEXT,
            dis_reason          TEXT,
            new_date            TEXT,
            doc_list            TEXT DEFAULT '1 2 3',
            is_send             INT NOT NULL DEFAULT 0
</code>```

My functions in db.py looks like:

```<code>@ensure_connection
def count_orders(conn):
    c = conn.cursor()
    c.execute('SELECT COUNT(*) FROM order_info')
    (res, ) = c.fetchone()
    return res
</code>```

答: You can create a csv file and then import this file in excel. https://docs.python.org/3/library/csv.html</p>

Body:
I have a database sqlite3 and use Python

Question: How to convert my sqlite3 database in excel file on Python. And if I call this function again for conversion, then how to overwrite this excel file.

I think that the Excel file will look like this: column names in Excel = column names in the database, and each new order on a new line.

Also i have screen of my database (if it help u))

Code:

        CREATE TABLE IF NOT EXISTS order_info (
            id                  INTEGER PRIMARY KEY,
            name                TEXT NOT NULL,
            surname             TEXT NOT NULL,
            email               TEXT NOT NULL,
            date                TEXT NOT NULL,
            time                TEXT NOT NULL,
            phone               TEXT NOT NULL,
            contact             TEXT NOT NULL,
            idd                 TEXT NOT NULL,
            doc                 TEXT NOT NULL,
            problem             TEXT NOT NULL,
            status              TEXT,
            dis_reason          TEXT,
            new_date            TEXT,
            doc_list            TEXT DEFAULT '1 2 3',
            is_send             INT NOT NULL DEFAULT 0

My functions in db.py looks like:

@ensure_connection
def count_orders(conn):
    c = conn.cursor()
    c.execute('SELECT COUNT(*) FROM order_info')
    (res, ) = c.fetchone()
    return res


问:
Read file line by line ARDUINO
I'm doing a function for my project in Arduino, for read line by line a file (log.txt) stored in a SdCard, and send (every line) it over Bluetooth.
The format of log is:

```<code>020/5/25 18:15:46|0*26.0 34.5
020/5/25 18:16:46|0*26.0 34.2
</code>```

I need to cut every line in two string (delimiter = '|'), and then send to an Android App (over BLE)
I use the next library for cut every line in two strings:https://www.somosioticos.com/archivos/separador.zip
And my code is:

```<code>void R_SdCard(){
   File printFile;
   String Buffer_Read_Line = "";
   String Sub_String_A = "";
   String Sub_String_B = "";

   printFile = SD.open("Log.txt", FILE_READ);

   while(printFile.available()){
     Buffer_Read_Line=printFile.readStringUntil("\r\n");
     Sub_String_A=S.separa(Buffer_Read_Line,'|',0);
     Sub_String_B=S.separa(Buffer_Read_Line,'|',1);
     HM10.println(Sub_String_A);
     delay(3000);
     HM10.println(Sub_String_B);
     delay(3000);
   }
   printFile.close();
}
</code>```

For string Sub_String_A, the output is:

```<code>020/5/25 18:15:46
</code>```

For string Sub_String_B, the output is:

```<code>18:15:46
</code>```

These is correct, but only read one line of the file... I need read every line in this file.
How can I do it???
Thx in advance!

答:
Ok, I found the solution.
The code is:

```<code>void R_SdCard(){
  File printFile;
  String Buffer_Read_Line = "";
  String Sub_String_A = "";
  String Sub_String_B = "";
  int LastPosition=0;

  printFile = SD.open("Log.txt");
  int totalBytes = printFile.size();

  while (printFile.available()){
    for(LastPosition=0; LastPosition<= totalBytes; LastPosition++){
      char caracter=printFile.read();
      Buffer_Read_Line=Buffer_Read_Line+caracter;
      if(caracter==10 ){            //ASCII new line
        Serial.println(Buffer_Read_Line);
        Sub_String_A=S.separa(Buffer_Read_Line,'|',0);
        Sub_String_B=S.separa(Buffer_Read_Line,'|',1);
        HM10.println(Sub_String_A);
        HM10.println(Sub_String_B);
        Buffer_Read_Line="";      //string to 0
      }
    }
  }
  printFile.close();
}
</code>```

I hope this code is helpful for those who need read data from a file!
Greetings!

Title: Read file line by line ARDUINO

Body:
I'm doing a function for my project in Arduino, for read line by line a file (log.txt) stored in a SdCard, and send (every line) it over Bluetooth.
The format of log is:

020/5/25 18:15:46|0*26.0 34.5
020/5/25 18:16:46|0*26.0 34.2

I need to cut every line in two string (delimiter = '|'), and then send to an Android App (over BLE)
I use the next library for cut every line in two strings:https://www.somosioticos.com/archivos/separador.zip
And my code is:

void R_SdCard(){
   File printFile;
   String Buffer_Read_Line = "";
   String Sub_String_A = "";
   String Sub_String_B = "";

   printFile = SD.open("Log.txt", FILE_READ);

   while(printFile.available()){
     Buffer_Read_Line=printFile.readStringUntil("\r\n");
     Sub_String_A=S.separa(Buffer_Read_Line,'|',0);
     Sub_String_B=S.separa(Buffer_Read_Line,'|',1);
     HM10.println(Sub_String_A);
     delay(3000);
     HM10.println(Sub_String_B);
     delay(3000);
   }
   printFile.close();
}

For string Sub_String_A, the output is:

020/5/25 18:15:46

For string Sub_String_B, the output is:

18:15:46

These is correct, but only read one line of the file... I need read every line in this file.
How can I do it???
Thx in advance!

Body:
Ok, I found the solution.
The code is:

void R_SdCard(){
  File printFile;
  String Buffer_Read_Line = "";
  String Sub_String_A = "";
  String Sub_String_B = "";
  int LastPosition=0;

  printFile = SD.open("Log.txt");
  int totalBytes = printFile.size();

  while (printFile.available()){
    for(LastPosition=0; LastPosition<= totalBytes; LastPosition++){
      char caracter=printFile.read();
      Buffer_Read_Line=Buffer_Read_Line+caracter;
      if(caracter==10 ){            //ASCII new line
        Serial.println(Buffer_Read_Line);
        Sub_String_A=S.separa(Buffer_Read_Line,'|',0);
        Sub_String_B=S.separa(Buffer_Read_Line,'|',1);
        HM10.println(Sub_String_A);
        HM10.println(Sub_String_B);
        Buffer_Read_Line="";      //string to 0
      }
    }
  }
  printFile.close();
}

I hope this code is helpful for those who need read data from a file!
Greetings!


问:
Python3 IMAP search special characters
I would like to find a note over IMAP using Python3 and it's IMAP extension. I try to search for a subject which contains special chars as in the example below. Is there a way I can encode the search string to be IMAP compatible?

```<code>self.connection.search(None, 'ALL', 'SUBJECT "büro"')
</code>```

returns

```<code>UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 10: ordinal not in range(128)
</code>```

答:
If there are special characters in search string, than literal must be used according to https://www.rfc-editor.org/rfc/rfc3501#page-54. Python imaplib does not do it for search command. So need to use workaround:

```<code>    imap.literal = subject.encode('UTF-8')
    status, data = imap.uid('SEARCH', 'CHARSET UTF-8 SUBJECT')
    # fetch is also must be used via uid command after this
</code>```

without uid version:

```<code>    imap.literal = subject.encode('UTF-8')
    typ, dat = imap._simple_command('SEARCH', "CHARSET UTF-8 SUBJECT")
    status, data = imap._untagged_response(typ, dat, 'SEARCH')
</code>```

Title: Python3 IMAP search special characters

Body:
I would like to find a note over IMAP using Python3 and it's IMAP extension. I try to search for a subject which contains special chars as in the example below. Is there a way I can encode the search string to be IMAP compatible?

self.connection.search(None, 'ALL', 'SUBJECT "büro"')

returns

UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 10: ordinal not in range(128)

Body:
If there are special characters in search string, than literal must be used according to https://www.rfc-editor.org/rfc/rfc3501#page-54. Python imaplib does not do it for search command. So need to use workaround:

    imap.literal = subject.encode('UTF-8')
    status, data = imap.uid('SEARCH', 'CHARSET UTF-8 SUBJECT')
    # fetch is also must be used via uid command after this

without uid version:

    imap.literal = subject.encode('UTF-8')
    typ, dat = imap._simple_command('SEARCH', "CHARSET UTF-8 SUBJECT")
    status, data = imap._untagged_response(typ, dat, 'SEARCH')


问:
Convert integer to character int j2me
I want to convert the integer into char.

Example:-

```<code>char c;
for(int i=0;i<10;i++){
    system.out.println(" char==="+c);
}
</code>```

I want to print the c as 0,1,2,3,4.....
I had tried :-

```<code>c=(char)i; --gives error
c=97-i; -----gives a,b,c
</code>```

答:
Use wrapper classes.

```<code>c = new Integer(i).toString().charAt(0);
</code>```

by the way, you can also use this :

```<code>c = (char)(i + 48);
</code>```

Title: Convert integer to character int j2me

Body:
I want to convert the integer into char.

Example:-

char c;
for(int i=0;i<10;i++){
    system.out.println(" char==="+c);
}

I want to print the c as 0,1,2,3,4.....
I had tried :-

c=(char)i; --gives error
c=97-i; -----gives a,b,c

Body:
Use wrapper classes.

c = new Integer(i).toString().charAt(0);

by the way, you can also use this :

c = (char)(i + 48);


问:
Getting AttributeError: __enter__ when using Microphone from Speech Recognizer
The code is below. As I researched the documention Speech_Recognision must be installed if we use Microphone. So I installed it but still i have this error.

```<code>def recordAudio():

r = sr.Recognizer()

with sr.Microphone as source:
    print('I am listening to you sir.')
    audio = r.listen(source)
    data = ''

try:
    data = r.recognize_google(audio)
    print('You said: ' + data)
except sr.UnknownValueError:
    print('Voice cannot be recognized.')
except sr.RequestError as e:
    print('Req results:' + e)

return data
</code>```

line 54, in recordAudio
    with sr.Microphone as source:
AttributeError: __enter__

答:
It would constantly listen until you terminate:
SpeechRecognition</p>

```<code>import speech_recognition as sr

def speech_recog():
    r = sr.Recognizer()

    mic = sr.Microphone()
    while True:
        with mic as source:
            print("Speak...")

            audio = r.listen(source)

            try:
                text = r.recognize_google(audio)
                print(f"You said {text}")

            except sr.UnknownValueError:
                print("Didnt hear that try again")
speech_recog()
</code>```

Body:
The code is below. As I researched the documention Speech_Recognision must be installed if we use Microphone. So I installed it but still i have this error.

def recordAudio():

r = sr.Recognizer()

with sr.Microphone as source:
    print('I am listening to you sir.')
    audio = r.listen(source)
    data = ''

try:
    data = r.recognize_google(audio)
    print('You said: ' + data)
except sr.UnknownValueError:
    print('Voice cannot be recognized.')
except sr.RequestError as e:
    print('Req results:' + e)

return data

line 54, in recordAudio
    with sr.Microphone as source:
AttributeError: __enter__

Body:
It would constantly listen until you terminate:
SpeechRecognition

import speech_recognition as sr

def speech_recog():
    r = sr.Recognizer()

    mic = sr.Microphone()
    while True:
        with mic as source:
            print("Speak...")

            audio = r.listen(source)

            try:
                text = r.recognize_google(audio)
                print(f"You said {text}")

            except sr.UnknownValueError:
                print("Didnt hear that try again")
speech_recog()


答:
Anaconda uses virtual conda environments to store the Python interpreter and libraries. If this isn't set up in your IDE, it won't see the libraries. This is described in this post: Use Conda environment in pycharm

Check your PyCharm interpreter options: File > Settings > Project > Project Interpreter. Make sure your desired Anaconda interpreter/environment is selected.

If your Anaconda environment isn't selected, click the Project Interpreter drop-down. if you see it there, select it. If not, click Show All... then + (Add) and browse to the Anaconda folder.

This post describes how to set up conda in Atom:
Using anaconda environment in Atom

Title: Sometimes Unable to Import NumPy

Body: When I work in Jupyter Notebooks everything works fine, and I can import numpy and pandas successfully. However, when I try to download the script and then run it in an editor such as PyCharm or Atom, I get an import error: no module named numpy, and the same for pandas. How do I fix this? Is this due to the packages being installed in a different location than where I am downloading the code? Everything is installed with Anaconda, and when I try to do ```conda install numpy`` it tells me that all packages have already been installed.


问:
Securing SQL Connection string in ASP.NET Core Windows authentication application
Is there a way to secure the connection string or any user secret for ASP.NET Core application using Windows authentication?</p>

答:
In general, if you're using Windows Authentication, the connection string shouldn't need to contain sensitive data - if it does, you likely have a mistake in it. Your connection string should contain the absolute minimum amount of information required to connect to your database (e.g. server name, authentication type) - no more.

By definition, if you're using Always Encrypted, you don't need to include any user secret in your connection string in order to log on - so don't include it.

Any other user secrets not related to connecting to the database can be stored via another mechanism, such as SQL Server's Always Encrypted mechanism.


问:
Nginx Static content caching proxy_cache_bypass proxy_no_cache
I have a problem with using nginx as a load balancer. I could configure it to work as a load balancer but I don't how to make it cache static contents from the proxied servers in the backend such as html,css,js, etc... This means I want nginx to
weather to cache or not based on the content of the response from the backend servers if it changed to bypass cache and send requests to the backend and if not to serve from cache. I tried and seached a lot in the internet to make it using many directives such as proxy_cache_bypass and proxy_no_cache but I couldn't. Is there any means to do this if anyone has experience in such topic. these are the configurations:

```<code>upstream backend {
    server www.webserver1.com:443 max_fails=3 fail_timeout=15s;
    server www.webserver2.com:443 max_fails=3 fail_timeout=15s;
}

server {
    listen      443 ssl;

    rewrite_log on;
    error_log   /var/log/nginx/lb.error.log;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Proxy-Cache $upstream_cache_status;
    ssl_certificate         /etc/nginx/client.crt;
    ssl_certificate_key     /etc/nginx/client.key;
    ssl on;

    location / {
        proxy_cache backcache;
        #proxy_cache_methods GET HEAD POST;
        #proxy_cache_bypass $cookie_nocache $arg_nocache;
        #proxy_no_cache $cookie_nocache $arg_nocache;
        proxy_cache_min_uses 1;
        #proxy_cache_revalidate on;
        #proxy_cache_valid 200 4m;
        proxy_cache_lock on;
        proxy_cache_background_update on;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_pass https://backend;
    }

}

server {
    listen 80 ;
    if ($http_x_forwarded_proto != 'https') {
        rewrite ^(.*) https://$host$1 redirect;
    }
}

</code>```

these are the contents of a config. file under /etc/nginx/conf.d/ which is included in the main config. file which is /etc/nginx/nginx.conf and also those 2 lines are in the main config. file :

```<code>    proxy_cache_path /var/lib/nginx/cache keys_zone=backcache:20m max_size=100m;
    proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args$cookie_user";
</code>```

答:
Your backend servers could be the root cause of that problem, if those servers were improperly configured. For example sending Cache-Control headers on requests to static files.

According to that docs by default, NGINX respects the Cache-Control headers from origin servers. It does not cache responses with Cache-Control set to Private, No-Cache, or No-Store or with Set-Cookie in the response header.

You can permanently change this behavior by adding those directives:

```<code>proxy_ignore_headers Cache-Control;
proxy_cache_valid any 30m;
</code>```

So the config will look like:

```<code>    location / {
        proxy_cache backcache;
        proxy_cache_revalidate on;
        proxy_cache_min_uses 3;
        proxy_cache_valid 200 302 10m;;
        proxy_cache_lock on;
        proxy_cache_background_update on;
        proxy_ignore_headers Cache-Control;
        proxy_cache_valid any 30m;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_pass https://backend;
    }
</code>```

Hope it will help you to figure out.

Body:
I have a problem with using nginx as a load balancer. I could configure it to work as a load balancer but I don't how to make it cache static contents from the proxied servers in the backend such as html,css,js, etc... This means I want nginx to
weather to cache or not based on the content of the response from the backend servers if it changed to bypass cache and send requests to the backend and if not to serve from cache. I tried and seached a lot in the internet to make it using many directives such as proxy_cache_bypass and proxy_no_cache but I couldn't. Is there any means to do this if anyone has experience in such topic. these are the configurations:

upstream backend {
    server www.webserver1.com:443 max_fails=3 fail_timeout=15s;
    server www.webserver2.com:443 max_fails=3 fail_timeout=15s;
}

server {
    listen      443 ssl;

    rewrite_log on;
    error_log   /var/log/nginx/lb.error.log;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Proxy-Cache $upstream_cache_status;
    ssl_certificate         /etc/nginx/client.crt;
    ssl_certificate_key     /etc/nginx/client.key;
    ssl on;

    location / {
        proxy_cache backcache;
        #proxy_cache_methods GET HEAD POST;
        #proxy_cache_bypass $cookie_nocache $arg_nocache;
        #proxy_no_cache $cookie_nocache $arg_nocache;
        proxy_cache_min_uses 1;
        #proxy_cache_revalidate on;
        #proxy_cache_valid 200 4m;
        proxy_cache_lock on;
        proxy_cache_background_update on;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_pass https://backend;
    }

}

server {
    listen 80 ;
    if ($http_x_forwarded_proto != 'https') {
        rewrite ^(.*) https://$host$1 redirect;
    }
}

these are the contents of a config. file under /etc/nginx/conf.d/ which is included in the main config. file which is /etc/nginx/nginx.conf and also those 2 lines are in the main config. file :

    proxy_cache_path /var/lib/nginx/cache keys_zone=backcache:20m max_size=100m;
    proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args$cookie_user";

Body:
Your backend servers could be the root cause of that problem, if those servers were improperly configured. For example sending Cache-Control headers on requests to static files.

According to that docs by default, NGINX respects the Cache-Control headers from origin servers. It does not cache responses with Cache-Control set to Private, No-Cache, or No-Store or with Set-Cookie in the response header.

You can permanently change this behavior by adding those directives:

proxy_ignore_headers Cache-Control;
proxy_cache_valid any 30m;

So the config will look like:

    location / {
        proxy_cache backcache;
        proxy_cache_revalidate on;
        proxy_cache_min_uses 3;
        proxy_cache_valid 200 302 10m;;
        proxy_cache_lock on;
        proxy_cache_background_update on;
        proxy_ignore_headers Cache-Control;
        proxy_cache_valid any 30m;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_pass https://backend;
    }

Hope it will help you to figure out.


问:
How can I pass POST parameters in a URL?
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like >, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like href="https://stackoverflow.com/questions/6210900/how-to-pass-post-parameters-in-a-url#comment7231173_6210900">Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

答:
You can make a link perform an Ajax post request when it's clicked.

In jQuery:

```<code>$('a').click(function(e) {
    var $this = $(this);
    e.preventDefault();
    $.post('url', {'user': 'something', 'foo': 'bar'}, function() {
        window.location = $this.attr('href');
    });
});
</code>```

You could also make the link submit a POST form with JavaScript:

```<code><form action="url" method="post">
    <input type="hidden" name="user" value="something" />
    <a href="#">CLick</a>
</form>

<script>
    $('a').click(function(e) {
        e.preventDefault();
        $(this).parents('form').submit();
    });
</script>
</code>```

Body:
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like <a href="process_user.php?user=<user>>, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

Body:
You can make a link perform an Ajax post request when it's clicked.

In jQuery:

$('a').click(function(e) {
    var $this = $(this);
    e.preventDefault();
    $.post('url', {'user': 'something', 'foo': 'bar'}, function() {
        window.location = $this.attr('href');
    });
});

You could also make the link submit a POST form with JavaScript:

<form action="url" method="post">
    <input type="hidden" name="user" value="something" />
    <a href="#">CLick</a>
</form>

<script>
    $('a').click(function(e) {
        e.preventDefault();
        $(this).parents('form').submit();
    });
</script>