问:
Retrieve Blogs by UserID using Auth2.0 Token (Javascript)
I'm currency creating a Local Hosted Server (Using WAMP Server) to Manage My Blog Post.

I could able to retrieve Auth2.0 Token, but how to send the HTTP request with Auth2.0 Token?

When I use XMLHttpRequest with xhttp.setRequestHeader("Authorization", token);, I get an error

403: PERMISSION_DENIED

Code:

```<code>function get_token(clientID, redirectURI) {
    let client = new jso.JSO({
        providerID: "google",
        client_id: clientID,
        redirect_uri: redirectURI,
        authorization: "https://accounts.google.com/o/oauth2/auth",
        scopes: { request: ["https://www.googleapis.com/auth/blogger"] }
    });
    client.callback();
    client.getToken()
        .then((token) => {
            console.log("I got the token : ", token)
            viewblogs(token['access_token'])
        })
}

function viewblogs(token) {
    // How to get blog list by userID?
}

get_token(
        'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
        'http://127.0.0.1/API/Auth2.0/'
);
</code>```

Here is the Google Developer Docs but there is no example code to how to do it with JavaScript
https://developers.google.com/blogger/docs/3.0/using#RetrievingAUsersBlogs

答:
The Token is a JWT token so you should add Bearer before writing the token.

Try this:

```<code>xhttp.setRequestHeader("Authorization", "Bearer "+token);
</code>```

Body:
I'm currency creating a Local Hosted Server (Using WAMP Server) to Manage My Blog Post.

I could able to retrieve Auth2.0 Token, but how to send the HTTP request with Auth2.0 Token?

When I use XMLHttpRequest with xhttp.setRequestHeader("Authorization", token);, I get an error

403: PERMISSION_DENIED

Code:

function get_token(clientID, redirectURI) {
    let client = new jso.JSO({
        providerID: "google",
        client_id: clientID,
        redirect_uri: redirectURI,
        authorization: "https://accounts.google.com/o/oauth2/auth",
        scopes: { request: ["https://www.googleapis.com/auth/blogger"] }
    });
    client.callback();
    client.getToken()
        .then((token) => {
            console.log("I got the token : ", token)
            viewblogs(token['access_token'])
        })
}

function viewblogs(token) {
    // How to get blog list by userID?
}

get_token(
        'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
        'http://127.0.0.1/API/Auth2.0/'
);

Here is the Google Developer Docs but there is no example code to how to do it with JavaScript
https://developers.google.com/blogger/docs/3.0/using#RetrievingAUsersBlogs

Body:
The Token is a JWT token so you should add Bearer before writing the token.

Try this:

xhttp.setRequestHeader("Authorization", "Bearer "+token);


来源: stackexchange

问:
Duplicate data when working with multiple tables. Clarification needed
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

```<code>DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'
</code>```

答:
Please use below query,

With Join

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,
case when a.statementitem = 'Revenues' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
case when a.statementitem = 'Gross Profit' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
case when a.statementitem = 'Selling General & Admin Expenses' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit
FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol
where a.periodtype = 'Annual'
</code>```

Without Join

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,
case when a.statementitem = 'Revenues' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
case when a.statementitem = 'Gross Profit' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
case when a.statementitem = 'Selling General & Admin Expenses' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit
FROM Income a
where a.periodtype = 'Annual'
and a.symbol in ('AAPL');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'

Body:
Please use below query,

With Join

SELECT distinct a.yearmonth, a.symbol, periodtype,
case when a.statementitem = 'Revenues' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
case when a.statementitem = 'Gross Profit' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
case when a.statementitem = 'Selling General & Admin Expenses' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit
FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol
where a.periodtype = 'Annual'

Without Join

SELECT distinct a.yearmonth, a.symbol, periodtype,
case when a.statementitem = 'Revenues' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
case when a.statementitem = 'Gross Profit' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
case when a.statementitem = 'Selling General & Admin Expenses' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit
FROM Income a
where a.periodtype = 'Annual'
and a.symbol in ('AAPL');


问:
[ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'
```<code>error: TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.
  return Deno.openPlugin(localPath);
              ~~~~~~~~~~
    at https://deno.land/x/plugin_prepare@v0.6.0/mod.ts:64:15
</code>```

getting an error like this when server project
Help me anyone have any idea about this.
thank you

答:
You have to run Deno with --unstable flag.

You can check that openPlugin is currently an unstable API.

More info regarding stability here:

As of Deno 1.0.0, the Deno namespace APIs are stable. That means we
  will strive to make code working under 1.0.0 continue to work in
  future versions.

However, not all of Deno's features are ready for production yet.
  Features which are not ready, because they are still in draft phase,
  are locked behind the --unstable command line flag.

Body:
error: TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.
  return Deno.openPlugin(localPath);
              ~~~~~~~~~~
    at https://deno.land/x/plugin_prepare@v0.6.0/mod.ts:64:15

getting an error like this when server project
Help me anyone have any idea about this.
thank you


问:
C++ invalid function type casting
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

```<code>void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};
</code>```

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

答:
The problem is that 'B1Method' is not a simple function - it's a class method.  That means that when you call myB.B1Method(), you're actually calling 'B1Method(&myB)', effectively passing the this pointer as a hidden argument - so you can't convert M1Method to a std::function without specifying which object it should act on.

One approach that should work is using std::bind to construct a callable object from a combination of an object (class instance) and the method.  Something like:

```<code>void BNowCorrectCall() { A::AMethod(std::bind(&B::B1Method, this)); }
</code>```

Title: C++ invalid function type casting

Body:
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

Body:
The problem is that 'B1Method' is not a simple function - it's a class method.  That means that when you call myB.B1Method(), you're actually calling 'B1Method(&myB)', effectively passing the this pointer as a hidden argument - so you can't convert M1Method to a std::function without specifying which object it should act on.

One approach that should work is using std::bind to construct a callable object from a combination of an object (class instance) and the method.  Something like:

void BNowCorrectCall() { A::AMethod(std::bind(&B::B1Method, this)); }


问:
Why are busy indicators not displayed when sending requests?
I have some slow OData calls which need to present some sort of visual indicator to the user that something is happening.

I've read the API reference and seen functions like attachRequestSent(), setBusy(), BusyDialog, BusyIndicator, etc.

I tried using them accordingly but did not work for me. The problem seems to be oModel.create causing the whole app to hang while it executes. No loading indicators or anything can run since the app is frozen until the create function has returned.

Edit: I have set up an asynchronous batch read OData call. I have then wrapped the code for handling the received data in a function and called that function inside the success function in the batch call.

This works; the view loads and I see a busy indicator before the fields are populated with the data

oModel.submitBatch(/*fnSuccess*/);
```

Is this a good way to do it, or is there a better way which is more standard?

答:
The main problem seems to be oModel.create causing the whole app to hang while it executes. No loading indicators or anything can run since the app is frozen until the create function has returned.

Sounds like you've been using the now-deprecated sap.ui.model.odata.ODataModel the whole time, which sends mostly synchronous XHRs. Synchronous XHRs block the main thread (== UI thread) until the browser receives the response. The browser isn't then able to update the DOM to display the busy indicator during the round trip.

If anyone reading this has the same issue, please migrate to the newer equivalent model: sap/ui/model/odata/v2/ODataModel. It sends only asynchronous requests (AJAX), allowing the UI thread to handle other tasks (such as adding the busy indicator to the DOM) while the browser waits for the response.

Body:
I have some slow OData calls which need to present some sort of visual indicator to the user that something is happening.

I've read the API reference and seen functions like attachRequestSent(), setBusy(), BusyDialog, BusyIndicator, etc.

I tried using them accordingly but did not work for me. The problem seems to be oModel.create causing the whole app to hang while it executes. No loading indicators or anything can run since the app is frozen until the create function has returned.

Edit: I have set up an asynchronous batch read OData call. I have then wrapped the code for handling the received data in a function and called that function inside the success function in the batch call.

This works; the view loads and I see a busy indicator before the fields are populated with the data

oModel.submitBatch(/*fnSuccess*/);

Is this a good way to do it, or is there a better way which is more standard?


问:
Prevent public access to MySQL port running using Docker-compose
I'm running MySQL using Docker-compose on my server.

This is the related part of my docker-compose.yml:

mysql:
    image: mysql:5.7.27
    environment:
      - MYSQL_DATABASE=app
      - MYSQL_ROOT_PASSWORD=secret
    ports:
      - 3306:3306
```

Now, it's accessible from the Internet ([Server Static IP]:3306) and it seems so insecure.

I want to prevent it from being accessible from the Internet and let it only be accessible inside the server and through SSH.

答:
Specify localhost (127.0.0.1) as the IP to bind (see the updated ports attributes).

```<code>mysql:
    image: mysql:5.7.27
    environment:
      - MYSQL_DATABASE=app
      - MYSQL_ROOT_PASSWORD=secret
    ports:
      - 127.0.0.1:3306:3306
</code>```

I haven't tested this, but should work. As with anything security related, please do check yourself that it does work!

Body:
I'm running MySQL using Docker-compose on my server.

This is the related part of my docker-compose.yml:

mysql:
    image: mysql:5.7.27
    environment:
      - MYSQL_DATABASE=app
      - MYSQL_ROOT_PASSWORD=secret
    ports:
      - 3306:3306

Now, it's accessible from the Internet ([Server Static IP]:3306) and it seems so insecure.

I want to prevent it from being accessible from the Internet and let it only be accessible inside the server and through SSH.

Body:
Specify localhost (127.0.0.1) as the IP to bind (see the updated ports attributes).

mysql:
    image: mysql:5.7.27
    environment:
      - MYSQL_DATABASE=app
      - MYSQL_ROOT_PASSWORD=secret
    ports:
      - 127.0.0.1:3306:3306

I haven't tested this, but should work. As with anything security related, please do check yourself that it does work!


问:
"python manage.py makemigrations" Traceback errors after creating models.py in Django
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked.

It seems like a lot of the Traceback errors have nothing to do with the models.py though.

(hopefully these are easy to read, sorry)

The traceback error:

Traceback (most recent call last):

File "manage.py", line 21, in  main()

File "manage.py", line 17, in main execute_from_command_line(sys.argv)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django
  /core/management/init.py", line 401, in execute_from_command_line
  utility.execute()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py",
  line 377, in execute django.setup()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py",
  line 24, in setup apps.populate(settings.INSTALLED_APPS)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py",
  line 114, in populate app_config.import_models()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py",
  line 211, in import_models self.models_module =
  import_module(models_module_name)

File "/usr/lib/python3.6/importlib/init.py", line 126, in
  import_module return _bootstrap._gcd_import(name[level:], package,
  level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 955, in
  _find_and_load_unlocked

File "", line 665, in _load_unlocked

File "", line 678, in
  exec_module

File "", line 219, in
  _call_with_frames_removed

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  6, in  class Post(models.Model):

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  9, in Post date_posted = models.DateTimeField(defualt=timezone.now)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs)

TypeError: init() got an unexpected keyword argument 'defualt'

models.py:

```<code>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(defualt=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

答:
I hope this is for

date_posted = models.DateTimeField(defualt=timezone.now).

Try Migrate the model with out this field.If migrate then try

```<code>date_posted = models.DateTimeField(default=timezone.now,blank=True, null=True)
</code>```

Body:
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked.

It seems like a lot of the Traceback errors have nothing to do with the models.py though.

(hopefully these are easy to read, sorry)

The traceback error:

Traceback (most recent call last):

File "manage.py", line 21, in  main()

File "manage.py", line 17, in main execute_from_command_line(sys.argv)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django
  /core/management/init.py", line 401, in execute_from_command_line
  utility.execute()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py",
  line 377, in execute django.setup()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py",
  line 24, in setup apps.populate(settings.INSTALLED_APPS)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py",
  line 114, in populate app_config.import_models()

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py",
  line 211, in import_models self.models_module =
  import_module(models_module_name)

File "/usr/lib/python3.6/importlib/init.py", line 126, in
  import_module return _bootstrap._gcd_import(name[level:], package,
  level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 955, in
  _find_and_load_unlocked

File "", line 665, in _load_unlocked

File "", line 678, in
  exec_module

File "", line 219, in
  _call_with_frames_removed

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  6, in  class Post(models.Model):

File "/home/alatimer/Environments/djangoproject/blog/models.py", line
  9, in Post date_posted = models.DateTimeField(defualt=timezone.now)

File
  "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs)

TypeError: init() got an unexpected keyword argument 'defualt'

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(defualt=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

Body:
I hope this is for

date_posted = models.DateTimeField(defualt=timezone.now).

Try Migrate the model with out this field.If migrate then try

date_posted = models.DateTimeField(default=timezone.now,blank=True, null=True)


问:
How make one step from two steps in SQL - users working simultaneously
currently I have in one system implemented solution for my problem. But I think there exists better solution, but I have not found it yet. I hope someone could find couliton or hint in me some direciton.

I have system for spliting different kind of jobs. Each work is in PostgreSQL database in table "jobs", where one row is one job (can be done multiple times). Each job has an attribute how many times it can be done (how many users can work on it). So my table jobs works like this:

```<code>ID_JOB NAME DONE HAS_TO_BE_DONE
1 Puzzle Solving 2  3
2 Washing Dishes 1 3
</code>```

When users comes and ask for job:

User gets id of job when job meets condition DONE < HAS_TO_BE_DONE

For given job value DONE is incremented ( +1 )

It works, but when more users are working simultaneously I need to everytime LOCK (type: SERIALIZABLE) database (even for reading).

If I would not used database locking probled could occur:
User #1 comes - he is in step 1, (he knows Id of job he got), in same time (a few miliseconds later) comes User #2 and will ask for job and will be in step 1 and will get same job as User #1 because #User 1 did not managed step 2 yet (and didn't incremente DONE). This is reason why I have to completely lock database.

Does anyone know how to improve this method?
Currently it works, but in moment when 100 users are working simultaneously database locking is causing slowing application. Problems are these two steps when in first step I will find job for user and then in second step I increment value.

If anyone would come with better solution I would be happy. Thank you

答:
The simplest approach is to check and update in a single statement.

```<code>update jobs
set done = done + 1
where done < has_to_be_done
  and id = ?
</code>```

If it updates a row, there was a job to be done. If it doesn't, there was no job to be done.

But there's a problem. You only have two statuses: job needs to be done, job is done. What if 5 users are all working on the same job, but it only needs to be done twice? That's wasteful. You need three statuses:

queued

in progress

done

You could add these as columns to the table and increment/decrement them.

```<code>create table jobs (
  id bigserial primary key,
  name text not null,
  queued integer not null default 0 check (queued >= 0),
  in_progress integer not null default 0 check (in_progress >= 0),
  done integer not null default 0 check (done >= 0)
);
</code>```

Queue a job.

```<code>update jobs
set queued = queued + 1
where id = ?
</code>```

Start a job. If it updates a column, you got a job. If it doesn't, there are no jobs in the queue.

```<code>update jobs
set queued = queued - 1,
    in_progress = in_progress + 1
where queued > 0
  and id = ?
</code>```

Finish a job.

```<code>update jobs
set in_progress = in_progress - 1,
    done = done + 1
where in_progress > 0
  and id = ?
</code>```

Or, for even finer control, split it into two tables: jobs and a job queue.

```<code>create table jobs (
  id bigserial primary key
  name text not null
);

create table job_queue (
   id bigserial primary key
   job_id bigint not null references jobs(id) on delete cascade
);

jobs
id    name
1     Puzzle Solving
2     Washing Dishes

job_queue
id job_id
3  1
5  2
6  2
</code>```

Queue a job by inserting it.

```<code>insert into job_queue (job_id) values (?)
</code>```

Finish a job by deleting one entry. It's not necessary to first check. If a row is deleted, you finished a job.

```<code>delete from jobs_queue
where id = (
  select id from jobs_queue
  where job_id = ?
  limit 1
)
</code>```

We can combine the two. Flags and a job_queue table. We can store more information like who is doing the work, when it was queued, and so on.

```<code>create table job_queue (
   id bigserial primary key
   job_id bigint not null references jobs(id) on delete cascade,
   status text not null default 'queued',
   user_id bigint references users(id) on delete set null,
   created_at timestamp not null default current_timestamp,
   updated_at timestamp not null default current_timestamp
);
</code>```

Queue a job.

```<code>insert into job_queue (job_id) values (?)
</code>```

Start a job. Again, no check necessary. Instead, check if a row was updated.

```<code>create table jobs (
  id bigserial primary key,
  name text not null,
  queued integer not null default 0 check (queued >= 0),
  in_progress integer not null default 0 check (in_progress >= 0),
  done integer not null default 0 check (done >= 0)
);
</code>```0

Finish a job. Use the ID returned from the update if you have it.

```<code>create table jobs (
  id bigserial primary key,
  name text not null,
  queued integer not null default 0 check (queued >= 0),
  in_progress integer not null default 0 check (in_progress >= 0),
  done integer not null default 0 check (done >= 0)
);
</code>```1

Or find a queued job you have in progress and update that.

```<code>create table jobs (
  id bigserial primary key,
  name text not null,
  queued integer not null default 0 check (queued >= 0),
  in_progress integer not null default 0 check (in_progress >= 0),
  done integer not null default 0 check (done >= 0)
);
</code>```2

Body:
currently I have in one system implemented solution for my problem. But I think there exists better solution, but I have not found it yet. I hope someone could find couliton or hint in me some direciton.

I have system for spliting different kind of jobs. Each work is in PostgreSQL database in table "jobs", where one row is one job (can be done multiple times). Each job has an attribute how many times it can be done (how many users can work on it). So my table jobs works like this:

ID_JOB NAME DONE HAS_TO_BE_DONE
1 Puzzle Solving 2  3
2 Washing Dishes 1 3

When users comes and ask for job:

User gets id of job when job meets condition DONE < HAS_TO_BE_DONE

For given job value DONE is incremented ( +1 )

It works, but when more users are working simultaneously I need to everytime LOCK (type: SERIALIZABLE) database (even for reading).

If I would not used database locking probled could occur:
User #1 comes - he is in step 1, (he knows Id of job he got), in same time (a few miliseconds later) comes User #2 and will ask for job and will be in step 1 and will get same job as User #1 because #User 1 did not managed step 2 yet (and didn't incremente DONE). This is reason why I have to completely lock database.

Does anyone know how to improve this method?
Currently it works, but in moment when 100 users are working simultaneously database locking is causing slowing application. Problems are these two steps when in first step I will find job for user and then in second step I increment value.

If anyone would come with better solution I would be happy. Thank you

Body:
The simplest approach is to check and update in a single statement.

update jobs
set done = done + 1
where done < has_to_be_done
  and id = ?

If it updates a row, there was a job to be done. If it doesn't, there was no job to be done.

But there's a problem. You only have two statuses: job needs to be done, job is done. What if 5 users are all working on the same job, but it only needs to be done twice? That's wasteful. You need three statuses:

queued

in progress

done

You could add these as columns to the table and increment/decrement them.

create table jobs (
  id bigserial primary key,
  name text not null,
  queued integer not null default 0 check (queued >= 0),
  in_progress integer not null default 0 check (in_progress >= 0),
  done integer not null default 0 check (done >= 0)
);

Queue a job.

update jobs
set queued = queued + 1
where id = ?

Start a job. If it updates a column, you got a job. If it doesn't, there are no jobs in the queue.

update jobs
set queued = queued - 1,
    in_progress = in_progress + 1
where queued > 0
  and id = ?

Finish a job.

update jobs
set in_progress = in_progress - 1,
    done = done + 1
where in_progress > 0
  and id = ?

Or, for even finer control, split it into two tables: jobs and a job queue.

create table jobs (
  id bigserial primary key
  name text not null
);

create table job_queue (
   id bigserial primary key
   job_id bigint not null references jobs(id) on delete cascade
);

jobs
id    name
1     Puzzle Solving
2     Washing Dishes

job_queue
id job_id
3  1
5  2
6  2

Queue a job by inserting it.

insert into job_queue (job_id) values (?)

Finish a job by deleting one entry. It's not necessary to first check. If a row is deleted, you finished a job.

delete from jobs_queue
where id = (
  select id from jobs_queue
  where job_id = ?
  limit 1
)

We can combine the two. Flags and a job_queue table. We can store more information like who is doing the work, when it was queued, and so on.

create table job_queue (
   id bigserial primary key
   job_id bigint not null references jobs(id) on delete cascade,
   status text not null default 'queued',
   user_id bigint references users(id) on delete set null,
   created_at timestamp not null default current_timestamp,
   updated_at timestamp not null default current_timestamp
);

Queue a job.

insert into job_queue (job_id) values (?)

Start a job. Again, no check necessary. Instead, check if a row was updated.

update job_queue
set status = 'in progress', user_id = ?, updated_at = current_timestamp
where id = (
  select id
  from job_queue
  where status = 'queued'
  limit 1
)
returning id

Finish a job. Use the ID returned from the update if you have it.

update job_queue
set status = 'done', updated_at = current_timestamp
where id = ?

Or find a queued job you have in progress and update that.

update job_queue
set status = 'done', updated_at = current_timestamp
where id = (
  select id
  from job_queue
  where user_id = ?
    and job_id = ?
    and status = 'in progress'
  limit 1
)


问:
_audio_microfrontend_op.so not found
My Python version is 3.7
(Windows10, 64bit, tensorflow 2.0)

I implemented a program to detect eye-blink using opencv.
Press F5 in the pycham to perform normal operation.
I made exe file using pyinstaller.
However, when I run with the generated exe file, an error occurs.

**...............
tensorflow.python.framework.errors_impl.NotFoundError: C:\User\User Name\AppData\Local\Temp\_MEI401122\tensorflow\lite\experimental\microfrontend\python\ops\_audio_microfrontend_op.so not found

[40068] Failed to execute script test**

I've tried numerous ways and found a solution, but it's not working out.

Path on the error message is not on my PC.(Folder _MEI401122 does not exist)

On my PC, the _audio_microfrontend_op.so file is in the path of the picture below.

I have no idea.  Please help me.

I add my source code and error content.

My project folder path is as follows.

Path: C:\Users\User Name\Downloads\eye_blink_detector-master

[My Error contents image]

[My source code]

```<code># -*- coding: utf-8 -*-
import cv2, dlib
import numpy as np
from imutils import face_utils
from keras.models import load_model
from time import localtime, strftime
from datetime import datetime
import time
from tkinter import *
import tkinter.messagebox

root = Tk()

WELCOME_MSG = '''Welcome to this event.'''
WELCOME_DURATION = 2000

def welcome():
    top = tkinter.Toplevel()
    top.title('Welcome')
    Message(top, text="카운트", padx=20, pady=20).pack()
    top.after(WELCOME_DURATION, top.destroy)

IMG_SIZE = (34, 26)

#root.mainloop()

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

model = load_model('models/2018_12_17_22_58_35.h5')
model.summary()

count = 0
count_eye_open = 0

f = open("d:/새파일.txt", 'a')

def crop_eye(img, eye_points):
  x1, y1 = np.amin(eye_points, axis=0)
  x2, y2 = np.amax(eye_points, axis=0)
  cx, cy = (x1 + x2) / 2, (y1 + y2) / 2

  w = (x2 - x1) * 1.2
  h = w * IMG_SIZE[1] / IMG_SIZE[0]

  margin_x, margin_y = w / 2, h / 2

  min_x, min_y = int(cx - margin_x), int(cy - margin_y)
  max_x, max_y = int(cx + margin_x), int(cy + margin_y)

  eye_rect = np.rint([min_x, min_y, max_x, max_y]).astype(np.int)

  eye_img = gray[eye_rect[1]:eye_rect[3], eye_rect[0]:eye_rect[2]]

  return eye_img, eye_rect

# main

cap = cv2.VideoCapture(0) #'videos/2.mp4')

while cap.isOpened():
  ret, img_ori = cap.read()

  if not ret:
    break

#윈도우 사이즈
  img_ori = cv2.resize(img_ori, dsize=(0, 0), fx=1.0, fy=1.0)

  img = img_ori.copy()
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  faces = detector(gray)

  dt = datetime.now()

  for face in faces:

    shapes = predictor(gray, face)
    shapes = face_utils.shape_to_np(shapes)

    eye_img_l, eye_rect_l = crop_eye(gray, eye_points=shapes[36:41]) #l_eye_poits = [36, 37, 38, 39, 40, 41] 원소스: [36,42]
    eye_img_r, eye_rect_r = crop_eye(gray, eye_points=shapes[42:47]) #r_eye_points = [42, 43, 44, 45, 46, 47] 원소스: [42:48]

    eye_img_l = cv2.resize(eye_img_l, dsize=IMG_SIZE)
    eye_img_r = cv2.resize(eye_img_r, dsize=IMG_SIZE)
    eye_img_r = cv2.flip(eye_img_r, flipCode=1)

    cv2.imshow('l', eye_img_l)
    cv2.imshow('r', eye_img_r)

    eye_input_l = eye_img_l.copy().reshape((1, IMG_SIZE[1], IMG_SIZE[0], 1)).astype(np.float32) / 255.
    eye_input_r = eye_img_r.copy().reshape((1, IMG_SIZE[1], IMG_SIZE[0], 1)).astype(np.float32) / 255.

    pred_l = model.predict(eye_input_l)
    pred_r = model.predict(eye_input_r)

    # visualize
    state_l = '%.2f' if pred_l > 0.1 else '-%.1f'
    state_r = '%.2f' if pred_r > 0.1 else '-%.1f'

    state_l = state_l % pred_l
    state_r = state_r % pred_r

    # Blink Count
    if pred_l <= 0.1 and pred_r <= 0.1:
        count_eye_open += 1
        print("blinking, "+ str(dt.strftime('%Y-%m-%d %H:%M:%S.%f')))

    cv2.rectangle(img, pt1=tuple(eye_rect_l[0:2]), pt2=tuple(eye_rect_l[2:4]), color=(255,255,255), thickness=2)
    cv2.rectangle(img, pt1=tuple(eye_rect_r[0:2]), pt2=tuple(eye_rect_r[2:4]), color=(255,255,255), thickness=2)

    cv2.putText(img, state_l, tuple(eye_rect_l[0:2]), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
    cv2.putText(img, state_r, tuple(eye_rect_r[0:2]), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)

    cv2.putText(img, "eye blink: " + str(count_eye_open), (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
    cv2.putText(img, "Time: " + str(strftime("%S", localtime())), (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))

    if str(strftime("%S", localtime())) == "00":
        count += 1
        if count == 1 and count_eye_open > 0:
            print("Transfer Data...:" + str(count_eye_open))
            f.write("Transfer Data...:" + str(count_eye_open) + "\n")
            count_eye_open = 0
            count = 0
    else:
      count = 0

    time.sleep(0.12)

  cv2.imshow('result', img)
  if cv2.waitKey(1) == ord('q'):
    f.close()
    break
</code>```

答:
For someone who is still confused in spec which is in directory, where is your original filename.py, add this in datas = []

```<code>(os.path.join(os.path.dirname(importlib.import_module('tensorflow').__file__),
                              "lite/experimental/microfrontend/python/ops/_audio_microfrontend_op.so"),
                 "tensorflow/lite/experimental/microfrontend/python/ops/")
</code>```

Then put there import

```<code>import os
import importlib
</code>```

Then run this to compile by the specs you changed.

```<code>pyinstaller filename.spec
</code>```

Title: _audio_microfrontend_op.so not found

Body:
My Python version is 3.7
(Windows10, 64bit, tensorflow 2.0)

I implemented a program to detect eye-blink using opencv.
Press F5 in the pycham to perform normal operation.
I made exe file using pyinstaller.
However, when I run with the generated exe file, an error occurs.

**...............
tensorflow.python.framework.errors_impl.NotFoundError: C:\User\User Name\AppData\Local\Temp\_MEI401122\tensorflow\lite\experimental\microfrontend\python\ops\_audio_microfrontend_op.so not found

[40068] Failed to execute script test**

I've tried numerous ways and found a solution, but it's not working out.

Path on the error message is not on my PC.(Folder _MEI401122 does not exist)

On my PC, the _audio_microfrontend_op.so file is in the path of the picture below.

I have no idea.  Please help me.

I add my source code and error content.

My project folder path is as follows.

Path: C:\Users\User Name\Downloads\eye_blink_detector-master

[My Error contents image]

[My source code]

# -*- coding: utf-8 -*-
import cv2, dlib
import numpy as np
from imutils import face_utils
from keras.models import load_model
from time import localtime, strftime
from datetime import datetime
import time
from tkinter import *
import tkinter.messagebox

root = Tk()

WELCOME_MSG = '''Welcome to this event.'''
WELCOME_DURATION = 2000

def welcome():
    top = tkinter.Toplevel()
    top.title('Welcome')
    Message(top, text="카운트", padx=20, pady=20).pack()
    top.after(WELCOME_DURATION, top.destroy)

IMG_SIZE = (34, 26)

#root.mainloop()

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

model = load_model('models/2018_12_17_22_58_35.h5')
model.summary()

count = 0
count_eye_open = 0

f = open("d:/새파일.txt", 'a')

def crop_eye(img, eye_points):
  x1, y1 = np.amin(eye_points, axis=0)
  x2, y2 = np.amax(eye_points, axis=0)
  cx, cy = (x1 + x2) / 2, (y1 + y2) / 2

  w = (x2 - x1) * 1.2
  h = w * IMG_SIZE[1] / IMG_SIZE[0]

  margin_x, margin_y = w / 2, h / 2

  min_x, min_y = int(cx - margin_x), int(cy - margin_y)
  max_x, max_y = int(cx + margin_x), int(cy + margin_y)

  eye_rect = np.rint([min_x, min_y, max_x, max_y]).astype(np.int)

  eye_img = gray[eye_rect[1]:eye_rect[3], eye_rect[0]:eye_rect[2]]

  return eye_img, eye_rect

# main

cap = cv2.VideoCapture(0) #'videos/2.mp4')

while cap.isOpened():
  ret, img_ori = cap.read()

  if not ret:
    break

#윈도우 사이즈
  img_ori = cv2.resize(img_ori, dsize=(0, 0), fx=1.0, fy=1.0)

  img = img_ori.copy()
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  faces = detector(gray)

  dt = datetime.now()

  for face in faces:

    shapes = predictor(gray, face)
    shapes = face_utils.shape_to_np(shapes)

    eye_img_l, eye_rect_l = crop_eye(gray, eye_points=shapes[36:41]) #l_eye_poits = [36, 37, 38, 39, 40, 41] 원소스: [36,42]
    eye_img_r, eye_rect_r = crop_eye(gray, eye_points=shapes[42:47]) #r_eye_points = [42, 43, 44, 45, 46, 47] 원소스: [42:48]

    eye_img_l = cv2.resize(eye_img_l, dsize=IMG_SIZE)
    eye_img_r = cv2.resize(eye_img_r, dsize=IMG_SIZE)
    eye_img_r = cv2.flip(eye_img_r, flipCode=1)

    cv2.imshow('l', eye_img_l)
    cv2.imshow('r', eye_img_r)

    eye_input_l = eye_img_l.copy().reshape((1, IMG_SIZE[1], IMG_SIZE[0], 1)).astype(np.float32) / 255.
    eye_input_r = eye_img_r.copy().reshape((1, IMG_SIZE[1], IMG_SIZE[0], 1)).astype(np.float32) / 255.

    pred_l = model.predict(eye_input_l)
    pred_r = model.predict(eye_input_r)

    # visualize
    state_l = '%.2f' if pred_l > 0.1 else '-%.1f'
    state_r = '%.2f' if pred_r > 0.1 else '-%.1f'

    state_l = state_l % pred_l
    state_r = state_r % pred_r

    # Blink Count
    if pred_l <= 0.1 and pred_r <= 0.1:
        count_eye_open += 1
        print("blinking, "+ str(dt.strftime('%Y-%m-%d %H:%M:%S.%f')))

    cv2.rectangle(img, pt1=tuple(eye_rect_l[0:2]), pt2=tuple(eye_rect_l[2:4]), color=(255,255,255), thickness=2)
    cv2.rectangle(img, pt1=tuple(eye_rect_r[0:2]), pt2=tuple(eye_rect_r[2:4]), color=(255,255,255), thickness=2)

    cv2.putText(img, state_l, tuple(eye_rect_l[0:2]), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
    cv2.putText(img, state_r, tuple(eye_rect_r[0:2]), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)

    cv2.putText(img, "eye blink: " + str(count_eye_open), (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
    cv2.putText(img, "Time: " + str(strftime("%S", localtime())), (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))

    if str(strftime("%S", localtime())) == "00":
        count += 1
        if count == 1 and count_eye_open > 0:
            print("Transfer Data...:" + str(count_eye_open))
            f.write("Transfer Data...:" + str(count_eye_open) + "\n")
            count_eye_open = 0
            count = 0
    else:
      count = 0

    time.sleep(0.12)

  cv2.imshow('result', img)
  if cv2.waitKey(1) == ord('q'):
    f.close()
    break

Body:
For someone who is still confused in spec which is in directory, where is your original filename.py, add this in datas = []

(os.path.join(os.path.dirname(importlib.import_module('tensorflow').__file__),
                              "lite/experimental/microfrontend/python/ops/_audio_microfrontend_op.so"),
                 "tensorflow/lite/experimental/microfrontend/python/ops/")

Then put there import

import os
import importlib

Then run this to compile by the specs you changed.

pyinstaller filename.spec


问:
Call to undefined function Illuminate\Encryption\openssl_decrypt()
I am using xampp and windows along with laravel, everything was working fine, but when I finished work and turned of xampp and try to open my work today morning, this is what I get:

```<code>FatalThrowableError in Encrypter.php line 100:
Fatal error: Call to undefined function Illuminate\Encryption\openssl_decrypt()
</code>```

Encrypter.php is a standard laravel file and I have not even touched it. My extension is turned on.

extension=php_openssl.dll

What might be wrong?

答: Just edit php.ini file and uncomment by removing ";" before this line --extension=openssl. in php.ini file. and it will start working properly.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am using xampp and windows along with laravel, everything was working fine, but when I finished work and turned of xampp and try to open my work today morning, this is what I get:

FatalThrowableError in Encrypter.php line 100:
Fatal error: Call to undefined function Illuminate\Encryption\openssl_decrypt()

Encrypter.php is a standard laravel file and I have not even touched it. My extension is turned on.

extension=php_openssl.dll

What might be wrong?


问:
Access VBA loop to export Excel files
I have some code that I copied and modified from Export Query in VBA loop to select data based on String Value

The code works although the problem is that when it runs it creates a query in the database which is then deleted at the end. If the code breaks half way through, this query is still in the database. So when the code is run again it gives an error message saying it can't create the query as it already exists.

The query that is created within the database is named "Select * from SalesData"

The objective is that I have a query called "SalesData" which includes sales information for a number of countries. I want to export all the data for each country into an Excel file in a loop without creating any additional Access objects. Is it possible to just filter the existing query within the VBA without creating the temporary object?

Can anyone suggest any modifications to the below code to achieve this?

```<code>Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()

Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")

Dim v As String
Dim strQry As String
Dim qdfTemp As DAO.QueryDef
Dim strQDF As String

strQDF = "select * from SalesData"

Do While Not rs1.EOF
    v = rs1.Fields(0).Value

    strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"

    Set qdfTemp = CurrentDb.CreateQueryDef(strQDF, strQry)
    qdfTemp.Close
    Set qdfTemp = Nothing

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
    strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True

    CurrentDb.QueryDefs.Delete strQDF
    rs1.MoveNext
Loop

rs1.Close

 End Sub
</code>```

答:
As far as I'm aware, it would not be possible to use the TransferSpreadsheet method to extract a parameterised version of your SalesData query without either modifying the SQL of the SalesData query itself or using an additional query with selection criteria applied to the data returned by SalesData.

However, you needn't delete & recreate such query with every iteration of the loop - instead, simply modify the SQL property of the query, e.g.:

```<code>Sub test()
    Dim qry As String: qry = "salesdata_temp"
    Dim sql As String: sql = "select * from salesdata where country = '{0}'"
    Dim out As String: out = "C:\Users\me\Desktop\VBA_TEST\"
    Dim dbs As DAO.Database
    Dim qdf As DAO.QueryDef

    On Error Resume Next
    DoCmd.DeleteObject acQuery, qry
    On Error GoTo error_handler

    Set dbs = CurrentDb
    Set qdf = dbs.CreateQueryDef(qry, sql)

    With dbs.OpenRecordset("select distinct country from salesdata")
         If Not .EOF Then
            .MoveFirst
            Do Until .EOF
                qdf.sql = Replace(sql, "{0}", !country)
                DoCmd.TransferSpreadsheet acExport, , qry, out & !country & ".xlsx", True
                .MoveNext
            Loop
         End If
         .Close
    End With

exit_sub:
    On Error Resume Next
    DoCmd.DeleteObject acQuery, qry
    Exit Sub

error_handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation + vbOKOnly, "Error"
    Resume exit_sub
End Sub
</code>```

Title: Access VBA loop to export Excel files

Body:
I have some code that I copied and modified from Export Query in VBA loop to select data based on String Value

The code works although the problem is that when it runs it creates a query in the database which is then deleted at the end. If the code breaks half way through, this query is still in the database. So when the code is run again it gives an error message saying it can't create the query as it already exists.

The query that is created within the database is named "Select * from SalesData"

The objective is that I have a query called "SalesData" which includes sales information for a number of countries. I want to export all the data for each country into an Excel file in a loop without creating any additional Access objects. Is it possible to just filter the existing query within the VBA without creating the temporary object?

Can anyone suggest any modifications to the below code to achieve this?

Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()

Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")

Dim v As String
Dim strQry As String
Dim qdfTemp As DAO.QueryDef
Dim strQDF As String

strQDF = "select * from SalesData"

Do While Not rs1.EOF
    v = rs1.Fields(0).Value

    strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"

    Set qdfTemp = CurrentDb.CreateQueryDef(strQDF, strQry)
    qdfTemp.Close
    Set qdfTemp = Nothing

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
    strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True

    CurrentDb.QueryDefs.Delete strQDF
    rs1.MoveNext
Loop

rs1.Close

 End Sub

Body:
As far as I'm aware, it would not be possible to use the TransferSpreadsheet method to extract a parameterised version of your SalesData query without either modifying the SQL of the SalesData query itself or using an additional query with selection criteria applied to the data returned by SalesData.

However, you needn't delete & recreate such query with every iteration of the loop - instead, simply modify the SQL property of the query, e.g.:

Sub test()
    Dim qry As String: qry = "salesdata_temp"
    Dim sql As String: sql = "select * from salesdata where country = '{0}'"
    Dim out As String: out = "C:\Users\me\Desktop\VBA_TEST\"
    Dim dbs As DAO.Database
    Dim qdf As DAO.QueryDef

    On Error Resume Next
    DoCmd.DeleteObject acQuery, qry
    On Error GoTo error_handler

    Set dbs = CurrentDb
    Set qdf = dbs.CreateQueryDef(qry, sql)

    With dbs.OpenRecordset("select distinct country from salesdata")
         If Not .EOF Then
            .MoveFirst
            Do Until .EOF
                qdf.sql = Replace(sql, "{0}", !country)
                DoCmd.TransferSpreadsheet acExport, , qry, out & !country & ".xlsx", True
                .MoveNext
            Loop
         End If
         .Close
    End With

exit_sub:
    On Error Resume Next
    DoCmd.DeleteObject acQuery, qry
    Exit Sub

error_handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation + vbOKOnly, "Error"
    Resume exit_sub
End Sub


问:
ruby 1.8.7 gems are installed but-- they aren't?
I have a rails 2.3.5 app and if I try to do rake db:migrate, I get:

```<code>Missing these required gems:
  authlogic  ~> 2.1.3
  will_paginate  ~> 2.3.11
  paperclip  ~> 2.3.1.1
  mimetype-fu  ~> 0.1.2
  nokogiri

You're running:
  ruby 1.8.7.302 at /usr/local/bin/ruby18
  rubygems 1.8.3 at /home/p/patrick/.gem/ruby/1.8, /usr/local/lib/ruby/gems/1.8

Run `rake gems:install` to install the missing gems.
</code>```

yet if I do:

```<code>rake gems
</code>```

I see:

```<code>    [F] authlogic ~> 2.1.3
    [F] will_paginate ~> 2.3.11
    [F] paperclip ~> 2.3.1.1
    [F] mimetype-fu ~> 0.1.2
    [R] rubyzip ~> 0.9.1
    [F] nokogiri

    I = Installed
    F = Frozen
    R = Framework (loaded before rails starts)
</code>```

My config/environment.rb has in it:

```<code>config.gem 'authlogic',     :version => '~> 2.1.3'
config.gem 'will_paginate', :version => '~> 2.3.11',  :source => 'http://gemcutt
config.gem 'paperclip',     :version => '~> 2.3.1.1'
config.gem 'mimetype-fu',   :lib => 'mimetype_fu',    :version => '~> 0.1.2'
config.gem 'rubyzip',       :lib => 'zip/ziprequire', :version => '~> 0.9.1'
config.gem 'nokogiri'
</code>```

答:
```<code>config.gem 'authlogic',     :version => '>= 2.1.3'
config.gem 'will_paginate', :version => '>= 2.3.11',  :source => 'http://gemcutt
config.gem 'paperclip',     :version => '>= 2.3.1.1'
config.gem 'mimetype-fu',   :lib => 'mimetype_fu',    :version => '>= 0.1.2'
config.gem 'rubyzip',       :lib => 'zip/ziprequire', :version => '>= 0.9.1'
config.gem 'nokogiri'
</code>```

I don't know what ~> means but this version should work properly

Body:
I have a rails 2.3.5 app and if I try to do rake db:migrate, I get:

Missing these required gems:
  authlogic  ~> 2.1.3
  will_paginate  ~> 2.3.11
  paperclip  ~> 2.3.1.1
  mimetype-fu  ~> 0.1.2
  nokogiri

You're running:
  ruby 1.8.7.302 at /usr/local/bin/ruby18
  rubygems 1.8.3 at /home/p/patrick/.gem/ruby/1.8, /usr/local/lib/ruby/gems/1.8

Run `rake gems:install` to install the missing gems.

yet if I do:

rake gems

I see:

    [F] authlogic ~> 2.1.3
    [F] will_paginate ~> 2.3.11
    [F] paperclip ~> 2.3.1.1
    [F] mimetype-fu ~> 0.1.2
    [R] rubyzip ~> 0.9.1
    [F] nokogiri

    I = Installed
    F = Frozen
    R = Framework (loaded before rails starts)

My config/environment.rb has in it:

config.gem 'authlogic',     :version => '~> 2.1.3'
config.gem 'will_paginate', :version => '~> 2.3.11',  :source => 'http://gemcutt
config.gem 'paperclip',     :version => '~> 2.3.1.1'
config.gem 'mimetype-fu',   :lib => 'mimetype_fu',    :version => '~> 0.1.2'
config.gem 'rubyzip',       :lib => 'zip/ziprequire', :version => '~> 0.9.1'
config.gem 'nokogiri'

Body:
config.gem 'authlogic',     :version => '>= 2.1.3'
config.gem 'will_paginate', :version => '>= 2.3.11',  :source => 'http://gemcutt
config.gem 'paperclip',     :version => '>= 2.3.1.1'
config.gem 'mimetype-fu',   :lib => 'mimetype_fu',    :version => '>= 0.1.2'
config.gem 'rubyzip',       :lib => 'zip/ziprequire', :version => '>= 0.9.1'
config.gem 'nokogiri'

I don't know what ~> means but this version should work properly


答:
The issue is that B::B1Method() is a non-static member function in B and, therefore, it needs to be called on an instance of B.

If the implementation of B1Method()  doesn't use any non-static data member of B and it doesn't call any other non-static member function of B, then simply declaring it as static will work with your current implementation of BIncorrectCall() as you will no longer need to call B1Method() on an instance of B:

```<code>class B {
  public:
    static void B1Method() { } // static now
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); } // no change
};
</code>```

Otherwise, you have to keep an object of type B whenever you want to call B1::B1Method().

Title: C++ invalid function type casting

Body:
The issue is that B::B1Method() is a non-static member function in B and, therefore, it needs to be called on an instance of B.

If the implementation of B1Method()  doesn't use any non-static data member of B and it doesn't call any other non-static member function of B, then simply declaring it as static will work with your current implementation of BIncorrectCall() as you will no longer need to call B1Method() on an instance of B:

class B {
  public:
    static void B1Method() { } // static now
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); } // no change
};

Otherwise, you have to keep an object of type B whenever you want to call B1::B1Method().


问:
Show the Progress Percentage of an operation running inside a FOR-loop in Label.Text
I have the following C# Code:

```<code>for (int i = 0; i < dgItems.Rows.Count - 1; i++)
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO TBL_OrderQty (SipStyle,SipColor,SipSize,[SipQty(-%5)],SipQty,[SipQty(+%5)]) VALUES('" + dgItems.Rows[i].Cells[0].Value + "','" + dgItems.Rows[i].Cells[1].Value + "','" + dgItems.Rows[i].Cells[2].Value + "','" + dgItems.Rows[i].Cells[3].Value + "','" + dgItems.Rows[i].Cells[4].Value + "','" + dgItems.Rows[i].Cells[5].Value + "')", con);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        progressBar1.Value = i;
                        LB_ProgText.Text = "Progress :%" + (i / 100) * dgItems.Rows.Count;
                        LB_ProgText.Invalidate();
                        LB_ProgText.Update();
                    }
</code>```

I'm trying to show the progress percentage of the whole operation, the progress bar is working just fine but I couldn't get the percentage right; can you please help me.

答:
First of all, this code is vulnerable to SQL injections. Please use Parametized Queries.

Secondly, this should not be a question. If it takes long enough to consider progress reporting, soemthing is fundamentally flawed with the process. There is a limit to how much data a human can process. And retreiving more then that data from the DB to do filtering in the UI, is a classical beginners mistake. Right next to SQL Injection vulnerability. Do as much sorting, filtering and pagination in the query as possible. If you are on mobile, consider a Distributed Design.

As for the actuall question:

You can only report progress between distinct lines of code. Some modern classes do support Events for progress reporting, but the DB classes are about 2 decades to old for that. You basically got these options:

find a class taht supports this

make a loop retreiving each row seperately. However this is a no-go in itself. Always retreive as much in 1 go as possible

Use a enumerator approach to retrieve the data. However this will usually not give you a count of the total amount until you reached the end.

realize this is way more trouble then it is worth and learn to live without it. The Windows Update people had to learn to live without that level of reporting and those guys had resources.

Body:
I have the following C# Code:

for (int i = 0; i < dgItems.Rows.Count - 1; i++)
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO TBL_OrderQty (SipStyle,SipColor,SipSize,[SipQty(-%5)],SipQty,[SipQty(+%5)]) VALUES('" + dgItems.Rows[i].Cells[0].Value + "','" + dgItems.Rows[i].Cells[1].Value + "','" + dgItems.Rows[i].Cells[2].Value + "','" + dgItems.Rows[i].Cells[3].Value + "','" + dgItems.Rows[i].Cells[4].Value + "','" + dgItems.Rows[i].Cells[5].Value + "')", con);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        progressBar1.Value = i;
                        LB_ProgText.Text = "Progress :%" + (i / 100) * dgItems.Rows.Count;
                        LB_ProgText.Invalidate();
                        LB_ProgText.Update();
                    }

I'm trying to show the progress percentage of the whole operation, the progress bar is working just fine but I couldn't get the percentage right; can you please help me.


问:
Github Pages / Github automated data push policy
For the sake of convenience, I've hosted a page in https://pages.github.com/ (until it grows in complexity), at this stage of the project, I anticipated the need to update some data hosted (50kb approx.) once every 2 days approx, but I have just noticed I will have to update the data many times during the day (once every 1-2 hours). I am fully aware Github pages was not built with such purpose in mind.

I've gone through the GitHub terms of service, the API limits and the acceptable use policy:

The API is only intended for searches, pulls, etc. not for pushes

Even if I want to "push", which is different, it looks like my use would be inside what they consider reasonable (at least for the API).

There is nothing in the general terms of service that would make that use look like a breach. They don't even mention the word "push".

The acceptable use policy establishes limits to bandwidth (which should not be a problem here).

The acceptable use policy bans "inauthentic interactions, such as fake accounts and automated inauthentic activity". The activity would be authentic, but obviously, automated.

Would it be OK to automatically push data 12-24 times per day? Could it represent a breach?

答:
This is a question you need to ask GitHub themselves, but here are some things you should consider:

The purpose of GitHub Pages is to host a personal website or blog or a site for your open-source project.  If the purpose of your site is something else, you should consider hosting it elsewhere.

If you need your page to be built within a certain timeframe or have a certain SLA, then you should host it somewhere that can provide that, since GitHub Pages doesn't make any guarantees about that.

GitHub Pages isn't intended for commercial use, such as selling a product or service to someone, although commercially sponsored open-source projects are fine.

If you meet those criteria, then things will probably be fine, but if you want to be certain, you should ask GitHub, such as on its community forums.


问:
Where to put Expanded inside Form Widget
I have this login form and when I press the second RaisedButton the keyboard comes up and the yellow/black banner of the problem in display widgets appears.

I want to know where exactly shall I put Expanded widget in this code to avoid this error:

```<code>body: Container(
    padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
    child: Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          SizedBox(height: 20.0),
          TextFormField(),
          SizedBox(height: 20.0),
          TextFormField(),
          SizedBox(height: 20.0),
          RaisedButton(),
          SizedBox(height: 12.0),
          Text(''),
          RaisedButton(),
          ),
        ],
      ),
    ),
  ),
</code>```

答:
You can fix this by adding resizeToAvoidBottomInset: false to your root Scaffold.

Example below:

```<code>Scaffold(
      resizeToAvoidBottomInset: false,
    );
</code>```

Body:
I have this login form and when I press the second RaisedButton the keyboard comes up and the yellow/black banner of the problem in display widgets appears.

I want to know where exactly shall I put Expanded widget in this code to avoid this error:

body: Container(
    padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
    child: Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          SizedBox(height: 20.0),
          TextFormField(),
          SizedBox(height: 20.0),
          TextFormField(),
          SizedBox(height: 20.0),
          RaisedButton(),
          SizedBox(height: 12.0),
          Text(''),
          RaisedButton(),
          ),
        ],
      ),
    ),
  ),

Body:
You can fix this by adding resizeToAvoidBottomInset: false to your root Scaffold.

Example below:

Scaffold(
      resizeToAvoidBottomInset: false,
    );


问:
Src unknown after push
Hi i have problem with pushing item from one array to another. It's system of equipment in my game. The problem is that image of item has unknown src after being pushed to another array.

angular ts

```<code>  itemy = [{id: 0, name: "sword", url:'../../../../assets/img/sword.png'}, {id: 1, name: "sword2", url:"../../../../assets/img/sword2.png"}];
  images = JSON.parse(localStorage.getItem('images')) || [];
  add (){
    let index=Math.round(Math.random())
    this.images.push(this.itemy[index]);
    localStorage.setItem('images', JSON.stringify(this.images));
  }

  eq = JSON.parse(localStorage.getItem('eq')) || [];
  select() {
    this.eq.push(this.images);
    this.eq.length = 1;
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }
  unselect() {
    this.eq.pop();
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }
}
</code>```

HTML

```<code><div class="eq">
  <div id="contentInside2" *ngFor="let image of eq">
    <img class="item" src={{image.url}}  (click)="unselect()"/> </div>
 </div>
  <button (click)="add()">Add</button>
<div id="content">
    <div id="contentInside" *ngFor="let image of images">
      <img class="item" src={{image.url}} (click)="select()"/>
    </div>
  </div>
</code>```

Here is how it looks now

答:
If you want to only select clicked image.

Change your template to :-

```<code><div class="eq">
  <div id="contentInside2" *ngFor="let image of eq; let i=index">
    <img class="item" src={{image.url}}  (click)="unselect(i, image)"/> </div>
 </div>
  <button (click)="add()">Add</button>
<div id="content">
    <div id="contentInside" *ngFor="let image of images; let i=index">
      <img class="item" src={{image.url}} (click)="select(i, image)"/>
    </div>
  </div>
</code>```

then typescript method to :-

```<code>select(index, image) {
    if(this.eq.length === 1) {
       return;
    }
    this.eq.push(image);
    this.images.splice(index, 1);
    localStorage.setItem('images', JSON.stringify(this.images));
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }

unselect(index, image) {
    this.eq.splice(index, 1);
    this.images.push(image);
    localStorage.setItem('images', JSON.stringify(this.images));
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }
</code>```

Title: Src unknown after push

Body:
Hi i have problem with pushing item from one array to another. It's system of equipment in my game. The problem is that image of item has unknown src after being pushed to another array.

angular ts

  itemy = [{id: 0, name: "sword", url:'../../../../assets/img/sword.png'}, {id: 1, name: "sword2", url:"../../../../assets/img/sword2.png"}];
  images = JSON.parse(localStorage.getItem('images')) || [];
  add (){
    let index=Math.round(Math.random())
    this.images.push(this.itemy[index]);
    localStorage.setItem('images', JSON.stringify(this.images));
  }

  eq = JSON.parse(localStorage.getItem('eq')) || [];
  select() {
    this.eq.push(this.images);
    this.eq.length = 1;
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }
  unselect() {
    this.eq.pop();
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }
}

HTML

  <button (click)="add()">Add</button>

Here is how it looks now

Body:
If you want to only select clicked image.

Change your template to :-

<div class="eq">
  <div id="contentInside2" *ngFor="let image of eq; let i=index">
    <img class="item" src={{image.url}}  (click)="unselect(i, image)"/> </div>
 </div>
  <button (click)="add()">Add</button>
<div id="content">
    <div id="contentInside" *ngFor="let image of images; let i=index">
      <img class="item" src={{image.url}} (click)="select(i, image)"/>
    </div>
  </div>

then typescript method to :-

select(index, image) {
    if(this.eq.length === 1) {
       return;
    }
    this.eq.push(image);
    this.images.splice(index, 1);
    localStorage.setItem('images', JSON.stringify(this.images));
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }

unselect(index, image) {
    this.eq.splice(index, 1);
    this.images.push(image);
    localStorage.setItem('images', JSON.stringify(this.images));
    localStorage.setItem('eq', JSON.stringify(this.eq));
  }


问:
Whats possible in a for loop
So today I went to an interview and one of the questions was the following (C# context).

```<code>//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}
</code>```

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

答: According to my exp and research, this type of  'condition construct' is very commonly seen in image processing, say(really, say) you need to compare pixels between two images in (say, again) opposite directions.  Or even traverse neighbors in opp directions, too.   Another example, under this type of 'condition construct', when you need to convert a 32-bit bmp to 24-bit or vice versa. (only that the increment would be bit diff like i=i+4, j=j+3).</p>

Title: Whats possible in a for loop

Body:
So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?


问:
How to transform a file .py to .exe
I read the comments here (and others) ,
but I still cannot solve my problem.

I have already created the file .exe.
But the program is not behaving as it should.
The basic idea of the program is to read a file (.csv) and then it should give two output other .csv and a .docx. My Python program does that. But the .exe doesn't.
I have the csv where the .exe is, but still is not working :/ the .exe executes but doesn't give me the desired output. Any ideas?
I have tried a lot of different things.

This is one part of the code that doesn't seem to be working in the .exe:

```<code>with pd.ExcelWriter('sales_mejorado.xlsx') as writer:

df_sales.to_excel(writer, sheet_name="sales.xlsx")
</code>```

I imported these libraries:

```<code>import numpy as np
import pandas as pd
import re
from docx import Document
from docx.shared import Inches
</code>```

Maybe this part it in't working...
(when I call the csv files)

```<code>df_sales = pd.read_csv('./Sales.csv', sep=',', encoding='latin-1')
</code>```

Thanks in advance. I really need help in this.
Edit: I try too the auto-py-to-exe, and it didn't help :(

答:
I suggest using:

```<code>auto-py-to-exe
</code>```

It has one directory option which will put all dependencies in one folder :)

Title: How to transform a file .py to .exe

Body:
I read the comments here (and others) ,
but I still cannot solve my problem.

I have already created the file .exe.
But the program is not behaving as it should.
The basic idea of the program is to read a file (.csv) and then it should give two output other .csv and a .docx. My Python program does that. But the .exe doesn't.
I have the csv where the .exe is, but still is not working :/ the .exe executes but doesn't give me the desired output. Any ideas?
I have tried a lot of different things.

This is one part of the code that doesn't seem to be working in the .exe:

with pd.ExcelWriter('sales_mejorado.xlsx') as writer:

df_sales.to_excel(writer, sheet_name="sales.xlsx")

I imported these libraries:

import numpy as np
import pandas as pd
import re
from docx import Document
from docx.shared import Inches

Maybe this part it in't working...
(when I call the csv files)

df_sales = pd.read_csv('./Sales.csv', sep=',', encoding='latin-1')

Thanks in advance. I really need help in this.
Edit: I try too the auto-py-to-exe, and it didn't help :(

Body:
I suggest using:

auto-py-to-exe

It has one directory option which will put all dependencies in one folder :)


问:
Exclude `unknown[]` from a union with a tuple?
I don't think this is possible, but I wanted to ask here before raising an issue on github.

I have a type that looks like this:

type X = [string, number] | unknown[]
```

<p>I want to extract the <code>[string, number]</code> part. Is this possible? This doesn't work:</p>

<pre class="lang-js prettyprint-override"><code>type Y = Exclude<X, unknown[]>
</code>```

With the above, Y is never. I understand why, because [string, number] extends unknown[], so by excluding it both sides of the union are "rejected". But are there any clever conditional types that can be used to get rid of unknown[]?

Note: I am not defining X myself, I'm trying to write a function signature where one of the intermediate types looks like [string, number] | unknown[]. So I can't just use [string, number] directly.

答:
From examples in docs

In an intersection everything absorbs unknown

We can create type that is for sure has nothing common with real types, e.g:

```<code>type Noop = { __noop: '__noop' };
</code>```

Then in conditional type we can check if intersection of array item extends our fake type and if yes - exclude it (as we know it must be unknown):

```<code>type ExcludeUnknown<T> = T extends Array<infer I>
  ? Noop extends (I & Noop) ? never : T
  : T;

type Y = ExcludeUnknown<X>; // [string, number]
</code>```

Playground

** Pay attention, this won't work with tuples containing {}, object or unknown (e.g. [string, number, {}])

Body:
I don't think this is possible, but I wanted to ask here before raising an issue on github.

I have a type that looks like this:

type X = [string, number] | unknown[]

I want to extract the [string, number] part. Is this possible? This doesn't work:

type Y = Exclude<X, unknown[]>

With the above, Y is never. I understand why, because [string, number] extends unknown[], so by excluding it both sides of the union are "rejected". But are there any clever conditional types that can be used to get rid of unknown[]?

Note: I am not defining X myself, I'm trying to write a function signature where one of the intermediate types looks like [string, number] | unknown[]. So I can't just use [string, number] directly.

Body:
From examples in docs

In an intersection everything absorbs unknown

We can create type that is for sure has nothing common with real types, e.g:

type Noop = { __noop: '__noop' };

Then in conditional type we can check if intersection of array item extends our fake type and if yes - exclude it (as we know it must be unknown):

type ExcludeUnknown<T> = T extends Array<infer I>
  ? Noop extends (I & Noop) ? never : T
  : T;

type Y = ExcludeUnknown<X>; // [string, number]

Playground

** Pay attention, this won't work with tuples containing {}, object or unknown (e.g. [string, number, {}])


问:
Bittrex REST API for Python, I want to create an order using API v3 https://api.bittrex.com/v3/orders
I need help to create orders using the bittrex version 3 REST API. I have the code below and I can't understand what is missing to work.
I can make other GET calls, but I cannot make this POST request.
I don't know how to deal with the passing of parameters.

Official documentation at https://bittrex.github.io/api/v3#tag-Orders.

```<code>def NewOrder(market, amount, price):
#print 'open sell v3', market
market = 'HEDG-BTC'#'BTC-'+market
uri = 'https://api.bittrex.com/v3/orders?'
params = {
    'marketSymbol': 'BTC-HEDG',#'HEDG-BTC', #market
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    'useAwards': True
}

timestamp = str(int(time.time()*1000))
Content = ""
contentHash = hashlib.sha512(Content.encode()).hexdigest()

Method = 'POST'
uri2 = buildURI(uri, params)
#uri2 = 'https://api.bittrex.com/v3/orders?direction=BUY&limit=0.00021&marketSymbol=HEDG-BTC&quantity=1.1&timeInForce=POST_ONLY_GOOD_TIL_CANCELLED&type=LIMIT&useAwards=True'
#print uri2
PreSign = timestamp + uri2 + Method + contentHash# + subaccountId
#print PreSign
Signature = hmac.new(apisecret, PreSign.encode(), hashlib.sha512).hexdigest()

headers = {
      'Api-Key' : apikey,
      'Api-Timestamp' : timestamp,
      'Api-Content-Hash': contentHash,
      'Api-Signature' : Signature
}

r = requests.post(uri2, data={}, headers=headers, timeout=11)
return json.loads(r.content)
</code>```

NewOrder('HEDG', 1.1, 0.00021)

And my error message:

```<code>{u'code': u'BAD_REQUEST', u'data': {u'invalidRequestParameter': u'direction'}, u'detail': u'Refer to the data field for specific field validation failures.'}
</code>```

答:
It seems from the documentation that this body is expected by the api as json data:

```<code>{
  "marketSymbol": "string",
  "direction": "string",
  "type": "string",
  "quantity": "number (double)",
  "ceiling": "number (double)",
  "limit": "number (double)",
  "timeInForce": "string",
  "clientOrderId": "string (uuid)",
  "useAwards": "boolean"
}
</code>```

and you are setting these values as url params that's the issue.

you need to do this:

```<code>uri = 'https://api.bittrex.com/v3/orders'

# NOTE >>>> please check that you provide all the required fields.
payload = {
    'marketSymbol': 'BTC-HEDG',#'HEDG-BTC', #market
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    'useAwards': True
}

# do rest of the stuffs as you are doing

# post payload as json data with the url given in doc
r = requests.post(uri, json=payload, headers=headers, timeout=11)
print(r.json())

</code>```

If you still have issues let us know. If it works then please mark answer as accepted.
Hope this helps.

Body:
I need help to create orders using the bittrex version 3 REST API. I have the code below and I can't understand what is missing to work.
I can make other GET calls, but I cannot make this POST request.
I don't know how to deal with the passing of parameters.

Official documentation at https://bittrex.github.io/api/v3#tag-Orders.

def NewOrder(market, amount, price):
#print 'open sell v3', market
market = 'HEDG-BTC'#'BTC-'+market
uri = 'https://api.bittrex.com/v3/orders?'
params = {
    'marketSymbol': 'BTC-HEDG',#'HEDG-BTC', #market
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    'useAwards': True
}

timestamp = str(int(time.time()*1000))
Content = ""
contentHash = hashlib.sha512(Content.encode()).hexdigest()

Method = 'POST'
uri2 = buildURI(uri, params)
#uri2 = 'https://api.bittrex.com/v3/orders?direction=BUY&limit=0.00021&marketSymbol=HEDG-BTC&quantity=1.1&timeInForce=POST_ONLY_GOOD_TIL_CANCELLED&type=LIMIT&useAwards=True'
#print uri2
PreSign = timestamp + uri2 + Method + contentHash# + subaccountId
#print PreSign
Signature = hmac.new(apisecret, PreSign.encode(), hashlib.sha512).hexdigest()

headers = {
      'Api-Key' : apikey,
      'Api-Timestamp' : timestamp,
      'Api-Content-Hash': contentHash,
      'Api-Signature' : Signature
}

r = requests.post(uri2, data={}, headers=headers, timeout=11)
return json.loads(r.content)

NewOrder('HEDG', 1.1, 0.00021)

And my error message:

{u'code': u'BAD_REQUEST', u'data': {u'invalidRequestParameter': u'direction'}, u'detail': u'Refer to the data field for specific field validation failures.'}

Body:
It seems from the documentation that this body is expected by the api as json data:

{
  "marketSymbol": "string",
  "direction": "string",
  "type": "string",
  "quantity": "number (double)",
  "ceiling": "number (double)",
  "limit": "number (double)",
  "timeInForce": "string",
  "clientOrderId": "string (uuid)",
  "useAwards": "boolean"
}

and you are setting these values as url params that's the issue.

you need to do this:

uri = 'https://api.bittrex.com/v3/orders'

# NOTE >>>> please check that you provide all the required fields.
payload = {
    'marketSymbol': 'BTC-HEDG',#'HEDG-BTC', #market
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    'useAwards': True
}

# do rest of the stuffs as you are doing

# post payload as json data with the url given in doc
r = requests.post(uri, json=payload, headers=headers, timeout=11)
print(r.json())

If you still have issues let us know. If it works then please mark answer as accepted.
Hope this helps.


问:
getting error ran out of data in Tensor flow 2.0
I am training a multi class classifier on a dataset :
Total Dataset: 1197 images
Training Dataset: 599 images
Validation/Test Dataset: 598 images

My code is given below -

```<code>import tensorflow as tf
import keras_preprocessing
from keras_preprocessing import image
from keras_preprocessing.image import ImageDataGenerator

TRAINING_DIR = "/content/drive/My Drive/solar_images/solar_images/train/"
training_datagen = ImageDataGenerator(
      rescale = 1./255,
        rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

VALIDATION_DIR = "/content/drive/My Drive/solar_images/solar_images/test/"
validation_datagen = ImageDataGenerator(rescale = 1./255)

train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=126
)

validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=126
)

model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 150x150 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.summary()

model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

history = model.fit(train_generator,
                    epochs=25,
                    steps_per_epoch=20,
                    validation_data = validation_generator,
                    verbose = 1,
                    validation_steps=3)

model.save("solar_images_weight.h5")
</code>```

But I am getting error -

```<code>Epoch 1/25
 5/20 [======>.......................] - ETA: 42:21 - loss: 2.3594 - accuracy: 0.3306WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 40 batches). You may need to use the repeat() function when building your dataset.
 5/20 [======>.......................] - 2378s 476s/step - loss: 2.3594 - accuracy: 0.3306 - val_loss: 1.1150 - val_accuracy: 0.3069
</code>```

I am using the below code, but still not working.

```<code>batch_size=126
history = model.fit(train_generator,
                    epochs=25,
                    steps_per_epoch=int(20/batch_size),
                    validation_data = validation_generator,
                    verbose = int(1/batch_size),
                    validation_steps=3)
</code>```

I am mainly follow this link
How to use repeat() function when building data in Keras?

Any help?

答:
The problem, as it is well answered in the link you provided, is that steps_per_epoch and validation_steps need to be equal to the total number of data points divided to the batch_size

Try this

```<code>history = model.fit(train_generator,
                    epochs=25,
                    steps_per_epoch=int(599/batch_size),
                    validation_data=validation_generator,
                    validation_steps=int(598/batch_size)
                    )
</code>```

Body:
I am training a multi class classifier on a dataset :
Total Dataset: 1197 images
Training Dataset: 599 images
Validation/Test Dataset: 598 images

My code is given below -

import tensorflow as tf
import keras_preprocessing
from keras_preprocessing import image
from keras_preprocessing.image import ImageDataGenerator

TRAINING_DIR = "/content/drive/My Drive/solar_images/solar_images/train/"
training_datagen = ImageDataGenerator(
      rescale = 1./255,
        rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

VALIDATION_DIR = "/content/drive/My Drive/solar_images/solar_images/test/"
validation_datagen = ImageDataGenerator(rescale = 1./255)

train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=126
)

validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(150,150),
    class_mode='categorical',
  batch_size=126
)

model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 150x150 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.summary()

model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

history = model.fit(train_generator,
                    epochs=25,
                    steps_per_epoch=20,
                    validation_data = validation_generator,
                    verbose = 1,
                    validation_steps=3)

model.save("solar_images_weight.h5")

But I am getting error -

Epoch 1/25
 5/20 [======>.......................] - ETA: 42:21 - loss: 2.3594 - accuracy: 0.3306WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 40 batches). You may need to use the repeat() function when building your dataset.
 5/20 [======>.......................] - 2378s 476s/step - loss: 2.3594 - accuracy: 0.3306 - val_loss: 1.1150 - val_accuracy: 0.3069

I am using the below code, but still not working.

batch_size=126
history = model.fit(train_generator,
                    epochs=25,
                    steps_per_epoch=int(20/batch_size),
                    validation_data = validation_generator,
                    verbose = int(1/batch_size),
                    validation_steps=3)

I am mainly follow this link
How to use repeat() function when building data in Keras?

Any help?

Body:
The problem, as it is well answered in the link you provided, is that steps_per_epoch and validation_steps need to be equal to the total number of data points divided to the batch_size

Try this

history = model.fit(train_generator,
                    epochs=25,
                    steps_per_epoch=int(599/batch_size),
                    validation_data=validation_generator,
                    validation_steps=int(598/batch_size)
                    )


问:
doc2vec - How to infer vectors of documents faster?
I have trained paragraph vectors for around 2300 paragraphs(between 2000-12000 words each) each with vector size of 300. Now, I need to infer paragraph vectors of around 100,000 sentences which I have considered as paragraphs(each sentence is around 10-30 words each corresponding to the earlier 2300 paragraphs already trained).

So, am using

model.infer_vector(sentence)

But, the problem is it is taking too long, and it does not take any arguments such as "workers" .! Is there a way I can speed up the process by threading or some other way? I am using a machine with 8gb ram and when I checked the available cores using

```<code>cores = multiprocessing.cpu_count()
</code>```

it comes out to be 8.

I need this for answering multiple choice questions. Also, are there any other libraries/models such as doc2vec which can help in this task?

Thanks in advance for your time.

答:
You may use multiprocessing:

from multiprocessing import Pool
from gensim.models import Doc2Vec

MODEL = Doc2Vec.load('my_doc2vec_model', mmap='r')
MODEL.delete_temporary_training_data(keep_doctags_vectors=False, keep_inference=True)

def infer_vector_worker(document):
    vector = MODEL.infer_vector(document)
    return vector

documents = [
    ['now', 'is', 'the', 'time'],       # first document
    ['for', 'all', 'good', 'men'],      # second document
    ['to', 'come', 'to', 'the'],        # third document
    ['aid', 'of', 'their', 'country'],  # fourth document
]
with Pool(processes=4) as pool:
    vectors = pool.map(infer_vector_worker, documents)
```

Since MODEL is a global variable, it will be shared copy-on-write between the processes. Therefore, there will be no extra memory consumption beyond what the inference consumes.

Body:
I have trained paragraph vectors for around 2300 paragraphs(between 2000-12000 words each) each with vector size of 300. Now, I need to infer paragraph vectors of around 100,000 sentences which I have considered as paragraphs(each sentence is around 10-30 words each corresponding to the earlier 2300 paragraphs already trained).

So, am using

model.infer_vector(sentence)

But, the problem is it is taking too long, and it does not take any arguments such as "workers" .! Is there a way I can speed up the process by threading or some other way? I am using a machine with 8gb ram and when I checked the available cores using

cores = multiprocessing.cpu_count()

it comes out to be 8.

I need this for answering multiple choice questions. Also, are there any other libraries/models such as doc2vec which can help in this task?

Thanks in advance for your time.

Body:
You may use multiprocessing:

from multiprocessing import Pool
from gensim.models import Doc2Vec

MODEL = Doc2Vec.load('my_doc2vec_model', mmap='r')
MODEL.delete_temporary_training_data(keep_doctags_vectors=False, keep_inference=True)

def infer_vector_worker(document):
    vector = MODEL.infer_vector(document)
    return vector

documents = [
    ['now', 'is', 'the', 'time'],       # first document
    ['for', 'all', 'good', 'men'],      # second document
    ['to', 'come', 'to', 'the'],        # third document
    ['aid', 'of', 'their', 'country'],  # fourth document
]
with Pool(processes=4) as pool:
    vectors = pool.map(infer_vector_worker, documents)

Since MODEL is a global variable, it will be shared copy-on-write between the processes. Therefore, there will be no extra memory consumption beyond what the inference consumes.


问:
Merging netCDF files in anaconda prompt using NCO?
i am really at a loss about how to merge netcdf files of different times in windows 10, especially merging all nc files in folder. Usually in my ubuntu system i use CDO and the code cdo mergetime *.nc output.nc and that does the job. Unfortunately, in windows, that's a whole different case for me. I went through these websites for solutions:

http://dvalts.io/data/modelling/2018/01/16/NetCDF-merging.html

http://wiki.seas.harvard.edu/geos-chem/index.php/Working_with_netCDF_data_files

Combine multiple NetCDF files into timeseries multidimensional array python

Utilizing codes mentioned there, i came through diversity of errors, these are some the of the codes i ran, which i embedded as image titles, after running them i got these errors:

ncecat ssh_global-reanalysis-phy-001-030-daily_1993-2013.nc ssh_global-reanalysis-phy-001-030-daily_2014-18.nc -O precip_all.nc

ncecat -hO ssh_global-reanalysis-phy-001-030-daily_1993-2013.nc ssh_global-reanalysis-phy-001-030-daily_2014-18.nc -O precip_all.nc

ncecat *.nc -O merged.nc

ncecat *nc -O merged.nc

This is probably happening cause my programming knowledge is very basic. Should i try running the codes in jupyter notebook or maybe spyder ? I would be really grateful if someone takes a look at this and refer me a possible solutions and help me merging netcf files with nco in windows.

this is the version i am using for nco

答: First, if you are trying to concatentate along the time dimension, use ncrcat not ncecat. In any case, it appears you are attempting to provide the input list using shell wildcards (i.e. *.nc) that do not work in Windows DOS shells. Try instead explicitly specifying the input filenames (e.g., 1.nc 2.nc 3.nc). It's not ideal because globbing or using standar input would be easier. One way to avoid having to explicitly specify input filenames on Windows is to use filename patterns from which NCO can construct the input list itself. This and other methods are documented here. Also, based on the error messages you received, you should first unpack (with 'ncpdq -U in.nc out.nc') the input files before attempting to concatenate them.


问:
How to return a hash containing an array of file names for each owner name?
There is a hash named "files" as following :

```<code>files = {
       'file1.txt' => 'John',
       'file2.rb'  => 'Andrew',
       'file3.txt' => 'John'
}
</code>```

Expected result:

A method that takes this hash as argument and return the hash containing the array of files for
respective owner. For e.g

```<code>{
  'John'   =>  ['file1.txt','file3.txt'],
  'Andrew' =>  ['file2.rb']
}

</code>```

答:
```<code>files.
  group_by(&:last). # {"John"=>[["file1.txt", "John"], ["file3.txt", "John"]], "Andrew"=>[["file2.rb", "Andrew"]]}
  transform_values { |v| v.map(&:first) } # {"John"=>["file1.txt", "file3.txt"], "Andrew"=>["file2.rb"]}
</code>```

Body:
There is a hash named "files" as following :

files = {
       'file1.txt' => 'John',
       'file2.rb'  => 'Andrew',
       'file3.txt' => 'John'
}

Expected result:

A method that takes this hash as argument and return the hash containing the array of files for
respective owner. For e.g

{
  'John'   =>  ['file1.txt','file3.txt'],
  'Andrew' =>  ['file2.rb']
}