问:
Django: update a model with the current user when an non-model form field is changed
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page.  I want to allow the user to "adopt" one or more activities by ticking a box, and have their user record linked to each activity via a ForeignKey.  Here are extracts from my code...

models.py

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

class Task(models.Model):
    category    = models.CharField(max_length=300)
    description = models.CharField(max_length=300)

class Activity(models.Model):
    task  = models.ForeignKey(Task, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    notes = models.TextField(blank=True)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
</code>```

The activity "owner" is linked to a User from the Django standard user model.

I added an extra field in the form definition for the adopt field - I don't want to add it to the model as I don't need to save it once it's done it's job.

forms.py

```<code>class ActivityForm(forms.ModelForm):
    adopt = forms.BooleanField(required=False)

    class Meta:
        model = Activity
        fields = '__all__'
</code>```

views.py

```<code>def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():
            ## ? DO SOMETHING HERE ? ##
            formset.save()
        return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)
</code>```

When the adopt field is ticked on the form, I want to be able to set the owner field in that form to the current user before the associated model instance is updated and saved.

I just can't figure out how to do that - if it was a single form (rather than an InlineFormSet), I think I could put code in the view to change the owner value in the form field before it was saved (I haven't tried this).  Or try save(commit = False) and update the model instance  then save() it.
Maybe I have to iterate through the formset in the view code and try one of those options when I find one that had adopt=True?

答:
When the adopt field is ticked on the form, I want to be able to set the owner field in that form to the current user before the associated model instance is updated and saved.

```<code>formset = TaskInlineFormSet(request.POST, instance = task)
if formset.adopt:
    # If True
    formset.user = request.user
    formset.save()

</code>```

I think I could put code in the view to change the owner value in the form field before it was saved (I haven't tried this).
You should give it a try.

Body:
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page.  I want to allow the user to "adopt" one or more activities by ticking a box, and have their user record linked to each activity via a ForeignKey.  Here are extracts from my code...

models.py

from django.contrib.auth.models import User

class Task(models.Model):
    category    = models.CharField(max_length=300)
    description = models.CharField(max_length=300)

class Activity(models.Model):
    task  = models.ForeignKey(Task, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    notes = models.TextField(blank=True)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)

The activity "owner" is linked to a User from the Django standard user model.

I added an extra field in the form definition for the adopt field - I don't want to add it to the model as I don't need to save it once it's done it's job.

forms.py

class ActivityForm(forms.ModelForm):
    adopt = forms.BooleanField(required=False)

    class Meta:
        model = Activity
        fields = '__all__'

views.py

def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():
            ## ? DO SOMETHING HERE ? ##
            formset.save()
        return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)

When the adopt field is ticked on the form, I want to be able to set the owner field in that form to the current user before the associated model instance is updated and saved.

I just can't figure out how to do that - if it was a single form (rather than an InlineFormSet), I think I could put code in the view to change the owner value in the form field before it was saved (I haven't tried this).  Or try save(commit = False) and update the model instance  then save() it.
Maybe I have to iterate through the formset in the view code and try one of those options when I find one that had adopt=True?

Body:
When the adopt field is ticked on the form, I want to be able to set the owner field in that form to the current user before the associated model instance is updated and saved.

formset = TaskInlineFormSet(request.POST, instance = task)
if formset.adopt:
    # If True
    formset.user = request.user
    formset.save()

I think I could put code in the view to change the owner value in the form field before it was saved (I haven't tried this).
You should give it a try.


来源: stackexchange

问:
How to calculate slope of line if lines are perpendicular?
There are two points lastPoint and prePoint. They determine a line.
I try to calculate slope of this line using this:

```<code>    let kbase = (lastPoint.Y - prePoint.Y) / (lastPoint.X - prePoint.X);
    let bbase = lastPoint.Y - kbase * lastPoint.X; //y = kx + b -> y - kx;
    let ybase = `${kbase} * x + ${bbase}`;
</code>```

So, if Y are equals then kbase is zero, it means straight line equation is y = b.

After that I try to calculate slope of perpendicular line to the first line, but I get error, because 1 / kbase where kbase == 0.

```<code>    let kh = -1 * (1 / kbase);
    let bh = startPoint.Y - kh * startPoint.X;
    let yh = `${kh} * x + ${bh}`;
</code>```

How to find a slope of perpendicular line if line equation is y = b?

答:
The explicit form of a line equation, y = mx + p does not allow to represent verticals, as the slope is infinite.

For your purposes, you can use the implicit form, ax + by + c = 0, which does not have this problem. An orthogonal line can be given the equation bx - ay + d = 0.

ContentLicense: CC BY-SA 4.0

Body:
There are two points lastPoint and prePoint. They determine a line.
I try to calculate slope of this line using this:

    let kbase = (lastPoint.Y - prePoint.Y) / (lastPoint.X - prePoint.X);
    let bbase = lastPoint.Y - kbase * lastPoint.X; //y = kx + b -> y - kx;
    let ybase = `${kbase} * x + ${bbase}`;

So, if Y are equals then kbase is zero, it means straight line equation is y = b.

After that I try to calculate slope of perpendicular line to the first line, but I get error, because 1 / kbase where kbase == 0.

    let kh = -1 * (1 / kbase);
    let bh = startPoint.Y - kh * startPoint.X;
    let yh = `${kh} * x + ${bh}`;

How to find a slope of perpendicular line if line equation is y = b?


问:
Why is yarn create react-app command not working
So I have tried to create a react project with yarn so I can use Elastic UI but unfortunately my terminal shoes me an error after I use the command

```<code>yarn create react-app my-app
</code>```

error

```<code>➤ YN0000: ┌ Resolution step
➤ YN0061: │ tar@npm:2.2.2 is deprecated: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.
➤ YN0000: └ Completed in 5s 215ms
➤ YN0000: ┌ Fetch step
➤ YN0000: └ Completed
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done with warnings in 5s 507ms

Creating a new React app in /home/flovet-stack/Documents/my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Usage Error: The project in /home/flovet-stack/package.json doesn't seem to have been installed - running an install there might help

$ yarn add [--json] [-E,--exact] [-T,--tilde] [-C,--caret] [-D,--dev] [-P,--peer] [-O,--optional] [--prefer-dev] [-i,--interactive] [--cached] [--mode #0] ...

Aborting installation.
  yarnpkg add --exact react react-dom react-scripts cra-template --cwd /home/flovet-stack/Documents/my-app has failed.

Deleting generated file... package.json
Deleting my-app/ from /home/flovet-stack/Documents
Done.
</code>```

答:
In you /home/flovet-stack/ folder, run ls -a | grep -E 'yarn|package' command. If you see there are a few folders and files such as

package.json

package-lock.json

.yarn or yarn.lock or any yarn folder and file

Delete these files.

Did you by any chance happen to try and change yarn version (yarn set version <version>) while in that folder? If you did, that's what might've happend. Set the version of yarn in your project or workspace folder only to avoid this in the future, as instructed here

Body:
So I have tried to create a react project with yarn so I can use Elastic UI but unfortunately my terminal shoes me an error after I use the command

yarn create react-app my-app

error

➤ YN0000: ┌ Resolution step
➤ YN0061: │ tar@npm:2.2.2 is deprecated: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.
➤ YN0000: └ Completed in 5s 215ms
➤ YN0000: ┌ Fetch step
➤ YN0000: └ Completed
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done with warnings in 5s 507ms

Creating a new React app in /home/flovet-stack/Documents/my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Usage Error: The project in /home/flovet-stack/package.json doesn't seem to have been installed - running an install there might help

$ yarn add [--json] [-E,--exact] [-T,--tilde] [-C,--caret] [-D,--dev] [-P,--peer] [-O,--optional] [--prefer-dev] [-i,--interactive] [--cached] [--mode #0] ...

Aborting installation.
  yarnpkg add --exact react react-dom react-scripts cra-template --cwd /home/flovet-stack/Documents/my-app has failed.

Deleting generated file... package.json
Deleting my-app/ from /home/flovet-stack/Documents
Done.


问:
Node.js with MySQL docker container network setup
I have a Node.js app (using the new NestJS) framework, running on port 3000. As the database I use MySQL via TypeORM. Locally it all works fine. I am having problems dockerizing it though.

My TypeORM config:

```<code>{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "root",
    "password": "root",
    "database": "nest",
    "entities": ["src/**/*.entity{.ts,.js}"],
    "synchronize": true
}
</code>```

My docker-compose.yml is as follows:

```<code>version: "3"
services:
  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: nest
      MYSQL_USER: root
      MYSQL_PASSWORD: root
    networks:
      - new
  nest:
    image: grimscythe/nest-sample
    depends_on:
      - db
    ports:
      - 3000:3000
    networks:
      - new
networks:
  new:
</code>```

I've been reading the docs on this particular scenario and all should work just fine.
Bash'ing into the MySQL container shows that the DB is running just fine. However the Node framework spits Unable to connect to the database.... Am I missing something in the docker-compose.yml file?

答:
I have just been through the same thing, writing it up for those that follow.

Your typeorm config host is specified as localhost, which is fine and required for local development where there is no docker container, but if you want to connect typeorm to the docker container use db ie. the name of the service on your docker-compose file.

One suggestion is to use "host": process.env.HOST ?? 'localhost' after installing the dotenv package so that you can use the HOST from an env file, else use localhost. Or create an array of connections, named for test / production / staging and load the approriatly named typeorm config, depending on the NODE_ENV at the time.

See Ben Awad Youtube video for a good example.

Body:
I have a Node.js app (using the new NestJS) framework, running on port 3000. As the database I use MySQL via TypeORM. Locally it all works fine. I am having problems dockerizing it though.

My TypeORM config:

{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "root",
    "password": "root",
    "database": "nest",
    "entities": ["src/**/*.entity{.ts,.js}"],
    "synchronize": true
}

My docker-compose.yml is as follows:

version: "3"
services:
  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: nest
      MYSQL_USER: root
      MYSQL_PASSWORD: root
    networks:
      - new
  nest:
    image: grimscythe/nest-sample
    depends_on:
      - db
    ports:
      - 3000:3000
    networks:
      - new
networks:
  new:

I've been reading the docs on this particular scenario and all should work just fine.
Bash'ing into the MySQL container shows that the DB is running just fine. However the Node framework spits Unable to connect to the database.... Am I missing something in the docker-compose.yml file?


问:
JQ: replace an array element, based on subelement value
I want to modify the value of DOMAIN_DISABLE to true if DOMAIN equals domain1.com

jq 'if .DATA[].DOMAIN == "domain1.com" then .DATA[].DOMAIN_DISABLE = true else . end' "${Json}"
```
<p>Json Array:</p>
<pre class="lang-json prettyprint-override"><code>{
    "ACTION": "domain.list",
    "DATA": [
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain1.com",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 11111,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": false,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain2.net",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 22222,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": false,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain3.edu",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 33333,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": true,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        }
    ],
    "ERRORARRAY": []
}
</code>```

Desired output:

{
    "ACTION": "domain.list",
    "DATA": [
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain1.com",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 11111,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": true,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain2.net",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 22222,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": false,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain3.edu",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 33333,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": true,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        }
    ],
    "ERRORARRAY": []
}
```

what should I change in my jq command?

答:
Here's another approach that simply assigns true to a selected set of targets. This works (the original object remains in context) because the selection (on the left-hand side) happens in a subcontext (in parentheses) while the assignment itself is still part of the top-level context.

jq '(.DATA[] | select(.DOMAIN == "domain1.com")).DOMAIN_DISABLE = true'
```

Demo

Body:
I want to modify the value of DOMAIN_DISABLE to true if DOMAIN equals domain1.com

jq 'if .DATA[].DOMAIN == "domain1.com" then .DATA[].DOMAIN_DISABLE = true else . end' "${Json}"

Json Array:

{
    "ACTION": "domain.list",
    "DATA": [
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain1.com",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 11111,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": false,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain2.net",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 22222,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": false,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain3.edu",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 33333,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": true,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        }
    ],
    "ERRORARRAY": []
}

Desired output:

{
    "ACTION": "domain.list",
    "DATA": [
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain1.com",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 11111,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": true,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain2.net",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 22222,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": false,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        },
        {
            "TYPE": "slave",
            "AXFR_IPS": "none",
            "DOMAIN": "domain3.edu",
            "TTL_SEC": 0,
            "SOA_EMAIL": "",
            "DOMAINID": 33333,
            "DESCRIPTION": "",
            "EXPIRE_SEC": 0,
            "RETRY_SEC": 0,
            "STATUS": 1,
            "DOMAIN_DISABLE": true,
            "LPM_DISPLAYGROUP": "",
            "REFRESH_SEC": 0
        }
    ],
    "ERRORARRAY": []
}

what should I change in my jq command?

Body:
Here's another approach that simply assigns true to a selected set of targets. This works (the original object remains in context) because the selection (on the left-hand side) happens in a subcontext (in parentheses) while the assignment itself is still part of the top-level context.

jq '(.DATA[] | select(.DOMAIN == "domain1.com")).DOMAIN_DISABLE = true'

Demo


问:
With Azure should i store my static shared JS and images files in the package release or in a blob?
Speed and cost in mind.
Say I have a few JS and images files shared for multiple websites. that is not huge images files, this is only few static files like PNG sprites and common JS files.
I'm kind of lost on the choice :
- Should i keep it in my webpackage to release in Azure ?
- Or should i put these in blobs ?

The things I don't know is if i have a lot of hits on the blob solution, it might cost more than the hits on the IIS level of the package ?
Right, wrong ?

Edit : I realize storing JS files on the blob won't deliver it gziped ?

答: Will your JS and image files be modified often? If so, putting them into the service package would mean that every time you want to update those files, you will have to recompile the service package and redeploy your instance. If you find yourself needing to update often, this will become cumbersome. From a speed perspective, you're not going to see too much of a difference between service them files up from the blogs or serving them up from the web role (assuming the files are in fact not huge). Last but not least, from a cost perspective, if you look at the cost of blob storage ($0.15 per GB stored per month, $0.01 per 10,000 storage transactions), its really not much. Your site would have to have a lot of traffic for the cost to become significant.</p>

ContentLicense: CC BY-SA 3.0


问:
503 Error: Service Unavailable heroku while doing inference
I have deployed a machine learning model using Fast API in Heroku and I have implemented the background worker and async but when I am doing inference I am still getting 503 error. I know the server response time in Heroku is 30 seconds.

But as I am using a background worker I should be able to run in the background, instead, I am getting errors. I am using Heroku free plan to deploy

app = FastAPI()
response = {}
@app.get('/predict')
async def predictions(solute, solvent):
    mol = Chem.MolFromSmiles(solute)
    response["predictions"] = delta_g.item()
    return {'result': response}

async def predict(background_tasks: BackgroundTasks,solute,solvent):
    background_tasks.add_task(predictions,solute,solvent)

from predict_json import json_data_func

@app.get('/predict_two')
async def predictions_two(solute):
    for i in data:
        delta_g, interaction_map = model([get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles(solute)))).to(device), get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles(i)))).to(device)])
        response_two[i] = delta_g.item()
    return {'result': response_two}

async def predict_two(background_tasks: BackgroundTasks,solute):
    background_tasks.add_task(predictions_two,solute)
```

Procfile:
web: gunicorn -w 2 -k uvicorn.workers.UvicornWorker main:app

So what should I have to do to run my code in the background without having a server response time-out error?

答:
You can add timeout parameter (with -t or --timeout) to the gunicorn as stated in the gunicorn documentation.

Example usage:

```<code>gunicorn -w 2 -k uvicorn.workers.UvicornWorker -t 90 main:app
</code>```

Body:
I have deployed a machine learning model using Fast API in Heroku and I have implemented the background worker and async but when I am doing inference I am still getting 503 error. I know the server response time in Heroku is 30 seconds.

But as I am using a background worker I should be able to run in the background, instead, I am getting errors. I am using Heroku free plan to deploy

app = FastAPI()
response = {}
@app.get('/predict')
async def predictions(solute, solvent):
    mol = Chem.MolFromSmiles(solute)
    response["predictions"] = delta_g.item()
    return {'result': response}

async def predict(background_tasks: BackgroundTasks,solute,solvent):
    background_tasks.add_task(predictions,solute,solvent)

from predict_json import json_data_func

@app.get('/predict_two')
async def predictions_two(solute):
    for i in data:
        delta_g, interaction_map = model([get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles(solute)))).to(device), get_graph_from_smile(Chem.MolToSmiles(Chem.AddHs(Chem.MolFromSmiles(i)))).to(device)])
        response_two[i] = delta_g.item()
    return {'result': response_two}

async def predict_two(background_tasks: BackgroundTasks,solute):
    background_tasks.add_task(predictions_two,solute)

Procfile:
web: gunicorn -w 2 -k uvicorn.workers.UvicornWorker main:app

So what should I have to do to run my code in the background without having a server response time-out error?

Body:
You can add timeout parameter (with -t or --timeout) to the gunicorn as stated in the gunicorn documentation.

Example usage:

gunicorn -w 2 -k uvicorn.workers.UvicornWorker -t 90 main:app


问:
Tkinter DateEntry not allowing selection
I am using a Tkinter DateEntry field to get a "from" and "to" date for a SQL query. I recetnly redid my project, but copied a lot of code over. In my old project, the date entry works fine, however in my new project whenever I try to select a day for any DateEntry fields, it autofills and does not allow me to use the drop-down window.

This link is an example of how it looks in my working project:
https://www.plus2net.com/python/tkinter-DateEntry.php

This is the working code:

```<code>date_joined_to = DateEntry(container, selectmode="day", year=datetime.now().year,
                           month=datetime.now().month, day=datetime.now().day,
                           date_pattern="yyyy-mm-dd", foreground="black",
                           headersforeground="black", selectforeground="black",
                           width=10)
date_joined_to.grid(row=4, column=1, sticky="W")
date_joined_to.delete(0, "end")
date_joined_to._top_cal.overrideredirect(False)
</code>```

This is my code in my new project where the problem occurs:

```<code>test_date_to = DateEntry(self.centersearch, selectmode="day", year=datetime.now().year,
                         month=datetime.now().month,
                         day=datetime.now().day, date_pattern="yyyy-mm-dd",
                         foreground="black", headersforeground="black",
                         selectforeground="black", width=10)
test_date_to.grid(row=9, column=1, sticky="E")
test_date_to.delete(0, "end")
test_date_to._top_cal.overrideredirect(False)
</code>```

I tried removing all keyword arguments to see if those caused it, but the issue persisted.

From my searches it does appear that many people have encountered this before.

答:
I can't answer as I've seen the same problem and got here looking for an answer. Here is code that shows it. In my case the version that works looks the same but is not in separate classes but instead in one large script file. But for real world problems that's poor coding practice. When I moved it out into classes It no longer works.

This version works

```<code>import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkcalendar import DateEntry

from datetime import datetime
current_day = datetime.now().day
current_month = datetime.now().month
current_year = datetime.now().year

root = tk.Tk()
root.title("Date Demo Works")
# root.minsize(750, 400)
root.geometry("1024x768+0+0")
root.grid()

demo_edit_screen = tk.Toplevel(root)
demo_edit_screen.geometry("1024x768+0+0")
demo_edit_screen.title("Demo Working")
demo_edit_screen.iconify()
demo_edit_screen.withdraw()

def DoNothing():
    tk.messagebox.showinfo(message='This is an info box that Does Nothing')
    print("testing do nothing dialog")

class DemoEdit():
    def __init__(self):
        leftsidebar = tk.Frame(demo_edit_screen, borderwidth=2, relief="raised", width=40)
        leftsidebar.grid(row=0, column=0, rowspan=11, sticky=("NSEW"))
        gohome = ttk.Button(leftsidebar, text="Home", command=DoNothing())
        gohome.grid(row=0, column=0)
        centersearch = tk.Frame(demo_edit_screen, width=850)
        centersearch.grid(row=0, column=1, sticky="W")
        test_date_label = tk.Label(centersearch, text='Test Date Range', anchor="e")
        test_date_label.grid(row=7, column=0, columnspan=2, padx=4)
        test_date_from_label = tk.Label(centersearch, text='From', anchor="w")
        test_date_from_label.grid(row=8, column=0, padx=4)
        test_date_to_label = tk.Label(centersearch, text='To', anchor="w")
        test_date_to_label.grid(row=8, column=1, padx=4)
        test_date_from = DateEntry(centersearch, selectmode="day"
                                   , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                   , date_pattern="yyyy-mm-dd"
                                   , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_from.grid(row=9, column=0, sticky="W")
        test_date_from.delete(0, "end")
        test_date_from._top_cal.overrideredirect(False)
        test_date_to = DateEntry(centersearch, selectmode="day"
                                 , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                 , date_pattern="yyyy-mm-dd"
                                 , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_to.grid(row=9, column=1, sticky="E")
        test_date_to.delete(0, "end")
        test_date_to._top_cal.overrideredirect(False)

    def show_demoedit(self):
        root.withdraw()
        demo_edit_screen.update()
        demo_edit_screen.deiconify()

leftsidebar = tk.Frame(root, borderwidth=2, relief="raised", height=768)
leftsidebar.grid(row=0, column=0, rowspan=8, sticky=("NSEW"))
show_screen = ttk.Button(leftsidebar, text="Show Calendar Screen", command=DemoEdit.show_demoedit(root))
show_screen.grid(row=3, column=0)
demo_edit = DemoEdit()

root.mainloop()
</code>```

This version does not

```<code>import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

from tkcalendar import DateEntry
from datetime import datetime

def DoNothing():
    tk.messagebox.showinfo(message='This is an info box that Does Nothing')
    print("testing do nothing dialog")

class TopScreen(tk.Frame):
    def __init__(self, parent, controller, label_text="sample", *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.controller = controller
        self.parent = parent
        #   Create the choose action sidebar that will go to specific screens
        self.leftsidebar = tk.Frame(self, borderwidth=2, relief="raised", height=768)
        self.leftsidebar.grid(row=0, column=0, rowspan=8, sticky=("NSEW"))
        self.home_label = tk.Label(self.leftsidebar, text=label_text)
        self.home_label.grid(row=0, column=0)

class CSVReportScreen(TopScreen):
    def __init__(self, parent, controller):
        super().__init__(parent, controller, label_text="CSV Report")
        self.controller = controller
        self.parent = parent
        create_csv_files_button = ttk.Button(self.leftsidebar, text="Create .CSV Files", command=DoNothing())
        create_csv_files_button.grid(row=3, column=0, sticky="NSEW")
        #   Top center search section
        self.centersearch = tk.Frame(self, width=850)
        self.centersearch.grid(row=0, column=1, sticky="W")

        test_date_label = tk.Label(self.centersearch, text='Test Date Range', anchor="e")
        test_date_label.grid(row=7, column=0, columnspan=2, padx=4)
        test_date_from_label = tk.Label(self.centersearch, text='From', anchor="w")
        test_date_from_label.grid(row=8, column=0, padx=4)
        test_date_to_label = tk.Label(self.centersearch, text='To', anchor="w")
        test_date_to_label.grid(row=8, column=1, padx=4)
        test_date_from = DateEntry(self.centersearch, selectmode="day"
                                 , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                 , date_pattern="yyyy-mm-dd"
                                 , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_from.grid(row=9, column=0, sticky="W")
        test_date_from.delete(0, "end")
        test_date_from._top_cal.overrideredirect(False)
        test_date_to = DateEntry(self.centersearch, selectmode="day"
                                 , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                 , date_pattern="yyyy-mm-dd"
                                 , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_to.grid(row=9, column=1, sticky="E")
        test_date_to.delete(0, "end")
        test_date_to._top_cal.overrideredirect(False)

class TestApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = dict()
        # Add each separate screen here. The name is the class for that screen
        trakker_classes = (CSVReportScreen,TopScreen)
        for F in trakker_classes:
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame("CSVReportScreen")

    def show_frame(self, page_name):
        # Show a frame for the given page name
        frame = self.frames[page_name]
        frame.tkraise()

if __name__ == "__main__":
    app = TestApp()
    app.mainloop()
</code>```

DateEntry is a part of tkcalendar. So I have the same question.

OK, I've just spent all day trying all sorts of permutations:

I'm running on MacOS Catalina 10.15.7 (19H1824)
I am using PyCharm 2021.03.3 (Professional Edition)
Build #Py-213.7172.26, built on March 15, 2022

I am using virtual environments and have tried the following versions with these results:

Python 3.8.3
tkinter 8.6.8
Cannot get the DateEntry dropdown calendar to appear. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior.

Python version 3.8.10 (v3.8.10:3d8993a744, May  3 2021, 08:55:58)
tkinter  8.6.8
DateEntry in the documentation demo code works when the  _top_cal.overrideredirect(False) is used.
My DateEntry is not working from within a class.

Python 3.9.8 Universal Version
tkinter 8.6.11
DateEntry dropdown requires double clicks to display. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior. Same in both documentation demo code and my code.

Python 3.9.12 Intel
tkinter 8.6.8
Cannot get the DateEntry dropdown calendar to appear. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior. Same in both documentation demo code and my code.

Python 3.10.4 Universal Version
tkinter 8.6.121
DateEntry dropdown requires double clicks to display. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior. Same in both documentation demo code and my code.

A couple of things I learned along the way.
The Intel Python installers all seem to include tkinter 8.6.8
The Universal installers seem to grab whatever was the latest for that version of Python.

I was not able to test all the options because for lots of the intervening ones there are no installers. I was not able to install from the source code.

I don't know where to go from here.

Body:
I am using a Tkinter DateEntry field to get a "from" and "to" date for a SQL query. I recetnly redid my project, but copied a lot of code over. In my old project, the date entry works fine, however in my new project whenever I try to select a day for any DateEntry fields, it autofills and does not allow me to use the drop-down window.

This link is an example of how it looks in my working project:
https://www.plus2net.com/python/tkinter-DateEntry.php

This is the working code:

date_joined_to = DateEntry(container, selectmode="day", year=datetime.now().year,
                           month=datetime.now().month, day=datetime.now().day,
                           date_pattern="yyyy-mm-dd", foreground="black",
                           headersforeground="black", selectforeground="black",
                           width=10)
date_joined_to.grid(row=4, column=1, sticky="W")
date_joined_to.delete(0, "end")
date_joined_to._top_cal.overrideredirect(False)

This is my code in my new project where the problem occurs:

test_date_to = DateEntry(self.centersearch, selectmode="day", year=datetime.now().year,
                         month=datetime.now().month,
                         day=datetime.now().day, date_pattern="yyyy-mm-dd",
                         foreground="black", headersforeground="black",
                         selectforeground="black", width=10)
test_date_to.grid(row=9, column=1, sticky="E")
test_date_to.delete(0, "end")
test_date_to._top_cal.overrideredirect(False)

I tried removing all keyword arguments to see if those caused it, but the issue persisted.

From my searches it does appear that many people have encountered this before.

Body:
I can't answer as I've seen the same problem and got here looking for an answer. Here is code that shows it. In my case the version that works looks the same but is not in separate classes but instead in one large script file. But for real world problems that's poor coding practice. When I moved it out into classes It no longer works.

This version works

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkcalendar import DateEntry

from datetime import datetime
current_day = datetime.now().day
current_month = datetime.now().month
current_year = datetime.now().year

root = tk.Tk()
root.title("Date Demo Works")
# root.minsize(750, 400)
root.geometry("1024x768+0+0")
root.grid()

demo_edit_screen = tk.Toplevel(root)
demo_edit_screen.geometry("1024x768+0+0")
demo_edit_screen.title("Demo Working")
demo_edit_screen.iconify()
demo_edit_screen.withdraw()

def DoNothing():
    tk.messagebox.showinfo(message='This is an info box that Does Nothing')
    print("testing do nothing dialog")

class DemoEdit():
    def __init__(self):
        leftsidebar = tk.Frame(demo_edit_screen, borderwidth=2, relief="raised", width=40)
        leftsidebar.grid(row=0, column=0, rowspan=11, sticky=("NSEW"))
        gohome = ttk.Button(leftsidebar, text="Home", command=DoNothing())
        gohome.grid(row=0, column=0)
        centersearch = tk.Frame(demo_edit_screen, width=850)
        centersearch.grid(row=0, column=1, sticky="W")
        test_date_label = tk.Label(centersearch, text='Test Date Range', anchor="e")
        test_date_label.grid(row=7, column=0, columnspan=2, padx=4)
        test_date_from_label = tk.Label(centersearch, text='From', anchor="w")
        test_date_from_label.grid(row=8, column=0, padx=4)
        test_date_to_label = tk.Label(centersearch, text='To', anchor="w")
        test_date_to_label.grid(row=8, column=1, padx=4)
        test_date_from = DateEntry(centersearch, selectmode="day"
                                   , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                   , date_pattern="yyyy-mm-dd"
                                   , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_from.grid(row=9, column=0, sticky="W")
        test_date_from.delete(0, "end")
        test_date_from._top_cal.overrideredirect(False)
        test_date_to = DateEntry(centersearch, selectmode="day"
                                 , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                 , date_pattern="yyyy-mm-dd"
                                 , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_to.grid(row=9, column=1, sticky="E")
        test_date_to.delete(0, "end")
        test_date_to._top_cal.overrideredirect(False)

    def show_demoedit(self):
        root.withdraw()
        demo_edit_screen.update()
        demo_edit_screen.deiconify()

leftsidebar = tk.Frame(root, borderwidth=2, relief="raised", height=768)
leftsidebar.grid(row=0, column=0, rowspan=8, sticky=("NSEW"))
show_screen = ttk.Button(leftsidebar, text="Show Calendar Screen", command=DemoEdit.show_demoedit(root))
show_screen.grid(row=3, column=0)
demo_edit = DemoEdit()

root.mainloop()

This version does not

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

from tkcalendar import DateEntry
from datetime import datetime

def DoNothing():
    tk.messagebox.showinfo(message='This is an info box that Does Nothing')
    print("testing do nothing dialog")

class TopScreen(tk.Frame):
    def __init__(self, parent, controller, label_text="sample", *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.controller = controller
        self.parent = parent
        #   Create the choose action sidebar that will go to specific screens
        self.leftsidebar = tk.Frame(self, borderwidth=2, relief="raised", height=768)
        self.leftsidebar.grid(row=0, column=0, rowspan=8, sticky=("NSEW"))
        self.home_label = tk.Label(self.leftsidebar, text=label_text)
        self.home_label.grid(row=0, column=0)

class CSVReportScreen(TopScreen):
    def __init__(self, parent, controller):
        super().__init__(parent, controller, label_text="CSV Report")
        self.controller = controller
        self.parent = parent
        create_csv_files_button = ttk.Button(self.leftsidebar, text="Create .CSV Files", command=DoNothing())
        create_csv_files_button.grid(row=3, column=0, sticky="NSEW")
        #   Top center search section
        self.centersearch = tk.Frame(self, width=850)
        self.centersearch.grid(row=0, column=1, sticky="W")

        test_date_label = tk.Label(self.centersearch, text='Test Date Range', anchor="e")
        test_date_label.grid(row=7, column=0, columnspan=2, padx=4)
        test_date_from_label = tk.Label(self.centersearch, text='From', anchor="w")
        test_date_from_label.grid(row=8, column=0, padx=4)
        test_date_to_label = tk.Label(self.centersearch, text='To', anchor="w")
        test_date_to_label.grid(row=8, column=1, padx=4)
        test_date_from = DateEntry(self.centersearch, selectmode="day"
                                 , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                 , date_pattern="yyyy-mm-dd"
                                 , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_from.grid(row=9, column=0, sticky="W")
        test_date_from.delete(0, "end")
        test_date_from._top_cal.overrideredirect(False)
        test_date_to = DateEntry(self.centersearch, selectmode="day"
                                 , year=datetime.now().year, month=datetime.now().month, day=datetime.now().day
                                 , date_pattern="yyyy-mm-dd"
                                 , foreground="black", headersforeground="black", selectforeground="black", width=10)
        test_date_to.grid(row=9, column=1, sticky="E")
        test_date_to.delete(0, "end")
        test_date_to._top_cal.overrideredirect(False)

class TestApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = dict()
        # Add each separate screen here. The name is the class for that screen
        trakker_classes = (CSVReportScreen,TopScreen)
        for F in trakker_classes:
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame("CSVReportScreen")

    def show_frame(self, page_name):
        # Show a frame for the given page name
        frame = self.frames[page_name]
        frame.tkraise()

if __name__ == "__main__":
    app = TestApp()
    app.mainloop()

DateEntry is a part of tkcalendar. So I have the same question.

OK, I've just spent all day trying all sorts of permutations:

I'm running on MacOS Catalina 10.15.7 (19H1824)
I am using PyCharm 2021.03.3 (Professional Edition)
Build #Py-213.7172.26, built on March 15, 2022

I am using virtual environments and have tried the following versions with these results:

Python 3.8.3
tkinter 8.6.8
Cannot get the DateEntry dropdown calendar to appear. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior.

Python version 3.8.10 (v3.8.10:3d8993a744, May  3 2021, 08:55:58)
tkinter  8.6.8
DateEntry in the documentation demo code works when the  _top_cal.overrideredirect(False) is used.
My DateEntry is not working from within a class.

Python 3.9.8 Universal Version
tkinter 8.6.11
DateEntry dropdown requires double clicks to display. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior. Same in both documentation demo code and my code.

Python 3.9.12 Intel
tkinter 8.6.8
Cannot get the DateEntry dropdown calendar to appear. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior. Same in both documentation demo code and my code.

Python 3.10.4 Universal Version
tkinter 8.6.121
DateEntry dropdown requires double clicks to display. Doesn't matter whether the _top_cal.overrideredirect(False) is set or not same behavior. Same in both documentation demo code and my code.

A couple of things I learned along the way.
The Intel Python installers all seem to include tkinter 8.6.8
The Universal installers seem to grab whatever was the latest for that version of Python.

I was not able to test all the options because for lots of the intervening ones there are no installers. I was not able to install from the source code.

I don't know where to go from here.


问:
Recursive/hierarchical query in BigQuery
I have a recursion/hierarchical problem that I'm trying to figure out in BigQuery.

I have a list of employees and each employee has a manager ID. I need to be able to enter a single Employee_ID and return an array of every person beneath them.

```<code>CREATE TABLE p_RLS.testHeirarchy
 (
   Employee_ID INT64,
   Employee_Name STRING,
   Position STRING,
   Line_Manager_ID INT64
 );

INSERT INTO p_RLS.testHeirarchy (Employee_ID, Employee_Name, Position, Line_Manager_ID)
VALUES(1,'Joe','Worker',11),
      (2,'James','Worker',11),
      (3,'Jack','Worker',11),
      (4,'Jill','Worker',12),
      (5,'Jan','Worker',12),
      (6,'Jacquie','Worker',13),
      (7,'Joaquin','Worker',14),
      (8,'Jeremy','Worker',14),
      (9,'Jade','Worker',15),
      (10,'Jocelyn','Worker',15),
      (11, 'Bob', 'Store Manager',16),
      (12, 'Bill', 'Store Manager',16),
      (13, 'Barb', 'Store Manager',16),
      (14, 'Ben', 'Store Manager',17),
      (15, 'Burt', 'Store Manager',17),
      (16, 'Sally','Group Manager',18),
      (17, 'Sam','Group Manager',19),
      (18, 'Anna', 'Ops Manager',20),
      (19, 'Amy', 'Ops Manager',20),
      (20, 'Zoe', 'State Manager', NULL);
</code>```

My desired output would resemble:

```<code>SELECT 20 as Employee_ID, [19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1] as Reports;
SELECT 11 as Employee_ID, [3,2,1] as Reports;
SELECT 1 as Employee_ID, [] as Reports;
</code>```

I have got the following working but it seems very ugly/inconvenient and doesn't support unlimited levels:

```<code>WITH test as (
SELECT L0.Employee_ID, L0.Employee_Name, L0.Position, L0.Line_Manager_ID,
ARRAY_AGG(DISTINCT L1.Employee_ID IGNORE NULLS) as Lvl1,
ARRAY_AGG(DISTINCT L2.Employee_ID IGNORE NULLS) as Lvl2,
ARRAY_AGG(DISTINCT L3.Employee_ID IGNORE NULLS) as Lvl3,
ARRAY_AGG(DISTINCT L4.Employee_ID IGNORE NULLS) as Lvl4,
ARRAY_AGG(DISTINCT L5.Employee_ID IGNORE NULLS) as Lvl5,
ARRAY_AGG(DISTINCT L6.Employee_ID IGNORE NULLS) as Lvl6,
ARRAY_AGG(DISTINCT L7.Employee_ID IGNORE NULLS) as Lvl7
FROM p_RLS.testHeirarchy as L0
LEFT OUTER JOIN p_RLS.testHeirarchy L1 ON L0.Employee_ID = L1.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L2 ON L1.Employee_ID = L2.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L3 ON L2.Employee_ID = L3.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L4 ON L3.Employee_ID = L4.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L5 ON L4.Employee_ID = L5.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L6 ON L5.Employee_ID = L6.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L7 ON L6.Employee_ID = L7.Line_Manager_ID
WHERE L0.Employee_ID = 16
GROUP BY 1,2,3,4)

SELECT
Employee_ID, ARRAY_CONCAT(
    IFNULL(Lvl1,[]),
    IFNULL(Lvl2,[]),
    IFNULL(Lvl3,[]),
    IFNULL(Lvl4,[]),
    IFNULL(Lvl5,[]),
    IFNULL(Lvl6,[]),
    IFNULL(Lvl7,[])) as All_reports
FROM test
</code>```

Is there a better way to do this? Is a recursive approach possible in BigQuery?

答:
Recursive CTE was recently introduced !

This makes things so much easier

```<code>with recursive iterations as (
  select line_manager_id, employee_id, 1 pos from your_table
  union all
  select b.line_manager_id, a.employee_id, pos + 1
  from your_table a join iterations b
  on b.employee_id = a.line_manager_id
)
select line_manager_id, string_agg('' || employee_id order by pos, employee_id desc) as reports_as_list
from iterations
where not line_manager_id is null
group by line_manager_id
order by line_manager_id desc
</code>```

If applied to sample data in question - output is

Body:
I have a recursion/hierarchical problem that I'm trying to figure out in BigQuery.

I have a list of employees and each employee has a manager ID. I need to be able to enter a single Employee_ID and return an array of every person beneath them.

CREATE TABLE p_RLS.testHeirarchy
 (
   Employee_ID INT64,
   Employee_Name STRING,
   Position STRING,
   Line_Manager_ID INT64
 );

INSERT INTO p_RLS.testHeirarchy (Employee_ID, Employee_Name, Position, Line_Manager_ID)
VALUES(1,'Joe','Worker',11),
      (2,'James','Worker',11),
      (3,'Jack','Worker',11),
      (4,'Jill','Worker',12),
      (5,'Jan','Worker',12),
      (6,'Jacquie','Worker',13),
      (7,'Joaquin','Worker',14),
      (8,'Jeremy','Worker',14),
      (9,'Jade','Worker',15),
      (10,'Jocelyn','Worker',15),
      (11, 'Bob', 'Store Manager',16),
      (12, 'Bill', 'Store Manager',16),
      (13, 'Barb', 'Store Manager',16),
      (14, 'Ben', 'Store Manager',17),
      (15, 'Burt', 'Store Manager',17),
      (16, 'Sally','Group Manager',18),
      (17, 'Sam','Group Manager',19),
      (18, 'Anna', 'Ops Manager',20),
      (19, 'Amy', 'Ops Manager',20),
      (20, 'Zoe', 'State Manager', NULL);

My desired output would resemble:

SELECT 20 as Employee_ID, [19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1] as Reports;
SELECT 11 as Employee_ID, [3,2,1] as Reports;
SELECT 1 as Employee_ID, [] as Reports;

I have got the following working but it seems very ugly/inconvenient and doesn't support unlimited levels:

WITH test as (
SELECT L0.Employee_ID, L0.Employee_Name, L0.Position, L0.Line_Manager_ID,
ARRAY_AGG(DISTINCT L1.Employee_ID IGNORE NULLS) as Lvl1,
ARRAY_AGG(DISTINCT L2.Employee_ID IGNORE NULLS) as Lvl2,
ARRAY_AGG(DISTINCT L3.Employee_ID IGNORE NULLS) as Lvl3,
ARRAY_AGG(DISTINCT L4.Employee_ID IGNORE NULLS) as Lvl4,
ARRAY_AGG(DISTINCT L5.Employee_ID IGNORE NULLS) as Lvl5,
ARRAY_AGG(DISTINCT L6.Employee_ID IGNORE NULLS) as Lvl6,
ARRAY_AGG(DISTINCT L7.Employee_ID IGNORE NULLS) as Lvl7
FROM p_RLS.testHeirarchy as L0
LEFT OUTER JOIN p_RLS.testHeirarchy L1 ON L0.Employee_ID = L1.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L2 ON L1.Employee_ID = L2.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L3 ON L2.Employee_ID = L3.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L4 ON L3.Employee_ID = L4.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L5 ON L4.Employee_ID = L5.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L6 ON L5.Employee_ID = L6.Line_Manager_ID
LEFT OUTER JOIN p_RLS.testHeirarchy L7 ON L6.Employee_ID = L7.Line_Manager_ID
WHERE L0.Employee_ID = 16
GROUP BY 1,2,3,4)

SELECT
Employee_ID, ARRAY_CONCAT(
    IFNULL(Lvl1,[]),
    IFNULL(Lvl2,[]),
    IFNULL(Lvl3,[]),
    IFNULL(Lvl4,[]),
    IFNULL(Lvl5,[]),
    IFNULL(Lvl6,[]),
    IFNULL(Lvl7,[])) as All_reports
FROM test

Is there a better way to do this? Is a recursive approach possible in BigQuery?

Body:
Recursive CTE was recently introduced !

This makes things so much easier

with recursive iterations as (
  select line_manager_id, employee_id, 1 pos from your_table
  union all
  select b.line_manager_id, a.employee_id, pos + 1
  from your_table a join iterations b
  on b.employee_id = a.line_manager_id
)
select line_manager_id, string_agg('' || employee_id order by pos, employee_id desc) as reports_as_list
from iterations
where not line_manager_id is null
group by line_manager_id
order by line_manager_id desc

If applied to sample data in question - output is


答:
As others have said, the slope of a vertical line is undefined. This is just how it works mathematically, and there are no problems with your code, and your math is correct. As you have realized, a horizontal line is a function that follows the form y = ox+b and its slope is 0. The perpendicular line of a horizontal line results in a vertical line which is not a function. This means that there are several values of y that correspond to one value you of x. Here is why that is important.

The general way of calculating slop is the change in y over the change in x.
Because a vertical line is not a function, there are multiple y's for one x. Here is an example. Let's say that we had the equation x=5. Here are some points: (5,1),(5,2),(5,3)(5,7). If you calculated slope with the first two points, it would result in (2-1)/(5-5) which is 1/0, and if you calculated slope with the last two points,
it would result in (7-3)/(5-5) which is 4/0. If you continued to do this, you would have an infinite number of undefined values for the slope of a vertical line. Keep in mind that 1/0 does not necessarily equal 2/0 or 6/0.Even if you tried to find a horizontal line and take the inverse reciprocal, which you did, you would not be able to find a defined value.

For example, if slope is the change in y over the change in x, then the inverse reciprocal would be -1 * the change in x over the change in y. Let's say that we had the horizontal line y = 0x + 5. The coefficient of the x or slope is 0. Four points would be (5,5), (9,5), (3,5) (6,5), and the two slope calculations for the slope of the perpendicular line would be 4/0 and 3/0 which leads to the same situation as last time.

To conclude, the answer to your question "How to find a slope of perpendicular line if line equation is y = b?" is that there is no defined value for the slope of a perpendicular line, and you definitely wont find one through the code you are using.

Title: How to calculate slope of line if lines are perpendicular?


问:
How to check if AVPlayer has Video or just Audio?
I try to play some "media" but at the time the AVPlayer starts I don't know if it is audio or Video.

I connected the player Layer and it works fine.

```<code>self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:[[PCPlayerManager sharedManager] audioPlayer]];
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
avPlayerLayer.frame = CGRectMake(0, 0, videoView.frame.size.width, videoView.frame.size.height);
[videoView.layer addSublayer:avPlayerLayer];
</code>```

But how can I check if there is Video so I can add/remove some Options?

答:
I found this better solution

```<code>func isVideoAvailable(item: AVPlayerItem) -> Bool {
        for video in item.tracks {
            if video.assetTrack?.mediaType == .video {
                return true
            }
        }
        return false
}
</code>```

And this

```<code>  if currentItem.tracks.contains(where: { track in
     track.assetTrack?.mediaType == .video
  }) {

     // This Code goes Here!
  }
</code>```

Body:
I try to play some "media" but at the time the AVPlayer starts I don't know if it is audio or Video.

I connected the player Layer and it works fine.

self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:[[PCPlayerManager sharedManager] audioPlayer]];
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
avPlayerLayer.frame = CGRectMake(0, 0, videoView.frame.size.width, videoView.frame.size.height);
[videoView.layer addSublayer:avPlayerLayer];

But how can I check if there is Video so I can add/remove some Options?

Body:
I found this better solution

func isVideoAvailable(item: AVPlayerItem) -> Bool {
        for video in item.tracks {
            if video.assetTrack?.mediaType == .video {
                return true
            }
        }
        return false
}

And this

  if currentItem.tracks.contains(where: { track in
     track.assetTrack?.mediaType == .video
  }) {

     // This Code goes Here!
  }


问:
New c# nullable option
In new version of C# is default option nullable. I mean this

It's really good feature for me. But I don't understand one thing. Is property nullable by me or by program?

I know that this property should never be null because I fill it in the form and never set it as null. But in general it can be null. How should I mark it?

Example:

UserModel:

```<code>public string? Name { get; set; }

public string Name { get; set; } = null!
</code>```

I'm really confused.

答:
I know that this property should never be null because I fill it in
the form and never set it as null. But in general it can be null. How
should I mark it?

If it is set to non-null in the constructor, then you can declare it a string rather than string? because it really is guaranteed to never be null.

If, however, it is null after the constructor has run (and before any other methods are called) then it CAN be null and you should declare it as string?.

The dichotomy you face is that (from what you say) it should never be null when the class is used correctly - i.e. if the calling code does indeed call the method that initialises the property to non-null before accessing it, it will be guaranteed to be not null - which means you would like to declare it as a non-null string so that callers don't need to use the null-forgiving ! operator to suppress nullable warnings.

What to do in this case? Well I think you have three possibilities:

Declare the property as nullable: string? and let the callers suppress the nullable warning or check the value for null.

Initialise the property to a non-null default such as string.Empty and declare the property as non nullable string.

Assume that accessing the property when it is null is a programming error, and throw an appropriate exception.

For the last case, you could do something like this:

```<code>private string? _name;

public string Name
{
    get
    {
        if (_name == null)
            throw new InvalidOperationException("Do not access Name without setting it to non-null or calling Init()");

        return _name;
    }

    set
    {
        if (value == null)
            throw new ArgumentNullException("value", "You cannot set Name to null.");

        _name = value;
    }
}
</code>```

This assumes that there's a method called Init() that can be called to initialise Name, but of course your code may vary.

Regardless of which of those approaches you take, you should really check for null in the property setter, as shown above.

Note that a more succinct way of writing the setter null check is:

```<code>set
{
    _name = value ?? throw new ArgumentNullException("value", "You cannot set Name to null.");
}
</code>```

Title: New c# nullable option

Body:
In new version of C# is default option nullable. I mean this

It's really good feature for me. But I don't understand one thing. Is property nullable by me or by program?

I know that this property should never be null because I fill it in the form and never set it as null. But in general it can be null. How should I mark it?

Example:

UserModel:

public string? Name { get; set; }

public string Name { get; set; } = null!

I'm really confused.

Body:
I know that this property should never be null because I fill it in
the form and never set it as null. But in general it can be null. How
should I mark it?

If it is set to non-null in the constructor, then you can declare it a string rather than string? because it really is guaranteed to never be null.

If, however, it is null after the constructor has run (and before any other methods are called) then it CAN be null and you should declare it as string?.

The dichotomy you face is that (from what you say) it should never be null when the class is used correctly - i.e. if the calling code does indeed call the method that initialises the property to non-null before accessing it, it will be guaranteed to be not null - which means you would like to declare it as a non-null string so that callers don't need to use the null-forgiving ! operator to suppress nullable warnings.

What to do in this case? Well I think you have three possibilities:

Declare the property as nullable: string? and let the callers suppress the nullable warning or check the value for null.

Initialise the property to a non-null default such as string.Empty and declare the property as non nullable string.

Assume that accessing the property when it is null is a programming error, and throw an appropriate exception.

For the last case, you could do something like this:

private string? _name;

public string Name
{
    get
    {
        if (_name == null)
            throw new InvalidOperationException("Do not access Name without setting it to non-null or calling Init()");

        return _name;
    }

    set
    {
        if (value == null)
            throw new ArgumentNullException("value", "You cannot set Name to null.");

        _name = value;
    }
}

This assumes that there's a method called Init() that can be called to initialise Name, but of course your code may vary.

Regardless of which of those approaches you take, you should really check for null in the property setter, as shown above.

Note that a more succinct way of writing the setter null check is:

set
{
    _name = value ?? throw new ArgumentNullException("value", "You cannot set Name to null.");
}


问:
What is the TypeScript type of failed useMutation requests?
Consider the following code:

```<code>const {
  mutate: storeData,
} = useMutation(...) // useMutation from @vue/apollo-composable

const sendForm = handleSubmit(async (values) => {
  try {
    const result = await storeData()
    console.log(result)
  } catch (e) { // <---- what is the TypeScript type of e?
    ...
  }
})
</code>```

I want to annotate the e parameter of catch(e) with its TypeScript type - but which type is it? If you know the solution, if possible also explain how I could have figured that out myself, thanks!

答:
Inspecting the code of apollo, the type is ApolloError

https://github.com/vuejs/apollo/blob/526fbacc18861029494963d03a88d7995f1cfc1f/packages/vue-apollo-composable/src/util/toApolloError.ts#L4

You can try thees two stategies to infer the type

```<code>import { ApolloError, isApolloError } from '@apollo/client/core'
import { GraphQLErrors } from '@apollo/client/errors'

export function toApolloError (error: unknown): ApolloError {
  if (!(error instanceof Error)) {
    return new ApolloError({
      networkError: Object.assign(new Error(), { originalError: error }),
      errorMessage: String(error),
    })
  }

  if (isApolloError(error)) {
    return error
  }

  return new ApolloError({ networkError: error, errorMessage: error.message })
}

export function resultErrorsToApolloError (errors: GraphQLErrors): ApolloError {
  return new ApolloError({
    graphQLErrors: errors,
    errorMessage: `GraphQL response contains errors: ${errors.map((e: any) => e.message).join(' | ')}`,
  })
}
</code>```

Try something like this:

```<code>try  {
  const result = await storeData()
  console.log(result)
}  catch  (error: ApolloError)  {
  // your stuff
}

// or

try  {
  const result = await storeData()
  console.log(result)
}  catch  (error)  {
if (error instanceof ApolloError) {

  // your stuff
}else {
  // other stuff
}
</code>```

Body:
Consider the following code:

const {
  mutate: storeData,
} = useMutation(...) // useMutation from @vue/apollo-composable

const sendForm = handleSubmit(async (values) => {
  try {
    const result = await storeData()
    console.log(result)
  } catch (e) { // <---- what is the TypeScript type of e?
    ...
  }
})

I want to annotate the e parameter of catch(e) with its TypeScript type - but which type is it? If you know the solution, if possible also explain how I could have figured that out myself, thanks!

Body:
Inspecting the code of apollo, the type is ApolloError

https://github.com/vuejs/apollo/blob/526fbacc18861029494963d03a88d7995f1cfc1f/packages/vue-apollo-composable/src/util/toApolloError.ts#L4

You can try thees two stategies to infer the type

import { ApolloError, isApolloError } from '@apollo/client/core'
import { GraphQLErrors } from '@apollo/client/errors'

export function toApolloError (error: unknown): ApolloError {
  if (!(error instanceof Error)) {
    return new ApolloError({
      networkError: Object.assign(new Error(), { originalError: error }),
      errorMessage: String(error),
    })
  }

  if (isApolloError(error)) {
    return error
  }

  return new ApolloError({ networkError: error, errorMessage: error.message })
}

export function resultErrorsToApolloError (errors: GraphQLErrors): ApolloError {
  return new ApolloError({
    graphQLErrors: errors,
    errorMessage: `GraphQL response contains errors: ${errors.map((e: any) => e.message).join(' | ')}`,
  })
}

Try something like this:

try  {
  const result = await storeData()
  console.log(result)
}  catch  (error: ApolloError)  {
  // your stuff
}

// or

try  {
  const result = await storeData()
  console.log(result)
}  catch  (error)  {
if (error instanceof ApolloError) {

  // your stuff
}else {
  // other stuff
}


问:
New wwwroot folders and content deleted during build
Via VS2022 I have created a subfolder under wwwroot/js and dragged the js files required into that new folder.

During build, I can see that new folder and contents "disappear" from Solution Explorer and also the new folder is deleted from disk ......

What could I be doing wrong?

答:
Silly Silly Me !

I have been working with Blazor for so long (no javascript) - I had forgotten that during the build of this old website Gulp was clearing and repopulating wwwroot !

Simply adding the folder and content via Solution Explorer was completely wrong!

I feel such an idiot!


问:
Confused about the way Leetcode displays binary trees?
I'm currently practicing binary tree exercises on Leetcode and am often confused. I'm currently solving this excercise. And one of the test cases is displayed as [1, null,2, null,3]. I can not figure out what kind of binary tree this should be. When printing the tree does Leetcode simply omit some null nodes? Does the node with the value 3 belong to the node with the value 2?

答:
When you do a level-ordered traversal of the tree, the array elements go in each open slot you encounter, so:</p>
```<code>           1
          / \
       null  2
            / \
         null  3
</code>```

Body:
When you do a level-ordered traversal of the tree, the array elements go in each open slot you encounter, so:

           1
          / \
       null  2
            / \
         null  3


问:
Heroku not recognized as an internal or external command (Windows)
Following this heroku tutorial to launch an app on heroku. But when I use the command heroku create, it says it's not recognized. I added C:\Program Files\Heroku to my PATH. How do I fix this?

答: There was another post here Heroku won't load within Visual Studio Code I did that and it worked for me. After uninstalling and npm i -g heroku</p>


问:
Calling C function from Raku that was compiled in C++ on Windows, Why is it not working?
I have this code in 64bit dll on Windows

```<code>#define TEMPLATENEST_API __declspec(dllexport)

extern  "C"  TEMPLATENEST_API  void templatenest_init(void** object);

 void templatenest_init(void** object)
{
    //TemmplNest
    *object =(void*) new TemplateNestClass();

}
</code>```

In raku,

```<code>sub templatenest_init(Pointer is rw) is native(dl) { * }

 my Pointer  $class_pointer;

 templatenest_init($class_pointer);
 templatenest_init($class_pointer)
</code>```

However, after this line, $class_pointer was 0.
Somehow the value of a the class pointer does not arrive in Raku.
I checked in a Debugger that *object was set to non zero value.

Signature of the exported function

2    1 00025621 templatenest_init = @ILT+5660(templatenest_init)

Minimal example:
Use Microsoft VIsual studio 2019 compile as dll library 64 bit

raku:

```<code>use v6;
use Data::Dump;
use NativeCall;

#constant dl = 'D:\m\cpp\TemplateNest\template-nest-rakudl\TemplateNestDll.dll';

constant dl = 'D:\m\cpp\TemplateNest\x64\Debug\DllMinitest.dll';

sub get_dll_name()
{
     if $*VM.osname eq 'linux' {
        return 'templatenest';
     }
     else
{
      return dl;
}

}
sub templatenest_init(Pointer is rw) is native(get_dll_name) { * }

my Pointer $class_pointer;

  templatenest_init($class_pointer);
   say "{$class_pointer.Int}";

# it prints 0.

export.cpp:
#define TEMPLATENEST_API __declspec(dllexport)

class TemplateNestClass {

};

extern  "C"  TEMPLATENEST_API  void templatenest_init(void** object);

void templatenest_init(void** object)
{
    //TemmplNest
    *object = (void*) new TemplateNestClass();

}

dllmain:
// dllmain.cpp : Defines the entry point for the DLL application.

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
</code>```

答:
A work around seems to work.

```<code>extern  "C"  TEMPLATENEST_API  void templatenest_init(__int64 * object);

sub templatenest_init(int64 is rw ) is native(get_dll_name) { * }

my int64 $class_pointer;

templatenest_init($class_pointer);
</code>```

Actual answer:
The pointer needs to be initialised like this:
my Pointer $class_pointer = Pointer.new();

All Pointer stuff needs to be new-ed.
Another example:
my Pointer[Str] $html = Pointer[Str].new();

Body:
I have this code in 64bit dll on Windows

#define TEMPLATENEST_API __declspec(dllexport)

extern  "C"  TEMPLATENEST_API  void templatenest_init(void** object);

 void templatenest_init(void** object)
{
    //TemmplNest
    *object =(void*) new TemplateNestClass();

}

In raku,

sub templatenest_init(Pointer is rw) is native(dl) { * }

 my Pointer  $class_pointer;

 templatenest_init($class_pointer);
 templatenest_init($class_pointer)

However, after this line, $class_pointer was 0.
Somehow the value of a the class pointer does not arrive in Raku.
I checked in a Debugger that *object was set to non zero value.

Signature of the exported function

2    1 00025621 templatenest_init = @ILT+5660(templatenest_init)

Minimal example:
Use Microsoft VIsual studio 2019 compile as dll library 64 bit

raku:

use v6;
use Data::Dump;
use NativeCall;

#constant dl = 'D:\m\cpp\TemplateNest\template-nest-rakudl\TemplateNestDll.dll';

constant dl = 'D:\m\cpp\TemplateNest\x64\Debug\DllMinitest.dll';

sub get_dll_name()
{
     if $*VM.osname eq 'linux' {
        return 'templatenest';
     }
     else
{
      return dl;
}

}
sub templatenest_init(Pointer is rw) is native(get_dll_name) { * }

my Pointer $class_pointer;

  templatenest_init($class_pointer);
   say "{$class_pointer.Int}";

# it prints 0.

export.cpp:
#define TEMPLATENEST_API __declspec(dllexport)

class TemplateNestClass {

};

extern  "C"  TEMPLATENEST_API  void templatenest_init(void** object);

void templatenest_init(void** object)
{
    //TemmplNest
    *object = (void*) new TemplateNestClass();

}

dllmain:
// dllmain.cpp : Defines the entry point for the DLL application.

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Body:
A work around seems to work.

extern  "C"  TEMPLATENEST_API  void templatenest_init(__int64 * object);

sub templatenest_init(int64 is rw ) is native(get_dll_name) { * }

my int64 $class_pointer;

templatenest_init($class_pointer);

Actual answer:
The pointer needs to be initialised like this:
my Pointer $class_pointer = Pointer.new();

All Pointer stuff needs to be new-ed.
Another example:
my Pointer[Str] $html = Pointer[Str].new();


问:
Will php token_get_all() without TOKEN_PARSE ever throw ParseError?
php token_get_all(), when called with TOKEN_PARSE flag, will throw ParseError if it encounters bad syntax.

Without the TOKEN_PARSE flag, I have not seen it throw anything.

I am working without TOKEN_PARSE because I am dealing with these problems myself, and it is faster this way.

Is this reliable? If not, is there any php code I could throw at it to make it throw an error or exception?

I want to know this for a parser I am working on:

If an error or exception never occurs, I can drop the try/catch.

If an error or exception can occur, and I keep the try/catch, I want to add test coverage, which needs a reproducible example.

Thanks!

答: If you are using the TOKEN_PARSE flag token_get_all() can throw an exception like Parse error: syntax error when parsing an invalin php file


问:
Error handling on form load using OnError Resume Next
I am trying to catch error on form load so I can call a function. On Error Resume Next is not catching error. I am trying to catch an error using Set rs = CurrentDb.OpenRecordset("SELECT DonorName FROM tblDonations"). Is there a way around this? I am thinking that the Err.Number <> 0 is returning 0 hence the next line is skipped. This code works well in access 2019 and 365 but not in access 2016. Please see below:

```<code>Private Sub Form_Load()
On Error Resume Next
Dim rs As DAO.Recordset

Set rs = CurrentDb.OpenRecordset("SELECT DName FROM tblDonations")
If Err.Number <> 0 Then
    MsgBox "Error Number: " & Err.Number & " " & Err.Description & " Please relink to Backend file!", , "Backend missing"
    Call RelinkTables
End If
rs.Close
Set rs = Nothing

DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmMainform"
End Sub
</code>```

答:
You should be able to work around this behaviour.

Private Sub Form_Load()

Dim rs As Object

On Error Resume Next
Set rs = CurrentDb.OpenRecordset("SELECT DName FROM tblDonations")
On Error GoTo 0

If rs Is Nothing Then
    MsgBox "rs Is Nothing", , "Backend missing"
    Call RelinkTables
End If

'...

End Sub
```

Body:
I am trying to catch error on form load so I can call a function. On Error Resume Next is not catching error. I am trying to catch an error using Set rs = CurrentDb.OpenRecordset("SELECT DonorName FROM tblDonations"). Is there a way around this? I am thinking that the Err.Number <> 0 is returning 0 hence the next line is skipped. This code works well in access 2019 and 365 but not in access 2016. Please see below:

Private Sub Form_Load()
On Error Resume Next
Dim rs As DAO.Recordset

Set rs = CurrentDb.OpenRecordset("SELECT DName FROM tblDonations")
If Err.Number <> 0 Then
    MsgBox "Error Number: " & Err.Number & " " & Err.Description & " Please relink to Backend file!", , "Backend missing"
    Call RelinkTables
End If
rs.Close
Set rs = Nothing

DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmMainform"
End Sub


问:
Problem with Inheritance beetwen classes//java
I've been trying to use a constructor and functions from class Adding in class AddOwner (which inherits from class Adding).

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

public class Adding extends JFrame {

    protected JFrame frame;

    Adding(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.setSize(300, 500);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        frame.setVisible(true);
    }

    class AddingTextField extends JTextField{
        protected JTextField nameField;
        String textFieldContent;

        AddingTextField(String textFieldContent) {
            nameField = new JTextField(textFieldContent);
            nameField.setPreferredSize(new Dimension(200, 50));
            nameField.setFont(new Font("MV Boli", Font.PLAIN, 35));
        }
    }

    class AddingDropList  <T> extends JComboBox{
        protected JComboBox dropListContent;
        AddingDropList(){
            dropListContent=new JComboBox<>();
            dropListContent.setPreferredSize(new Dimension(200,50));
            dropListContent.setFont(new Font("MV Boli",Font.PLAIN,35));
        }

        public void addContentToDropList(T content){
            dropListContent.addItem(content);
        }

        public void removeContentFromDropList(T content){
            dropListContent.removeItem(content);
        }
    }

}
</code>```

class AddOwner:

```<code>public class AddOwner extends Adding{

    private AddingTextField name;
    private AddingTextField surname;
    private AddingTextField age;
    private AddingDropList gender;

    public AddOwner(){

        super();

        name=new AddingTextField("name");
        surname=new AddingTextField("surname");
        age =new AddingTextField("age");
        gender=new AddingDropList<String>();
        gender.addContentToDropList("Male");
        gender.addContentToDropList("Female");
        this.add(name);
        this.add(surname);
        this.add(age);
        this.add(gender);

    }
}
</code>```

Unfortunately, frame poped up without added components. I decided to discard construtor from class Adding and use at least classes from Adding clas to created objects AddingTextField and AddingDropList.

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

public class Adding extends JFrame {

    public class AddingTextField extends JTextField{
        protected JTextField nameField;
        String textFieldContent;

        AddingTextField(String textFieldContent) {
            nameField = new JTextField(textFieldContent);
            nameField.setPreferredSize(new Dimension(200, 50));
            nameField.setFont(new Font("MV Boli", Font.PLAIN, 35));
        }
    }

    public class AddingDropList  <T> extends JComboBox{
        protected JComboBox dropListContent;
        AddingDropList(){
            dropListContent=new JComboBox<>();
            dropListContent.setPreferredSize(new Dimension(200,50));
            dropListContent.setFont(new Font("MV Boli",Font.PLAIN,35));
        }

        public void addContentToDropList(T content){
            dropListContent.addItem(content);
        }

        public void removeContentFromDropList(T content){
            dropListContent.removeItem(content);
        }
    }

}
</code>```

Class AddOwner:

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

public class AddOwner extends Adding {
    private JFrame frame;
    private AddingTextField name;
    private AddingTextField surname;
    private AddingTextField age;
    private AddingDropList gender;

    AddOwner(){

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.setSize(300, 500);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        name=new AddingTextField("name");
        surname=new AddingTextField("surname");
        age =new AddingTextField("age");
        gender=new AddingDropList<String>();
        gender.addContentToDropList("Male");
        gender.addContentToDropList("Female");
        frame.add(name);
        frame.add(surname);
        frame.add(age);
        frame.add(gender);
        frame.setVisible(true);

    }
}
</code>```

Now it's been adding components, but it looks like that
enter image description here

Can anyone explain it to me, why it doesn't work?

答:
Give the Components you add specific sizes. Without them, they will all have minimum size (0 or very small).

Or use another LayoutManager that automatically adjusts its Components' sizes.

Body:
I've been trying to use a constructor and functions from class Adding in class AddOwner (which inherits from class Adding).

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

public class Adding extends JFrame {

    protected JFrame frame;

    Adding(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.setSize(300, 500);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        frame.setVisible(true);
    }

    class AddingTextField extends JTextField{
        protected JTextField nameField;
        String textFieldContent;

        AddingTextField(String textFieldContent) {
            nameField = new JTextField(textFieldContent);
            nameField.setPreferredSize(new Dimension(200, 50));
            nameField.setFont(new Font("MV Boli", Font.PLAIN, 35));
        }
    }

    class AddingDropList  <T> extends JComboBox{
        protected JComboBox dropListContent;
        AddingDropList(){
            dropListContent=new JComboBox<>();
            dropListContent.setPreferredSize(new Dimension(200,50));
            dropListContent.setFont(new Font("MV Boli",Font.PLAIN,35));
        }

        public void addContentToDropList(T content){
            dropListContent.addItem(content);
        }

        public void removeContentFromDropList(T content){
            dropListContent.removeItem(content);
        }
    }

}

class AddOwner:

public class AddOwner extends Adding{

    private AddingTextField name;
    private AddingTextField surname;
    private AddingTextField age;
    private AddingDropList gender;

    public AddOwner(){

        super();

        name=new AddingTextField("name");
        surname=new AddingTextField("surname");
        age =new AddingTextField("age");
        gender=new AddingDropList<String>();
        gender.addContentToDropList("Male");
        gender.addContentToDropList("Female");
        this.add(name);
        this.add(surname);
        this.add(age);
        this.add(gender);

    }
}

Unfortunately, frame poped up without added components. I decided to discard construtor from class Adding and use at least classes from Adding clas to created objects AddingTextField and AddingDropList.

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

public class Adding extends JFrame {

    public class AddingTextField extends JTextField{
        protected JTextField nameField;
        String textFieldContent;

        AddingTextField(String textFieldContent) {
            nameField = new JTextField(textFieldContent);
            nameField.setPreferredSize(new Dimension(200, 50));
            nameField.setFont(new Font("MV Boli", Font.PLAIN, 35));
        }
    }

    public class AddingDropList  <T> extends JComboBox{
        protected JComboBox dropListContent;
        AddingDropList(){
            dropListContent=new JComboBox<>();
            dropListContent.setPreferredSize(new Dimension(200,50));
            dropListContent.setFont(new Font("MV Boli",Font.PLAIN,35));
        }

        public void addContentToDropList(T content){
            dropListContent.addItem(content);
        }

        public void removeContentFromDropList(T content){
            dropListContent.removeItem(content);
        }
    }

}

Class AddOwner:

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

public class AddOwner extends Adding {
    private JFrame frame;
    private AddingTextField name;
    private AddingTextField surname;
    private AddingTextField age;
    private AddingDropList gender;

    AddOwner(){

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.setSize(300, 500);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        name=new AddingTextField("name");
        surname=new AddingTextField("surname");
        age =new AddingTextField("age");
        gender=new AddingDropList<String>();
        gender.addContentToDropList("Male");
        gender.addContentToDropList("Female");
        frame.add(name);
        frame.add(surname);
        frame.add(age);
        frame.add(gender);
        frame.setVisible(true);

    }
}

Now it's been adding components, but it looks like that
enter image description here

Can anyone explain it to me, why it doesn't work?


问:
Mongoose - Code Outside of Query Executed First
I'm using Node JS and am making a request to my MongoDB server. The problem is the 2 console logs outside of my Data.findOne() seem to be executed before the contents in the query.

```<code>Data.findOne({_id: "---"}, (err, docs) => {
    item1 = docs.projects[1]
    item2 = docs.projects[2]
    console.log(item1)
    console.log(item2)
})
console.log(item1)
console.log(item2)
</code>```

This is causing errors later on in my code as it's trying to access the contents in item1 and item2 but they are undefined. It's not an issue of whether or not the object actually exists because the logs inside the function return objects, it's just that the contents of the functions are executed at the wrong time.

答:
You can use promise style instead of call back style.

```<code>const SomeFunction = async() => {
 try {
    const docs = await Data.findOne({_id: "---"}).lean()
    const item1 = docs.projects[1]
    const item2 = docs.projects[2]
    console.log(item1)
    console.log(item2)
 } catch(err) {
      console.log(error)
 }
}
</code>```

Bonus: Faster Query with lean()

Body:
I'm using Node JS and am making a request to my MongoDB server. The problem is the 2 console logs outside of my Data.findOne() seem to be executed before the contents in the query.

Data.findOne({_id: "---"}, (err, docs) => {
    item1 = docs.projects[1]
    item2 = docs.projects[2]
    console.log(item1)
    console.log(item2)
})
console.log(item1)
console.log(item2)

This is causing errors later on in my code as it's trying to access the contents in item1 and item2 but they are undefined. It's not an issue of whether or not the object actually exists because the logs inside the function return objects, it's just that the contents of the functions are executed at the wrong time.

Body:
You can use promise style instead of call back style.

const SomeFunction = async() => {
 try {
    const docs = await Data.findOne({_id: "---"}).lean()
    const item1 = docs.projects[1]
    const item2 = docs.projects[2]
    console.log(item1)
    console.log(item2)
 } catch(err) {
      console.log(error)
 }
}

Bonus: Faster Query with lean()


问:
How to perform Grid Search on a multi-label classification problem?
I am learning Scikit-Learn and I am trying to perform a grid search on a multi label classification problem. This is what I wrote:

```<code>from sklearn.model_selection import GridSearchCV

param_grid = [
    {'randomforestclassifier__n_estimators': [3, 10, 30], 'randomforestclassifier__max_features': [2, 4, 5, 8]},
    {'randomforestclassifier__bootstrap': [False], 'randomforestclassifier__n_estimators': [3, 10], 'randomforestclassifier__max_features': [2, 3, 4]}
]

rf_classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)
grid_search = GridSearchCV(rf_classifier, param_grid=param_grid, cv=5, scoring = 'f1_micro')
grid_search.fit(X_train_prepared, y_train)
</code>```

However when I run it I get the following error:

```<code>ValueError: Invalid parameter randomforestclassifier for estimator
OneVsRestClassifier(estimator=Pipeline(steps=[('randomforestclassifier',
RandomForestClassifier(random_state=42))])). Check the list of available parameters
with `estimator.get_params().keys()`.
</code>```

I tried to run also the grid_search.estimator.get_params().keys() command but I just get a list of parameters containing the ones that I have written, therefore I am not sure what I should do.

Would you be able to suggest what the issue is and how I can run the grid search properly?

答:
You would have been able to define param_grid as you did in case rf_classifier was a Pipeline object. Quoting the Pipeline's docs

The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters. For this, it enables setting parameters of the various steps using their names and the parameter name separated by a '__'.

In your case, instead, rf_classifier is OneVsRestClassifier instance. Therefore, before setting the parameters for the RFC, you'll need to be able to  access the pipeline instance, which you can do via OneVsRestClassifier estimator's parameter, as follows:

```<code>param_grid = [
    {'estimator__randomforestclassifier__n_estimators': [3, 10, 30],
     'estimator__randomforestclassifier__max_features': [2, 4, 5, 8]
    },
    {'estimator__randomforestclassifier__bootstrap': [False],
     'estimator__randomforestclassifier__n_estimators': [3, 10],
     'estimator__randomforestclassifier__max_features': [2, 3, 4]
    }
]
</code>```

Body:
I am learning Scikit-Learn and I am trying to perform a grid search on a multi label classification problem. This is what I wrote:

from sklearn.model_selection import GridSearchCV

param_grid = [
    {'randomforestclassifier__n_estimators': [3, 10, 30], 'randomforestclassifier__max_features': [2, 4, 5, 8]},
    {'randomforestclassifier__bootstrap': [False], 'randomforestclassifier__n_estimators': [3, 10], 'randomforestclassifier__max_features': [2, 3, 4]}
]

rf_classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)
grid_search = GridSearchCV(rf_classifier, param_grid=param_grid, cv=5, scoring = 'f1_micro')
grid_search.fit(X_train_prepared, y_train)

However when I run it I get the following error:

ValueError: Invalid parameter randomforestclassifier for estimator
OneVsRestClassifier(estimator=Pipeline(steps=[('randomforestclassifier',
RandomForestClassifier(random_state=42))])). Check the list of available parameters
with `estimator.get_params().keys()`.

I tried to run also the grid_search.estimator.get_params().keys() command but I just get a list of parameters containing the ones that I have written, therefore I am not sure what I should do.

Would you be able to suggest what the issue is and how I can run the grid search properly?

Body:
You would have been able to define param_grid as you did in case rf_classifier was a Pipeline object. Quoting the Pipeline's docs

The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters. For this, it enables setting parameters of the various steps using their names and the parameter name separated by a '__'.

In your case, instead, rf_classifier is OneVsRestClassifier instance. Therefore, before setting the parameters for the RFC, you'll need to be able to  access the pipeline instance, which you can do via OneVsRestClassifier estimator's parameter, as follows:

param_grid = [
    {'estimator__randomforestclassifier__n_estimators': [3, 10, 30],
     'estimator__randomforestclassifier__max_features': [2, 4, 5, 8]
    },
    {'estimator__randomforestclassifier__bootstrap': [False],
     'estimator__randomforestclassifier__n_estimators': [3, 10],
     'estimator__randomforestclassifier__max_features': [2, 3, 4]
    }
]


问:
How can I add multiple conditions in react?
I have button Description. When clicked description is displayed. Now I want to add Read more/less on description.

With the belpw code, I do not see button Description, description is displayed directly

Flow- Display button-> On click-> Show 200 character text (With Read more option)

```<code>  const [readMore, setReadMore] = useState(false);

  const [displaydescription, setDisplayDescription] = useState(false);
  const clickHandler = () => {
    setDisplayDescription(true);
  };

 <p>
          {displaydescription || readMore
            ? description
            : `${description.substring(0, 200)}`}
        </p>
</code>```

答:
The syntax to add a condition in React jsx is {condition &&  }
so you could try</p>
```<code>{ description && !readmore
  <p> `${description.substring(0, 200)}` <p>
}
{ description && readmore
  <p> `${description}` <p>
}
</code>```

Body:
I have button Description. When clicked description is displayed. Now I want to add Read more/less on description.

With the belpw code, I do not see button Description, description is displayed directly

Flow- Display button-> On click-> Show 200 character text (With Read more option)

  const [readMore, setReadMore] = useState(false);

  const [displaydescription, setDisplayDescription] = useState(false);
  const clickHandler = () => {
    setDisplayDescription(true);
  };

          {displaydescription || readMore
            ? description
            : `${description.substring(0, 200)}`}

Body:
The syntax to add a condition in React jsx is {condition &&  }
so you could try

{ description && !readmore
  <p> `${description.substring(0, 200)}` <p>
}
{ description && readmore
  <p> `${description}` <p>
}


问:
jquery ui .autocomplete() not firing when same letter entered after blur()
Example code here: http://jsbin.com/etaziy (using http://jqueryui.com/demos/autocomplete/)

If you type in a 'j' you get the 3 names, 'John' 'Jack' and 'Joe'. If you then blur away, I clear the input, just by making the inputs val(''). Then if you go back to the input, and type a 'j' again, nothing happens? It's not until you type a second matching letter that you get the popup showing.

My example might seem a bit odd, but essentially this is a really cut back version of what I'm working on. I need to clear the input after a blur(), and clear it after a selection is made. Doing this is making subsequent selections look buggy.

I'm partly thinking this is intended functionality, but for my purpose, its not what i want. I really need the popup with the list to show as soon as any letter is typed.

Cheers.

答:
The problem is that the autocomplete keeps track of the value it is matching on internally, so when you first type j it sets this internal value to 'j' and then it wasn't being reset to the empty string when you changed the input to be empty.

After looking at the autocomplete source I wasn't able to find out how to directly access the internal variable, but you can force the autocomplete to update it for you by running another search once you've changed the input to be empty (and with a length of zero it won't actually do the search).

```<code>$(function() {
    $("#search").autocomplete({
                source: data,
                change: function() { // Triggered when the field is blurred, if the value has changed; ui.item refers to the selected item.
                        $("#search").val("");
                        $("#search").autocomplete("search", "");    //THIS IS THE NEW LINE THAT MAKES IT HAPPY
                }
        });
});
</code>```

Body:
The problem is that the autocomplete keeps track of the value it is matching on internally, so when you first type j it sets this internal value to 'j' and then it wasn't being reset to the empty string when you changed the input to be empty.

After looking at the autocomplete source I wasn't able to find out how to directly access the internal variable, but you can force the autocomplete to update it for you by running another search once you've changed the input to be empty (and with a length of zero it won't actually do the search).

$(function() {
    $("#search").autocomplete({
                source: data,
                change: function() { // Triggered when the field is blurred, if the value has changed; ui.item refers to the selected item.
                        $("#search").val("");
                        $("#search").autocomplete("search", "");    //THIS IS THE NEW LINE THAT MAKES IT HAPPY
                }
        });
});