问:
Integrating a custom function in Django
I would like to access and print metadata (attributes and values) served by an ERDDAP server, which is a variety of OPeNDAP, on my Django website.

so I prepared a simple example function called get_conventions to access a metadata field on this public server hosting data and metadata. To get started, I install the required packages:

$ pip install pandas erddapy
```
<p>and then,</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from erddapy import ERDDAP

def get_conventions(dataset_id):
    e = ERDDAP(server='https://gliders.ioos.us/erddap/', protocol='tabledap', response='csv')
    url = e.get_info_url(dataset_id, response='csv')
    df = pd.read_csv(url)

    # this replace spaces with underscores in column names
    df.columns = [col_name.replace(' ', '_') for col_name in df.columns]

    conventions = df[df.Attribute_Name == 'Conventions'].Value
    return conventions
</code>```

Using a Python interpreter, one could call the function like this with this sample dataset id as an argument (amelia-20180501T0000), which is found on the server; the output follows:

>>> get_conventions('amelia-20180501T0000')
6    Unidata Dataset Discovery v1.0, COARDS, CF-1.6
Name: Value, dtype: object
>>>
```

I would like my website to print on a webpage the output of the above function.

I can print the argument string in a page (model.py, views.py and a related html templates - those being similar to the Django tutorial), but I am unsure how to refer the argument to the function (and expect a return) or how/where to integrate the function in the Django structure.

The argument is stored in a local database which can be referred using models/views/template

But I am unsure how to integrate the part involving the function in Django?

答:
I was able to make this work after reading this, by D. Patel.

It involved adding the following to the file named services.py which was placed an app subfolder titled templatetags. This is where the get_conventions custom function reside:

from django import template
...

register = template.Library()

@register.filter
def get_conventions(dataset_id):
...
    return conventions
```
<p>and in the template, I had to load the <code>services</code> file and add the following to the html template:</p>
<pre class="lang-py prettyprint-override"><code>{% load services %}
{% block content %}
    <p><strong>Conventions:</strong> {{ station.dataset_id | get_conventions }}</p>
...
{% endblock %}
</code>```

station.dataset_id being the argument for the get_conventions function paired | with the return value

and it worked as intended. It was quite straightforward.

Title: Integrating a custom function in Django

Body:
I would like to access and print metadata (attributes and values) served by an ERDDAP server, which is a variety of OPeNDAP, on my Django website.

so I prepared a simple example function called get_conventions to access a metadata field on this public server hosting data and metadata. To get started, I install the required packages:

$ pip install pandas erddapy

and then,

import pandas as pd
from erddapy import ERDDAP

def get_conventions(dataset_id):
    e = ERDDAP(server='https://gliders.ioos.us/erddap/', protocol='tabledap', response='csv')
    url = e.get_info_url(dataset_id, response='csv')
    df = pd.read_csv(url)

    # this replace spaces with underscores in column names
    df.columns = [col_name.replace(' ', '_') for col_name in df.columns]

    conventions = df[df.Attribute_Name == 'Conventions'].Value
    return conventions

Using a Python interpreter, one could call the function like this with this sample dataset id as an argument (amelia-20180501T0000), which is found on the server; the output follows:

>>> get_conventions('amelia-20180501T0000')
6    Unidata Dataset Discovery v1.0, COARDS, CF-1.6
Name: Value, dtype: object
>>>

I would like my website to print on a webpage the output of the above function.

I can print the argument string in a page (model.py, views.py and a related html templates - those being similar to the Django tutorial), but I am unsure how to refer the argument to the function (and expect a return) or how/where to integrate the function in the Django structure.

The argument is stored in a local database which can be referred using models/views/template

But I am unsure how to integrate the part involving the function in Django?

Body:
I was able to make this work after reading this, by D. Patel.

It involved adding the following to the file named services.py which was placed an app subfolder titled templatetags. This is where the get_conventions custom function reside:

from django import template
...

register = template.Library()

@register.filter
def get_conventions(dataset_id):
...
    return conventions

and in the template, I had to load the services file and add the following to the html template:

{% load services %}
{% block content %}
    <p><strong>Conventions:</strong> {{ station.dataset_id | get_conventions }}</p>
...
{% endblock %}

station.dataset_id being the argument for the get_conventions function paired | with the return value

and it worked as intended. It was quite straightforward.


来源: stackexchange

问:
Converting unsigned to signed integers (Using Excel formulas or Power Query)
I have a list of unsigned 32-bit unsigned integers that actually are supposed to represent 32-bit signed integers.
For example 62714 = binary 1111010011111010 = signed -2822 when interpreted as two's complement
Basically I am trying find some formula to get from 62714 to -2822

The solution listed here does not seem to work:  https://ocroquette.wordpress.com/2015/10/26/converting-unsigned-to-signed-integers-using-powershell-or-excel/

答:
It appears that you are using 16 bit signed integers, so you could do:</p>
```<code>=MOD(A1+2^15,2^15)-2^15
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It appears that you are using 16 bit signed integers, so you could do:

=MOD(A1+2^15,2^15)-2^15


问:
How do I set the initial value of an accumulator in KDB?
I've written a function r that represents a functional state s update, of the form s: r[s;q]

I'm trying to get it to scan a list of integers q, but the problem I'm getting is that the application of scan / consumes the first and second digits of the list, rather than the initial state s. The result should be a list of states.

What am I doing wrong?

Actual code:

```<code>a: 5+cos (til 20)
s: `peg`ent`exi!3#enlist[::]
r: {[s;q]
  l: 0.9; h: 1.1;
  init: `peg`ent`exi!({null x};{null x}; {null x});
  s1: `peg`ent`exi!({not null x};{null x}; {null x});
  s2: `peg`ent`exi!({not null x};{not null x}; {null x});

  s: $[all init@'s; s, enlist[`peg]!enlist[q];s];
  s: $[(all s1@'s) & q<l*s[`peg]; s, enlist[`ent]!enlist[q];s];
  s: $[(all s2@'s) & q>h*s[`peg]; s, enlist[`exi]!enlist[q];s];
  s
  }

r scan a
</code>```

答:
The answer to this was to set the first value of the list to the state:</p>
```<code>r scan enlist[s], a
</code>```

Body:
I've written a function r that represents a functional state s update, of the form s: r[s;q]

I'm trying to get it to scan a list of integers q, but the problem I'm getting is that the application of scan / consumes the first and second digits of the list, rather than the initial state s. The result should be a list of states.

What am I doing wrong?

Actual code:

a: 5+cos (til 20)
s: `peg`ent`exi!3#enlist[::]
r: {[s;q]
  l: 0.9; h: 1.1;
  init: `peg`ent`exi!({null x};{null x}; {null x});
  s1: `peg`ent`exi!({not null x};{null x}; {null x});
  s2: `peg`ent`exi!({not null x};{not null x}; {null x});

  s: $[all init@'s; s, enlist[`peg]!enlist[q];s];
  s: $[(all s1@'s) & q<l*s[`peg]; s, enlist[`ent]!enlist[q];s];
  s: $[(all s2@'s) & q>h*s[`peg]; s, enlist[`exi]!enlist[q];s];
  s
  }

r scan a

Body:
The answer to this was to set the first value of the list to the state:

r scan enlist[s], a


问:
module has no exports on my new npm package that I publish
I just recently try to create new npm package. On my imports, it said module has no exports. I've export my component in index.js inside dist folder.
This is my project structure

```<code>
- dist
  - components
    - MyComponent.tsx
  - index.js

package.json

</code>```

My index.js before compile

```<code>import MyComponent from "./components/MyComponent";

export {MyComponent}
</code>```

My package.json

```<code>{
  "name": "my-test-npm",
  "homepage": "https://github.com/ganinw13120/my-test-npm",
  "main": "dist/index.js",
  "module": "dist/index.js",
  "bin": "dist/index.js",
  "version": "0.1.13",
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "@types/jest": "^26.0.24",
    "@types/node": "^12.20.37",
    "@types/react": "^17.0.37",
    "@types/react-dom": "^17.0.11",
    "@types/uuid": "^8.3.3",
    "bignumber.js": "^9.0.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.3",
    "typescript": "^4.5.3",
    "uuid": "^8.3.2",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/cli": "^7.16.8",
    "@babel/core": "^7.16.7",
    "@babel/preset-env": "^7.16.8",
    "@types/styled-components": "^5.1.17"
  },
  "files": [
    "dist",
    "package.json"
  ]
}
</code>```

On my error, it also said Field 'browser' doesn't contain a valid alias configuration then my component path on dist folder. It seem like it cannot find my component in dist folder, which is already included.

答:
I am facing the similar problem recently. I check my project config and your config, you can try to add config in the npm package source code package.json:

```<code>"type": "module",
</code>```

what I am imported the public npm package component I created like this:

```<code>import { ResponseHandler } from "js-wheel/dist/index";
</code>```

and export in the npm package source index.ts like this:

```<code>import {ResponseHandler} from "./net/rest/ResponseHandler";

export {
    ResponseHandler
}
</code>```

I take days to fix this problem and finally it works.

Body:
I just recently try to create new npm package. On my imports, it said module has no exports. I've export my component in index.js inside dist folder.
This is my project structure

- dist
  - components
    - MyComponent.tsx
  - index.js

package.json

My index.js before compile

import MyComponent from "./components/MyComponent";

export {MyComponent}

My package.json

{
  "name": "my-test-npm",
  "homepage": "https://github.com/ganinw13120/my-test-npm",
  "main": "dist/index.js",
  "module": "dist/index.js",
  "bin": "dist/index.js",
  "version": "0.1.13",
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "@types/jest": "^26.0.24",
    "@types/node": "^12.20.37",
    "@types/react": "^17.0.37",
    "@types/react-dom": "^17.0.11",
    "@types/uuid": "^8.3.3",
    "bignumber.js": "^9.0.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.3",
    "typescript": "^4.5.3",
    "uuid": "^8.3.2",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/cli": "^7.16.8",
    "@babel/core": "^7.16.7",
    "@babel/preset-env": "^7.16.8",
    "@types/styled-components": "^5.1.17"
  },
  "files": [
    "dist",
    "package.json"
  ]
}

On my error, it also said Field 'browser' doesn't contain a valid alias configuration then my component path on dist folder. It seem like it cannot find my component in dist folder, which is already included.

Body:
I am facing the similar problem recently. I check my project config and your config, you can try to add config in the npm package source code package.json:

"type": "module",

what I am imported the public npm package component I created like this:

import { ResponseHandler } from "js-wheel/dist/index";

and export in the npm package source index.ts like this:

import {ResponseHandler} from "./net/rest/ResponseHandler";

export {
    ResponseHandler
}

I take days to fix this problem and finally it works.


问:
How to use the strncpy function in the 3rd array of 2d array strings
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char d2arr[6][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];
    memset(d3arr, NULL, sizeof(d3arr));

    strncpy(d2arr[0], d3arr[0][0], sizeof(7));
    strncpy(d2arr[1], d3arr[0][1], sizeof(7));
    strncpy(d2arr[2], d3arr[0][2], sizeof(7));
    strncpy(d2arr[3], d3arr[0][3], sizeof(7));
    strncpy(d2arr[4], d3arr[0][4], sizeof(7));

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    return 0;
}
</code>```

There is no error message, and the results do not come out, so I ask questions.
Please let me know why the string in the 2D array is not copied.

答:
Your code does not behave as expected:

the first argument to strncpy is the destination pointer.

the second argument is the source pointer

the third argument is the size in bytes at the destination to stop the copy or up to which to pad with null bytes if the source string is shorter. You pass sizeof(7) which is most likely 4 on your system, whereas you should just pass 7.

Note however that strncpy is a very poorly understood function that does not behave as most programmers expect and is error prone for everyone. Here is sound advice about this function: Stop using strncpy already!

In your case, calling strcpy or even memcpy works fine.

Also do not use NULL for a null byte as the second argument to memcpy: use '\0' or 0.

```<code>#include <stdio.h>
#include <string.h>

int main(void) {
    char d2arr[][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];

    memset(d3arr, '\0', sizeof(d3arr));

    strcpy(d3arr[0][0], d2arr[0]);
    strcpy(d3arr[0][1], d2arr[1]);
    strcpy(d3arr[0][2], d2arr[2]);
    strcpy(d3arr[0][3], d2arr[3]);
    strcpy(d3arr[0][4], d2arr[4]);

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    memcpy(d3arr[1][0], d2arr[0], 7);
    memcpy(d3arr[1][1], d2arr[1], 7);
    memcpy(d3arr[1][2], d2arr[2], 7);
    memcpy(d3arr[1][3], d2arr[3], 7);
    memcpy(d3arr[1][4], d2arr[4], 7);

    printf("%s\n", d3arr[1][0]);
    printf("%s\n", d3arr[1][1]);
    printf("%s\n", d3arr[1][2]);
    printf("%s\n", d3arr[1][3]);
    printf("%s\n", d3arr[1][4]);

    return 0;
}
</code>```

Body:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char d2arr[6][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];
    memset(d3arr, NULL, sizeof(d3arr));

    strncpy(d2arr[0], d3arr[0][0], sizeof(7));
    strncpy(d2arr[1], d3arr[0][1], sizeof(7));
    strncpy(d2arr[2], d3arr[0][2], sizeof(7));
    strncpy(d2arr[3], d3arr[0][3], sizeof(7));
    strncpy(d2arr[4], d3arr[0][4], sizeof(7));

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    return 0;
}

There is no error message, and the results do not come out, so I ask questions.
Please let me know why the string in the 2D array is not copied.

Body:
Your code does not behave as expected:

the first argument to strncpy is the destination pointer.

the second argument is the source pointer

the third argument is the size in bytes at the destination to stop the copy or up to which to pad with null bytes if the source string is shorter. You pass sizeof(7) which is most likely 4 on your system, whereas you should just pass 7.

Note however that strncpy is a very poorly understood function that does not behave as most programmers expect and is error prone for everyone. Here is sound advice about this function: Stop using strncpy already!

In your case, calling strcpy or even memcpy works fine.

Also do not use NULL for a null byte as the second argument to memcpy: use '\0' or 0.

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

int main(void) {
    char d2arr[][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];

    memset(d3arr, '\0', sizeof(d3arr));

    strcpy(d3arr[0][0], d2arr[0]);
    strcpy(d3arr[0][1], d2arr[1]);
    strcpy(d3arr[0][2], d2arr[2]);
    strcpy(d3arr[0][3], d2arr[3]);
    strcpy(d3arr[0][4], d2arr[4]);

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    memcpy(d3arr[1][0], d2arr[0], 7);
    memcpy(d3arr[1][1], d2arr[1], 7);
    memcpy(d3arr[1][2], d2arr[2], 7);
    memcpy(d3arr[1][3], d2arr[3], 7);
    memcpy(d3arr[1][4], d2arr[4], 7);

    printf("%s\n", d3arr[1][0]);
    printf("%s\n", d3arr[1][1]);
    printf("%s\n", d3arr[1][2]);
    printf("%s\n", d3arr[1][3]);
    printf("%s\n", d3arr[1][4]);

    return 0;
}


问:
Probability of a roll dice
I generated 1,000,000 random number draws using the random module

```<code>import random
liste = []
for i in range(0, 1000000):
liste.append(random.uniform(0,1))
</code>```

Now I have to store the values obtained in a histogram at 6 bins using the bins option.
And using if/else conditions on the list items, write a algorithm to simulate the result of 1,000,000 dice rolls.
Then I have to calculate the frequency of occurrence of each value and compare it to the expected probability p = 1/6.

Does anyone know how to do this please I have no idea...

Thanks in advance!

edit: concerning the bins options

they talk about this :

```<code>import matplotlib.pyplot as plt
import numpy as np
# Création de la figure et des axes
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
axs.hist(valeurs, bins=np.arange(0.5, 7.5, 1), ec="black")
axs.set_title("Résultats jet dé")
axs.set_xlabel("Valeur dé")
</code>```

After using @Roland_Smith's program it gives me this

```<code> #import random
 #liste = []
 #for i in range(0, 1000000):
 #    liste.append(random.uniform(0,1))
 import random
 liste = random.choices((1,2,3,4,5,6), k=1000000)
 import collections
 c = collections.Counter(liste)
 print(c)

 p = [j/1e6 for j in c.values()]
 print(p)

 import matplotlib.pyplot as plt
 import numpy as np
 # Création de la figure et des axes
 fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
 # Ajout de l'histogramme
 axs.hist(c, bins=np.arange(0.5, 7.5, 1), ec="black")
 axs.set_title("Résultats jet dé")
 axs.set_xlabel("Valeur dé")
</code>```

but the problem is that my histogram looks like this

is it normal because each number has the same probability of appearing or is it not normal?

edit for tdy

```<code>import matplotlib.pyplot as plt
import numpy as np
# Création de la figure et des axes
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
axs.hist(c,ec="black")
axs.set_title("Résultats jet dé")
axs.set_xlabel("Valeur dé")
</code>```

edit after help for @JohanC

```<code>#import random
#liste = []
#for i in range(0, 1000000):
#    liste.append(random.uniform(0,1))
import random
liste = random.choices((1,2,3,4,5,6), k=1000000)
import collections
c = collections.Counter(liste)
print(c)

p = [j/1e6 for j in c.values()]
print(p)

import matplotlib.pyplot as plt
import numpy as np
plt.bar(c.keys(), c.values())

# Création de la figure et des axes
#fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
#axs.hist(c,ec="black")
#axs.set_title("Résultats jet dé")
#axs.set_xlabel("Valeur dé")
</code>```

i get a value of 160000 for each dice face, i.e. 6. but 6*160000+960000 i shouldn't get the number of rolls, i.e. 1000000?

答:
Dice rolls produce an integer value.

So using random.uniform (which returns a float) is not the right way.

Try:

```<code>import random
liste = random.choices((1,2,3,4,5,6), k=1000000)
</code>```

Then, I'd use collections.Counter to count the values:

```<code>import collections
c = collections.Counter(liste)
print(c)
</code>```

This would get you something like:

```<code>Counter({6: 167399, 5: 167083, 2: 166789, 3: 166548, 1: 166236, 4: 165945})
</code>```

Calculating the probability:

```<code>p = [j/1e6 for j in c.values()]
</code>```

This yields:

```<code>[0.167083, 0.165945, 0.167399, 0.166789, 0.166548, 0.166236]
</code>```

For plotting;

```<code>import matplotlib.pyplot as plt

plt.bar(c.keys(),p)
plt.show()
</code>```

It will look something like this:

The reason that all bars look about the same is because they are.

Let's check the difference between p and the probability of a fair dice, which is 1/6:

```<code>[round(j-1/6, 6) for j in p]
</code>```

This gives:

```<code>[0.000416, -0.000722, 0.000732, 0.000122, -0.000119, -0.000431]
</code>```

So the actual counted probability is pretty close to that of a fair dice.

Title: Probability of a roll dice

Body:
I generated 1,000,000 random number draws using the random module

import random
liste = []
for i in range(0, 1000000):
liste.append(random.uniform(0,1))

Now I have to store the values obtained in a histogram at 6 bins using the bins option.
And using if/else conditions on the list items, write a algorithm to simulate the result of 1,000,000 dice rolls.
Then I have to calculate the frequency of occurrence of each value and compare it to the expected probability p = 1/6.

Does anyone know how to do this please I have no idea...

Thanks in advance!

edit: concerning the bins options

they talk about this :

import matplotlib.pyplot as plt
import numpy as np
# Création de la figure et des axes
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
axs.hist(valeurs, bins=np.arange(0.5, 7.5, 1), ec="black")
axs.set_title("Résultats jet dé")
axs.set_xlabel("Valeur dé")

After using @Roland_Smith's program it gives me this

 #import random
 #liste = []
 #for i in range(0, 1000000):
 #    liste.append(random.uniform(0,1))
 import random
 liste = random.choices((1,2,3,4,5,6), k=1000000)
 import collections
 c = collections.Counter(liste)
 print(c)

 p = [j/1e6 for j in c.values()]
 print(p)

 import matplotlib.pyplot as plt
 import numpy as np
 # Création de la figure et des axes
 fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
 # Ajout de l'histogramme
 axs.hist(c, bins=np.arange(0.5, 7.5, 1), ec="black")
 axs.set_title("Résultats jet dé")
 axs.set_xlabel("Valeur dé")

but the problem is that my histogram looks like this

is it normal because each number has the same probability of appearing or is it not normal?

edit for tdy

import matplotlib.pyplot as plt
import numpy as np
# Création de la figure et des axes
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
axs.hist(c,ec="black")
axs.set_title("Résultats jet dé")
axs.set_xlabel("Valeur dé")

edit after help for @JohanC

#import random
#liste = []
#for i in range(0, 1000000):
#    liste.append(random.uniform(0,1))
import random
liste = random.choices((1,2,3,4,5,6), k=1000000)
import collections
c = collections.Counter(liste)
print(c)

p = [j/1e6 for j in c.values()]
print(p)

import matplotlib.pyplot as plt
import numpy as np
plt.bar(c.keys(), c.values())

# Création de la figure et des axes
#fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
#axs.hist(c,ec="black")
#axs.set_title("Résultats jet dé")
#axs.set_xlabel("Valeur dé")

i get a value of 160000 for each dice face, i.e. 6. but 6*160000+960000 i shouldn't get the number of rolls, i.e. 1000000?

Body:
Dice rolls produce an integer value.

So using random.uniform (which returns a float) is not the right way.

Try:

import random
liste = random.choices((1,2,3,4,5,6), k=1000000)

Then, I'd use collections.Counter to count the values:

import collections
c = collections.Counter(liste)
print(c)

This would get you something like:

Counter({6: 167399, 5: 167083, 2: 166789, 3: 166548, 1: 166236, 4: 165945})

Calculating the probability:

p = [j/1e6 for j in c.values()]

This yields:

[0.167083, 0.165945, 0.167399, 0.166789, 0.166548, 0.166236]

For plotting;

import matplotlib.pyplot as plt

plt.bar(c.keys(),p)
plt.show()

It will look something like this:

The reason that all bars look about the same is because they are.

Let's check the difference between p and the probability of a fair dice, which is 1/6:

[round(j-1/6, 6) for j in p]

This gives:

[0.000416, -0.000722, 0.000732, 0.000122, -0.000119, -0.000431]

So the actual counted probability is pretty close to that of a fair dice.


问:
How to make SwiftUI List scroll on tvOS
```<code>struct ContentView: View {

    private let showList = [
        "The Flintstones",
        "The Cosby Show",
        "The Fresh Prince of Bel Air",
        "Full House",
        "Seinfeld",
        "Friends",
        "The Big Bang Theory",
        "How I Met Your Mother",
        "Grey's Anatomy",
        "The Office",
        "Law & Order",
        "I Love Lucy",
        "Family Guy",
        "The Simpsons",
        "24"
    ]

    var body: some View {
        List(showList,id: \.self) { element in
            Text(element)
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

I am trying to use List in a tvOS app, but when I run the app, the list does not scroll. This list scrolls fine when the same code is run on iOS.

How can I make this list scroll on tvOS?

答:
In TVOS only focusable Elements can be selected via the remote control. So you need to make your list elements focusable. One way would be to make a list of buttons:</p>
```<code>      List {
        ForEach(showList ?? []) { show in
          Button(action: {}) {
          Text(show)
          }
          .buttonStyle(CardButtonStyle())
        }
      }
</code>```

Title: How to make SwiftUI List scroll on tvOS

Body:
struct ContentView: View {

    private let showList = [
        "The Flintstones",
        "The Cosby Show",
        "The Fresh Prince of Bel Air",
        "Full House",
        "Seinfeld",
        "Friends",
        "The Big Bang Theory",
        "How I Met Your Mother",
        "Grey's Anatomy",
        "The Office",
        "Law & Order",
        "I Love Lucy",
        "Family Guy",
        "The Simpsons",
        "24"
    ]

    var body: some View {
        List(showList,id: \.self) { element in
            Text(element)
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I am trying to use List in a tvOS app, but when I run the app, the list does not scroll. This list scrolls fine when the same code is run on iOS.

How can I make this list scroll on tvOS?

Body:
In TVOS only focusable Elements can be selected via the remote control. So you need to make your list elements focusable. One way would be to make a list of buttons:

      List {
        ForEach(showList ?? []) { show in
          Button(action: {}) {
          Text(show)
          }
          .buttonStyle(CardButtonStyle())
        }
      }


问:
Request to change default dialer isn't showing the system dialog on some devices
Our app needs to become the default dialer app (also known as: "default phone handler", "default calling app") so it'll be able to make calls under Android's new permissions policy.

We use the following intent to show a system dialog to ask the user to make our app the default:

```<code>Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
startActivityForResult(intent, RC_DEFAULT_PHONE);
</code>```

This works well on all our test devices, and apparently for most users, but doesn't show any dialog and immediately returns a RESULT_CANCELED result code for some devices.

By looking at the reports, it seems like the majority if not all reports are coming from Huawei devices (and from Huawei's brand - Honor).

Any idea how to display the default call app dialog on those devices?

Any other intent we can run to help the user manually set our app to be the default calling app?

答:
I had the same problem while building dialer app
Starting from the release Q android os
must but this code to ask default dialer in phone >= Q android</p>
```<code>private static final int CHANGE_DEFAULT_DIALER_CODE =25 ;

private void offerReplacingDefaultDialer() {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
        intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
                this.getPackageName());
        startActivity(intent);

    }
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
        RoleManager roleManager = (RoleManager) getSystemService(ROLE_SERVICE);
        Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER);
        startActivityForResult(intent, CHANGE_DEFAULT_DIALER_CODE);
    }
}
</code>```

Body:
Our app needs to become the default dialer app (also known as: "default phone handler", "default calling app") so it'll be able to make calls under Android's new permissions policy.

We use the following intent to show a system dialog to ask the user to make our app the default:

Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
startActivityForResult(intent, RC_DEFAULT_PHONE);

This works well on all our test devices, and apparently for most users, but doesn't show any dialog and immediately returns a RESULT_CANCELED result code for some devices.

By looking at the reports, it seems like the majority if not all reports are coming from Huawei devices (and from Huawei's brand - Honor).

Any idea how to display the default call app dialog on those devices?

Any other intent we can run to help the user manually set our app to be the default calling app?

Body:
I had the same problem while building dialer app
Starting from the release Q android os
must but this code to ask default dialer in phone >= Q android

private static final int CHANGE_DEFAULT_DIALER_CODE =25 ;

private void offerReplacingDefaultDialer() {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
        intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
                this.getPackageName());
        startActivity(intent);

    }
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
        RoleManager roleManager = (RoleManager) getSystemService(ROLE_SERVICE);
        Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER);
        startActivityForResult(intent, CHANGE_DEFAULT_DIALER_CODE);
    }
}


问:
$ADB_SERVER_SOCKET
I have a question. I was learning how to connect to android emulator from wsl-2. I saw $ADB_SERVER_SOCKET variable when looking for a solve way for the problem. I can’t find any information about the variable. Can anyone share a official source about the variable?

答:
adb has two parts:

adb client - the command-line adb executable you use

adb-server - this component is the one talking to your devices. If you execute adb client and the server is not running then it starts it.

Both communicate to each other using TCP. Usually both parts are running on the same computer and even on the same user account.

By using the variable $ADB_SERVER_SOCKET you can advice the adb client to connect to an adb-server running somewhere else. As WSL2 is a virtual environment separated from your regular Windows you can use it to advice e.g. adb client inside WSL2 to communicate with adb-server on your Windows machine.

```<code>export ADB_SERVER_SOCKET=tcp:$WSL_HOST_IP:5037
</code>```

Your WSL_HOST_IP can be found in /etc/resolv.conf in the nameserver entry1.

Title: $ADB_SERVER_SOCKET

Body:
adb has two parts:

adb client - the command-line adb executable you use

adb-server - this component is the one talking to your devices. If you execute adb client and the server is not running then it starts it.

Both communicate to each other using TCP. Usually both parts are running on the same computer and even on the same user account.

By using the variable $ADB_SERVER_SOCKET you can advice the adb client to connect to an adb-server running somewhere else. As WSL2 is a virtual environment separated from your regular Windows you can use it to advice e.g. adb client inside WSL2 to communicate with adb-server on your Windows machine.

export ADB_SERVER_SOCKET=tcp:$WSL_HOST_IP:5037

Your WSL_HOST_IP can be found in /etc/resolv.conf in the nameserver entry1.


问:
flutter problem: how to logout from apple sign in?

I am using "Sign_in _with_apple" plugin.
I did not understood how to logout from that.

I am using "Sign_in _with_apple" plugin.
I did not understood how to logout from that.

This is my functionality for apple signin.

```<code>import 'dart:convert';
import 'dart:math';

import 'package:crypto/crypto.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

/// Generates a cryptographically secure random nonce, to be included in a
/// credential request.
String generateNonce([int length = 32]) {
  final charset =
      '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
  final random = Random.secure();
  return List.generate(length, (_) => charset[random.nextInt(charset.length)])
      .join();
}

/// Returns the sha256 hash of [input] in hex notation.
String sha256ofString(String input) {
  final bytes = utf8.encode(input);
  final digest = sha256.convert(bytes);
  return digest.toString();
}

 signInWithApple() async {
  // To prevent replay attacks with the credential returned from Apple, we
  // include a nonce in the credential request. When signing in with
  // Firebase, the nonce in the id token returned by Apple, is expected to
  // match the sha256 hash of `rawNonce`.
  final rawNonce = generateNonce();
  final nonce = sha256ofString(rawNonce);

  // Request credential for the currently signed in Apple account.
  final appleCredential = await SignInWithApple.getAppleIDCredential(
    scopes: [
      AppleIDAuthorizationScopes.email,
      AppleIDAuthorizationScopes.fullName,
    ],
    nonce: nonce,
  );

  // Create an `OAuthCredential` from the credential returned by Apple.
  final oauthCredential = OAuthProvider("apple.com").credential(
    idToken: appleCredential.identityToken,
    rawNonce: rawNonce,
  );

  // Sign in the user with Firebase. If the nonce we generated earlier does
  // not match the nonce in `appleCredential.identityToken`, sign in will fail.
  final result = await FirebaseAuth.instance.signInWithCredential(oauthCredential);
  // return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
   print(result.user!.displayName.toString());
   print(result.user!.email.toString());
   print(result.user!.uid.toString());
   print(result.additionalUserInfo!.username.toString());

}

</code>```

I want logout functionality for this sign in fuctionality

答:
Firebase Auth has a function called signOut(), you can use it like this:</p>
```<code>await FirebaseAuth.instance.signOut();
</code>```

Body:
I am using "Sign_in _with_apple" plugin.
I did not understood how to logout from that.

I am using "Sign_in _with_apple" plugin.
I did not understood how to logout from that.

This is my functionality for apple signin.

import 'dart:convert';
import 'dart:math';

import 'package:crypto/crypto.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

/// Generates a cryptographically secure random nonce, to be included in a
/// credential request.
String generateNonce([int length = 32]) {
  final charset =
      '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
  final random = Random.secure();
  return List.generate(length, (_) => charset[random.nextInt(charset.length)])
      .join();
}

/// Returns the sha256 hash of [input] in hex notation.
String sha256ofString(String input) {
  final bytes = utf8.encode(input);
  final digest = sha256.convert(bytes);
  return digest.toString();
}

 signInWithApple() async {
  // To prevent replay attacks with the credential returned from Apple, we
  // include a nonce in the credential request. When signing in with
  // Firebase, the nonce in the id token returned by Apple, is expected to
  // match the sha256 hash of `rawNonce`.
  final rawNonce = generateNonce();
  final nonce = sha256ofString(rawNonce);

  // Request credential for the currently signed in Apple account.
  final appleCredential = await SignInWithApple.getAppleIDCredential(
    scopes: [
      AppleIDAuthorizationScopes.email,
      AppleIDAuthorizationScopes.fullName,
    ],
    nonce: nonce,
  );

  // Create an `OAuthCredential` from the credential returned by Apple.
  final oauthCredential = OAuthProvider("apple.com").credential(
    idToken: appleCredential.identityToken,
    rawNonce: rawNonce,
  );

  // Sign in the user with Firebase. If the nonce we generated earlier does
  // not match the nonce in `appleCredential.identityToken`, sign in will fail.
  final result = await FirebaseAuth.instance.signInWithCredential(oauthCredential);
  // return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
   print(result.user!.displayName.toString());
   print(result.user!.email.toString());
   print(result.user!.uid.toString());
   print(result.additionalUserInfo!.username.toString());

}

I want logout functionality for this sign in fuctionality

Body:
Firebase Auth has a function called signOut(), you can use it like this:

await FirebaseAuth.instance.signOut();


问:
Why the method uses Activator.CreateInstance instead of directly "new Class()"?
In the method GetNotificationCorrespondingToDomainEvent in
https://github.com/jasontaylordev/CleanArchitecture/blob/main/src/Infrastructure/Services/DomainEventService.cs, it has the following method,

```<code>private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
    return (INotification)Activator.CreateInstance(
        typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;
}
</code>```

How it compares with new DomainEventNotification(....)? BTW, is the ! at the end necessary?

```<code>private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
    return new DomainEventNotification<DomainEvent>(domainEvent)!;
}
</code>```

答:
The difference is that

```<code>return (INotification)Activator.CreateInstance(
        typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;
</code>```

creates an instance with the dynamic type of domainEvent. So if the actual argument is MyDerivedDomainEvent, it creates an instance of DomainEventNotification<MyDerivedDomainEvent>. There's not enough context to tell whether that makes sense, but that's what happens.

Activator.CreateInstance() has the return type object?, so the ! is necessary to prevent the nullability warning. One could question why they selected the return type to be nullable, because I don't think it will ever return null.

Body:
In the method GetNotificationCorrespondingToDomainEvent in
https://github.com/jasontaylordev/CleanArchitecture/blob/main/src/Infrastructure/Services/DomainEventService.cs, it has the following method,

private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
    return (INotification)Activator.CreateInstance(
        typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;
}

How it compares with new DomainEventNotification(....)? BTW, is the ! at the end necessary?

private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
    return new DomainEventNotification<DomainEvent>(domainEvent)!;
}

Body:
The difference is that

return (INotification)Activator.CreateInstance(
        typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;

creates an instance with the dynamic type of domainEvent. So if the actual argument is MyDerivedDomainEvent, it creates an instance of DomainEventNotification<MyDerivedDomainEvent>. There's not enough context to tell whether that makes sense, but that's what happens.

Activator.CreateInstance() has the return type object?, so the ! is necessary to prevent the nullability warning. One could question why they selected the return type to be nullable, because I don't think it will ever return null.


问:
Extending a line segment in matplotlib
Is there a function in matplotlib similar to MATLAB's line extensions?

I am basically looking for a way to extend a line segment to a plot. My current plot looks like this.

After looking at another question and applying the formula, I was able to get it to here, but it still looks messy.

Does anyone have the magic formula here?

答:
New in matplotlib 3.3

There is now an axline method to easily extend arbitrary lines:

Adds an infinitely long straight line. The line can be defined either by two points xy1 and xy2

```<code>plt.axline(xy1=(0, 1), xy2=(1, 0.5), color='r')
</code>```

or defined by one point xy1 and a slope.

```<code>plt.axline(xy1=(0, 1), slope=-0.5, color='r')
</code>```

Sample data for reference:

```<code>import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.default_rng(123).random((2, 100)) * 2 - 1
m, b = -0.5, 1
plt.scatter(x, y, c=np.where(y > m*x + b, 'r', 'k'))
</code>```

Title: Extending a line segment in matplotlib

Body:
New in matplotlib 3.3

There is now an axline method to easily extend arbitrary lines:

Adds an infinitely long straight line. The line can be defined either by two points xy1 and xy2

plt.axline(xy1=(0, 1), xy2=(1, 0.5), color='r')

or defined by one point xy1 and a slope.

plt.axline(xy1=(0, 1), slope=-0.5, color='r')

Sample data for reference:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.default_rng(123).random((2, 100)) * 2 - 1
m, b = -0.5, 1
plt.scatter(x, y, c=np.where(y > m*x + b, 'r', 'k'))


问:
Include local .json file in Eclipse Android project
I have a local .json file. I don't want it to be on a server, I just want it to be included in my app. I tried to paste it directly into Eclipse in my project, but I got a FileNotFoundException, I also tried to paste it in the workspace folder in Windows Explorer/Finder and got the same exception. Where should I put it?

Thanks!

答:
Put the file in the assets folder.
You can use the AssetManager open(String fileName) to read the file. </p>

ContentLicense: CC BY-SA 3.0


问:
PCF cfdev plugin install No Such Host Error
I tried to install Cloud Foundary cfdev plugin to setup pivotal cloud environment in local machine (MacOS Big Sur).

```<code> ~ % cf install-plugin -r CF-Community cfdev
Searching CF-Community for plugin cfdev...
Plugin cfdev 0.0.18 found in: CF-Community
Attention: Plugins are binaries written by potentially untrusted authors.
Install and use plugins at your own risk.
Do you want to install the plugin cfdev? [yN]: y
Starting download of plugin binary from repository CF-Community...
Get https://d3p1cc0zb2wjno.cloudfront.net/cfdev/cfdev-v0.0.18-rc.36-darwin: dial tcp: lookup d3p1cc0zb2wjno.cloudfront.net: no such host
FAILED
</code>```

Looks like unable to reach d3p1cc0zb2wjno.cloudfront.net host and even I tried hitting https://d3p1cc0zb2wjno.cloudfront.net/cfdev/cfdev-v0.0.18-rc.36-darwin endpoint in browser but no luck.

Any suggestion to try out, or resolution please?

答: I found a workaround by adjusting the time on the host machine for 01.2021 - in theory, could be any date less than 10.04.2021. I managed to get the full installation + apps-manager and scs. After that, the auto-sync of time could be restored.</p>

Body:
I tried to install Cloud Foundary cfdev plugin to setup pivotal cloud environment in local machine (MacOS Big Sur).

 ~ % cf install-plugin -r CF-Community cfdev
Searching CF-Community for plugin cfdev...
Plugin cfdev 0.0.18 found in: CF-Community
Attention: Plugins are binaries written by potentially untrusted authors.
Install and use plugins at your own risk.
Do you want to install the plugin cfdev? [yN]: y
Starting download of plugin binary from repository CF-Community...
Get https://d3p1cc0zb2wjno.cloudfront.net/cfdev/cfdev-v0.0.18-rc.36-darwin: dial tcp: lookup d3p1cc0zb2wjno.cloudfront.net: no such host
FAILED

Looks like unable to reach d3p1cc0zb2wjno.cloudfront.net host and even I tried hitting https://d3p1cc0zb2wjno.cloudfront.net/cfdev/cfdev-v0.0.18-rc.36-darwin endpoint in browser but no luck.

Any suggestion to try out, or resolution please?


问:
Is there something special to encrypting a string into another file using a custom dictionary?
I made a custom dictionary in Python changing the alphabet (both upper and lowercase) into symbols and numbers.  I am trying to copy the content of one text file to another but encrypt it in the custom dictionary.  For example, if the file says "Hello World" the other file that it is being copied to should say "%?;;2 !2(;". I tried a bunch of things but it either gives me an error or the other file stays blank

Here's the code below

```<code>fileData = open('EXAMPLE.txt', 'r')
f = open('ENCODE.txt', 'w')

for x in fileData:
    encrypt = code.get(x, '')
    f.write(encrypt)
</code>```

fileData is the file the is being read/ copied from.  code is the dictionary name.  Then I tried getting the value from the key or if it is a number/ white space, it will just default. However, it keeps coming out blank.  I tried the import json but I also can not get that to encrypt with the dictionary.

EXAMPLE.txt has the text

```<code>the quick brown fox jumps over the lazy dog
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
</code>```

ENCODE.txt is blank as the text will be copied over and encoded

Dictionary below

```<code>code = {'A':'1',
         'a':'@',
         'B':'!',
         'b':'#',
         'C':'3',
         'c':'$',
         'D':'4',
         'd':'^',
         'E':'<',
         'e':'?',
         'F':'>',
         'f':',',
         'G':'5',
         'g':'/',
         'H':'%',
         'h':']',
         'I':'[',
         'i':'£',
         'J':'|',
         'j':'*',
         'K':'-',
         'k':'+',
         'L':'8',
         'l':')',
         'M':'9',
         'm':'(',
         'N':'&',
         'n':'7',
         'O':';',
         'o':'`',
         'P':'0',
         'p':'_',
         'Q':'"',
         'q':'~',
         'R':'.',
         'r':'2',
         'S':'6',
         's':'8',
         'T':'7',
         't':'=',
         'U':'[',
         'u':'>',
         'V':'{',
         'v':';',
         'W':'}',
         'w':':',
         'X':'é',
         'x':'¡',
         'Y':'»',
         'y':'¤',
         'Z':'§',
         'z':'µ'}
</code>```

答:
for x in fileData: iterates lines of text.  You need something like the following to read a single character at a time:

```<code>while (x := fileData.read(1)):
</code>```

But there is also str.translate and str.maketrans which are built-in methods of string to generate lookup tables and perform translation, so you can read the whole file and translate efficiently:

Python 3.10 example:

xlat = str.maketrans('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz',
                     '1@!#3$4^<?>,5/%][£|*-+8)9(&7;`0_"~.2687=[>{;}:é¡»¤§µ')

with (open('EXAMPLE.txt', 'r') as fileData,
      open('ENCODE.txt', 'w') as f):

    encrypt = fileData.read().translate(xlat)
    f.write(encrypt)
```

Body:
I made a custom dictionary in Python changing the alphabet (both upper and lowercase) into symbols and numbers.  I am trying to copy the content of one text file to another but encrypt it in the custom dictionary.  For example, if the file says "Hello World" the other file that it is being copied to should say "%?;;2 !2(;". I tried a bunch of things but it either gives me an error or the other file stays blank

Here's the code below

fileData = open('EXAMPLE.txt', 'r')
f = open('ENCODE.txt', 'w')

for x in fileData:
    encrypt = code.get(x, '')
    f.write(encrypt)

fileData is the file the is being read/ copied from.  code is the dictionary name.  Then I tried getting the value from the key or if it is a number/ white space, it will just default. However, it keeps coming out blank.  I tried the import json but I also can not get that to encrypt with the dictionary.

EXAMPLE.txt has the text

the quick brown fox jumps over the lazy dog
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

ENCODE.txt is blank as the text will be copied over and encoded

Dictionary below

code = {'A':'1',
         'a':'@',
         'B':'!',
         'b':'#',
         'C':'3',
         'c':'$',
         'D':'4',
         'd':'^',
         'E':'<',
         'e':'?',
         'F':'>',
         'f':',',
         'G':'5',
         'g':'/',
         'H':'%',
         'h':']',
         'I':'[',
         'i':'£',
         'J':'|',
         'j':'*',
         'K':'-',
         'k':'+',
         'L':'8',
         'l':')',
         'M':'9',
         'm':'(',
         'N':'&',
         'n':'7',
         'O':';',
         'o':'`',
         'P':'0',
         'p':'_',
         'Q':'"',
         'q':'~',
         'R':'.',
         'r':'2',
         'S':'6',
         's':'8',
         'T':'7',
         't':'=',
         'U':'[',
         'u':'>',
         'V':'{',
         'v':';',
         'W':'}',
         'w':':',
         'X':'é',
         'x':'¡',
         'Y':'»',
         'y':'¤',
         'Z':'§',
         'z':'µ'}

Body:
for x in fileData: iterates lines of text.  You need something like the following to read a single character at a time:

while (x := fileData.read(1)):

But there is also str.translate and str.maketrans which are built-in methods of string to generate lookup tables and perform translation, so you can read the whole file and translate efficiently:

Python 3.10 example:

xlat = str.maketrans('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz',
                     '1@!#3$4^<?>,5/%][£|*-+8)9(&7;`0_"~.2687=[>{;}:é¡»¤§µ')

with (open('EXAMPLE.txt', 'r') as fileData,
      open('ENCODE.txt', 'w') as f):

    encrypt = fileData.read().translate(xlat)
    f.write(encrypt)


问:
How to change the orientation of SimpleITK image in Python
I used this code to read a series for dicom images into python

```<code>series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(data_directory)
series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(data_directory, series_IDs[0])
series_reader = sitk.ImageSeriesReader()
series_reader.SetFileNames(series_file_names)
series_reader.LoadPrivateTagsOn()
image3D=series_reader.Execute()
size = image3D.GetSize()
</code>```

currently, its orientation is the following:

I need to change the orientation to the following orientation:

Is there any command in python to be able to change the orientation of SimpleITK image?

答:
I needed to reorient NIfTI images (files with .nii or .nii.gz extension) and the above solution didn't work for me. After some research in the SimpleITK library I found the function sitk.DICOMOrient() which worked for me.

Adjusting to your example (Tested in version 2.1.1 of SimpleITK and Python 3.7.1) :

```<code># Given a sitk image instance -> img

reoriented = sitk.DICOMOrient(img, 'LPS')
</code>```

It is also possible to test multiple permutations of the orientation labels,
check this doc to understand the about the meaning of the labels.

Body:
I used this code to read a series for dicom images into python

series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(data_directory)
series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(data_directory, series_IDs[0])
series_reader = sitk.ImageSeriesReader()
series_reader.SetFileNames(series_file_names)
series_reader.LoadPrivateTagsOn()
image3D=series_reader.Execute()
size = image3D.GetSize()

currently, its orientation is the following:

I need to change the orientation to the following orientation:

Is there any command in python to be able to change the orientation of SimpleITK image?

Body:
I needed to reorient NIfTI images (files with .nii or .nii.gz extension) and the above solution didn't work for me. After some research in the SimpleITK library I found the function sitk.DICOMOrient() which worked for me.

Adjusting to your example (Tested in version 2.1.1 of SimpleITK and Python 3.7.1) :

# Given a sitk image instance -> img

reoriented = sitk.DICOMOrient(img, 'LPS')

It is also possible to test multiple permutations of the orientation labels,
check this doc to understand the about the meaning of the labels.


问:
AttributeError: 'Model' object has no attribute '....' Django Rest Framework
I have this model

```<code>class EntityPhoto(models.Model):
    user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user')
    entity = models.ForeignKey('Entity', on_delete=models.CASCADE)
    image = models.FileField(upload_to='entities/')
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
</code>```
```<code>class Entity(models.Model):
....
</code>```
```<code>class EntityPhotosSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField('get_img')

    def get_img(self, entity_photo):
        if not entity_photo.image:
            raise NotFound

        request = self.context.get('request')
        return request.build_absolute_uri(entity_photo.image.url)

    class Meta:
        model = EntityPhoto
        fields = ('user', 'entity', 'image',)

class SpecialistSerializer(serializers.ModelSerializer):
    reviews_quantity = serializers.IntegerField(source="get_reviews_quantity")

    class Meta:
        model = Entity
        fields = '__all__'

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['photos'] = EntityPhotosSerializer(many=True, instance=instance.image_set.all()).data
        return data

</code>```

and after making get request I get an error:

```<code>AttributeError: 'Entity' object has no attribute 'image_set'
</code>```

Which is weird because a few days ago i did the same thing with a model that was connected via reverse relationship the same way, i even copied the code and it worked. Do you think it might be because of the image file? I wanna show the list of Photos(that the serializer changed to url) for every Entity Instance.

答:
You are trying to access to "image_set" but there is no "image" model linked to Entity. However, there is a EntityPhoto model.

So doing

```<code>data['photos'] = EntityPhotosSerializer(many=True,instance=instance.image_set.all()).data
</code>```

is not supposed to give anything.

If you want to access to the related entity photo of the entity, you are supposed to do

```<code>data['photos'] = EntityPhotosSerializer(many=True,instance=instance.entityphoto_set.all()).data
</code>```

Body:
I have this model

class EntityPhoto(models.Model):
    user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user')
    entity = models.ForeignKey('Entity', on_delete=models.CASCADE)
    image = models.FileField(upload_to='entities/')
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)

class Entity(models.Model):
....

class EntityPhotosSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField('get_img')

    def get_img(self, entity_photo):
        if not entity_photo.image:
            raise NotFound

        request = self.context.get('request')
        return request.build_absolute_uri(entity_photo.image.url)

    class Meta:
        model = EntityPhoto
        fields = ('user', 'entity', 'image',)

class SpecialistSerializer(serializers.ModelSerializer):
    reviews_quantity = serializers.IntegerField(source="get_reviews_quantity")

    class Meta:
        model = Entity
        fields = '__all__'

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['photos'] = EntityPhotosSerializer(many=True, instance=instance.image_set.all()).data
        return data

and after making get request I get an error:

AttributeError: 'Entity' object has no attribute 'image_set'

Which is weird because a few days ago i did the same thing with a model that was connected via reverse relationship the same way, i even copied the code and it worked. Do you think it might be because of the image file? I wanna show the list of Photos(that the serializer changed to url) for every Entity Instance.

Body:
You are trying to access to "image_set" but there is no "image" model linked to Entity. However, there is a EntityPhoto model.

So doing

data['photos'] = EntityPhotosSerializer(many=True,instance=instance.image_set.all()).data

is not supposed to give anything.

If you want to access to the related entity photo of the entity, you are supposed to do

data['photos'] = EntityPhotosSerializer(many=True,instance=instance.entityphoto_set.all()).data


问:
"rusty_v8" build error on 32-bit platforms
I am new at Rust and Chromium V8 Engine.

I tried to build Deno from source on Raspberry Pi OS(32bit arm), but an error has occurred at rusty_v8 build. And same result on Intel 32bit.

```<code>  ../../../../.cargo/registry/src/github.com-1285ae84e5963aae/v8-0.39.0/src/binding.cc:40:1: error: static_assert failed due to requirement 'sizeof(v8::ScriptCompiler::Source) <= sizeof(unsigned int) * 8' "Source size mismatch"
  static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(size_t) * 8,
  ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3 warnings and 1 error generated.
</code>```

I thought the size of "size_t" depends the host machine's architecture, so I fixed "binding.cc" to

static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(uint64_t) * 8,
              "Source size mismatch");
```

Is this correct? And please explain what is this "static_assert"?

I'm not a native speaker so please forgive my weird English.

答:
Is this correct? And please explain what is this "static_assert"?

Static assertions specifically instruct the compiler to check that a certain condition is true, and produce an error otherwise. They are used to guard assumptions made by the code. So changing the static_assert without updating the code it guards is pretty much guaranteed to cause further problems.

In the case at hand, it is likely that some code assumes that a v8::ScriptCompiler::Source can be stored in the space of 8 size_ts. The static_assert makes sure that this assumption actually holds. By changing the assertion without updating the code that makes this assumption, you're very likely to create a bug (chances are, either something else will be overwritten, or a Source won't be fully stored; either way there'll likely be some form of memory corruption).

(If you want an analogy: it's like driving in a car and encountering a red stop light at a railroad crossing. You can "fix" it by throwing some green paint at the light, but unless you also stop the approaching train, that green paint is unlikely to actually help you :-) )

Body:
I am new at Rust and Chromium V8 Engine.

I tried to build Deno from source on Raspberry Pi OS(32bit arm), but an error has occurred at rusty_v8 build. And same result on Intel 32bit.

  ../../../../.cargo/registry/src/github.com-1285ae84e5963aae/v8-0.39.0/src/binding.cc:40:1: error: static_assert failed due to requirement 'sizeof(v8::ScriptCompiler::Source) <= sizeof(unsigned int) * 8' "Source size mismatch"
  static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(size_t) * 8,
  ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3 warnings and 1 error generated.

I thought the size of "size_t" depends the host machine's architecture, so I fixed "binding.cc" to

static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(uint64_t) * 8,
              "Source size mismatch");

Is this correct? And please explain what is this "static_assert"?

I'm not a native speaker so please forgive my weird English.


问:
How do I add execute permission to a file in CVS after it's already been checked in?
We use CVS on Linux for software development.

I noticed that one of the scripts I'm working on is missing the execute bit set in the CVS repository.

Is there any way to add the execute bit back to the file?

I think it involves modifying the repository directly, but I don't know how to do this.

答: Modify the permissions of the related ,v file in the repository.  Per this article, the file is checked out with the same permissions as the ,v file in CVSROOT.

OwnerDisplayName: Jin Kim

OwnerDisplayName: Alex B

LastEditorDisplayName: Alex B


答: You should put the file either in the /assets or /res/raw directory of your Android project.  From there, you can retrieve it with either: Context.getResources().openRawResource(R.raw.filename) or Context.getResources().getAssets().open("filename").

Title: Include local .json file in Eclipse Android project

Body:
I have a local .json file. I don't want it to be on a server, I just want it to be included in my app. I tried to paste it directly into Eclipse in my project, but I got a FileNotFoundException, I also tried to paste it in the workspace folder in Windows Explorer/Finder and got the same exception. Where should I put it?

Thanks!


问:
How to pass different variables to multiple functons?
I am very new to python and I have three lists that I edited in a function and want to pass these three lists to multiple different functions,
This is basic example of what I mean:

```<code>def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]

def aa():

def bb():
</code>```

I would like to send firstlist to aa() and all three lists to bb() but I am confused. What would be the most efficient way to do that?

答:
You can return in the first function a tuple of the list:

```<code>def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]
    return firstlist, seclist, thirdlist
</code>```

So, you just call this function and get the index of the tuple you want:

```<code>def aa():
    return editing()[0]
print(aa())
</code>```

Output:

```<code>[1, 2, 3]
</code>```

And so on

Body:
I am very new to python and I have three lists that I edited in a function and want to pass these three lists to multiple different functions,
This is basic example of what I mean:

def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]

def aa():

def bb():

I would like to send firstlist to aa() and all three lists to bb() but I am confused. What would be the most efficient way to do that?

Body:
You can return in the first function a tuple of the list:

def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]
    return firstlist, seclist, thirdlist

So, you just call this function and get the index of the tuple you want:

def aa():
    return editing()[0]
print(aa())

Output:

[1, 2, 3]

And so on


问:
Telegram BOT - How to get chat ID of users in my group?
I've been using a Telegram BOT to send notifications for a group, and for users.

I already know i can get Chat ID by receiving a message from the user on my bot, using getUpdates.

I also know i can get Group ID using the same method...

But what i really need is:
There is three users in my group.

My bot.

Me.

Another user that didn't sent any messages to my bot so it does not appear on getUpdates

Is it possible to get this third user his ID?
PS: I am the group owner, and also added my bot as Admin...

The third user is a normal user.
Can someone help me?

Thanks!

答:
That's not possible with the official Telegram Bot API.

Possible Workarounds:

Hold a list of your own. If a user is joining (new_chat_member), leaving (left_chat_member), somebody is sending a message in the group, and so on. Check Message for more information.

Check if a user is a member of the group with getChatMember.

Also may be helpful: getChatMembersCount and getChatAdministrators


问:
MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB
I want to create a table of 325 column:

```<code>CREATE TABLE NAMESCHEMA.NAMETABLE
(
      ROW_ID TEXT NOT NULL ,        //this is the primary key

324 column of these types:
      CHAR(1),
      DATE,
      DECIMAL(10,0),
      DECIMAL(10,7),
      TEXT,
      LONG,

) ROW_FORMAT=COMPRESSED;
</code>```

I replaced all the VARCHAR with the TEXT and i have added Barracuda in the my.ini file of MySQL, this is the attributes added:

```<code>innodb_file_per_table=1
innodb_file_format=Barracuda
innodb_file_format_check = ON
</code>```

but i still have this error:

```<code>Error Code: 1118
 Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.
</code>```

EDIT: I can't change the structure of the database because it's legacy application/system/database. The create of a new table, it's an export of the legacy database.

EDIT2: i wrote this question that is similar to others but inside there are some solution that i found on internet like VARCHAR and Barracuda, but i still have that problem so i decided to open a new question with already the classic answer inside for seeing if someone have other answers

答:
In the case that this message appears when changing MariaDB version, I had exactly the same issue changing to MariaDB 10.6.5 and that's how I solved the issue:

Using PhpMyAdmin, I exported the .sql file from the old MariaDB version

Edited the .sql file using an editor such as Notepad++ and added the line
SET GLOBAL innodb_default_row_format='dynamic'; on top as follows:

```<code>-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: (*Your host*)
-- Generation Time: Feb 12, 2022 at 05:22 PM
-- Server version: 10.6.4-MariaDB
-- PHP Version: 8.0.3

SET GLOBAL innodb_default_row_format='dynamic';
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
</code>```

3.Imported the altered .sql file to MariaDB 10.6.5

All worked fine

Body:
I want to create a table of 325 column:

CREATE TABLE NAMESCHEMA.NAMETABLE
(
      ROW_ID TEXT NOT NULL ,        //this is the primary key

324 column of these types:
      CHAR(1),
      DATE,
      DECIMAL(10,0),
      DECIMAL(10,7),
      TEXT,
      LONG,

) ROW_FORMAT=COMPRESSED;

I replaced all the VARCHAR with the TEXT and i have added Barracuda in the my.ini file of MySQL, this is the attributes added:

innodb_file_per_table=1
innodb_file_format=Barracuda
innodb_file_format_check = ON

but i still have this error:

Error Code: 1118
 Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.

EDIT: I can't change the structure of the database because it's legacy application/system/database. The create of a new table, it's an export of the legacy database.

EDIT2: i wrote this question that is similar to others but inside there are some solution that i found on internet like VARCHAR and Barracuda, but i still have that problem so i decided to open a new question with already the classic answer inside for seeing if someone have other answers

Body:
In the case that this message appears when changing MariaDB version, I had exactly the same issue changing to MariaDB 10.6.5 and that's how I solved the issue:

Using PhpMyAdmin, I exported the .sql file from the old MariaDB version

Edited the .sql file using an editor such as Notepad++ and added the line
SET GLOBAL innodb_default_row_format='dynamic'; on top as follows:

-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: (*Your host*)
-- Generation Time: Feb 12, 2022 at 05:22 PM
-- Server version: 10.6.4-MariaDB
-- PHP Version: 8.0.3

SET GLOBAL innodb_default_row_format='dynamic';
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

3.Imported the altered .sql file to MariaDB 10.6.5

All worked fine


问:
System.Data.OleDb.OleDbException: 'Parameter @Status has no default value.' in VB
Apologies if my post doesn't follow common practice/rules for coding forums as this is my second question.

I have a button that once clicked, performs a search in an MS Access database for items based on the selected values in combo boxes and adds these items to a data grid. It creates a parameter for each value and adds the relevant combo box item to that parameter.

The CreateSQLStr() function forms the SQL command text based on what combo boxes have a selected value (i.e. if a combo box doesn't have a selected value then it won't specify a condition for that field in the table but if it does it will add AND (TableField = @Parameter) onto the SQL command text).

I've tried changing the "ACTIVE" to a pre-defined string and the same error and I can't think of anything else.

My error is `System.Data.OleDb.OleDbException: 'Parameter @Status has no default value.'

Details:

```<code>System.Data.OleDb.OleDbException
  HResult=0x80040E10
  Message=Parameter @Status has no default value.
  Source=System.Data
  StackTrace:
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.OleDb.OleDbCommand.ExecuteReader()
   at WindowsApplication1.frmEmployee.vehiclesearch_Click(Object sender, EventArgs e) in C:\Users\aawad\OneDrive\Documents\QHP\QHP\QHP\frmEmployee.vb:line 79
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
   at WindowsApplication1.My.MyApplication.Main(String[] Args) in :line 81

  This exception was originally thrown at this call stack:
    [External Code]
    WindowsApplication1.frmEmployee.vehiclesearch_Click(Object, System.EventArgs) in frmEmployee.vb
    [External Code]
</code>```

`

```<code>Private Sub vehiclesearch_Click(sender As Object, e As EventArgs) Handles VehicleSearch.Click
    If DbConnect() Then 'This fucntions returns boolean for whether or not database is connecyed
        Dim SQLcmd As New OleDbCommand
        With SQLcmd
            .Connection = cn
            .CommandText = CreateSQLStr() 'Creates command text based on selected combo box items, see below
            .Parameters.AddWithValue("@Make", MakeCBox.SelectedItem)
            .Parameters.AddWithValue("@Model", ModelCBox.SelectedItem)
            .Parameters.AddWithValue("@ClassV", ClassCBox.SelectedItem)
            .Parameters.AddWithValue("@VSeats", SeatsCBox.SelectedItem)
            .Parameters.AddWithValue("@GrBox", GrboxCBox.SelectedItem)
            .Parameters.AddWithValue("@Branch", BranchCBox.SelectedItem)
            .Parameters.AddWithValue("@Status", "ACTIVE")
            Dim rs As OleDbDataReader = .ExecuteReader 'Error occurs at this point
            While rs.Read 'Adding data to data grid
                Dim make, model, year, fuel, vclass, body As String
                make = rs("VMake")
                model = rs("VModel")
                year = rs("VRegYear")
                fuel = rs("VFuel")
                vclass = rs("VClass")
                body = rs("VBody")
                VehDGrid.Rows.Add(make, model, year, fuel, vclass, body)
            End While
            rs.Close()
            cn.Close()
        End With
    Else 'Error message when no vehicle found
        MessageBox.Show("Could not find any vehicles with the selected details. ", "Find vehicle", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End If
End Sub

Function CreateSQLStr() As String
    Dim SQLStr As String
    SQLStr = "Select * FROM Vehicles WHERE (VStatus = @Status)"
    If MakeCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr + " AND (VMake = @Make)"
    End If
    If ModelCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VModel = @Model)"
    End If
    If ClassCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VClass = @ClassV)"
    End If
    If SeatsCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VSeats = @Seats)"
    End If
    If GrboxCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VGearbox = @GrBox)"
    End If
    If BranchCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (BranchID = @Branch)"
    End If
    Return SQLStr
End Function

</code>```

EDIT: reply to comment

```<code> Dim rs As OleDbDataReader = SQLcmd.ExecuteReader

                While rs.Read
                    VehDGrid.Rows.Add(rs("VehicleID"), rs("VMake"), rs("VModel"), rs("VRegYear"),
                                      rs("VFuel"), rs("VClass"), rs("VBody"), rs("VSeats"),
                                      rs("VGearbox"), rs("VReg"), rs("PPDay"), rs("VColour"))
                End While
</code>```

答:
You don't need a loop to file out the data grid.

And I would not mess if the conneciton is open or closed. All code written will have closed the connection, so code based on that assumpiton.

While the "@" name parameters for oleDB does not matter (for Access data engine), however, you might as well use them, since that code can be used in the future for sql server etc.

I would also NOT separate add where clause and THEN separate add parameters. ALWAYS add them both at the SAME time.

That way, you can change the order of the code, or even cut + paste more parts in, and it will always work. Since Access is sensitive to order of parameters, then this advice is EVEN MORE valuable (add sql, and parameters as a group in your code - not in two separate places. That way, you really can't mess up the order, since you pair this process in code.

As noted, you don't need a loop to add the rows to the data grid - it is a data aware code, and you can thus just send it the data table.

eg this:

```<code>    Using conn As New OleDbConnection(My.Settings.AccessDB)

        conn.Open()

        Using cmdSQL As New OleDbCommand("", conn)

            pAdd(cmdSQL, "VMake", MakeCBox)
            pAdd(cmdSQL, "Vmodel", ModelCBox)
            pAdd(cmdSQL, "VClass", ClassCBox)
            pAdd(cmdSQL, "VSeats", SeatsCBox)
            pAdd(cmdSQL, "VGearBox", GrboxCBox)
            pAdd(cmdSQL, "BranchID", BranchCBox)

            cmdSQL.CommandText &= " AND (VStatus = @VStatus)"
            cmdSQL.Parameters.AddWithValue("@VStatus", "ACTIVE")

            cmdSQL.CommandText = "SELECT * FROM Vehicles WHERE " & cmdSQL.CommandText
            Console.WriteLine(cmdSQL.CommandText)

            Dim rstData As New DataTable
            rstData.Load(cmdSQL.ExecuteReader)

            If rstData.Rows.Count = 0 Then
                MsgBox("no data")
            Else
                VehDGrid.DataSource = rstData
            End If

        End Using
    End Using

End Sub

Sub pAdd(cmd As OleDbCommand, sColumn As String,  c As ComboBox)

    If c.SelectedItem IsNot Nothing AndAlso c.Text <> "" Then

        Dim sP As String = "@" & sColumn
        If cmd.CommandText <> "" Then cmd.CommandText &= " AND "
        cmd.CommandText &= "(" & sColumn & " = " & sP & ")"
        cmd.Parameters.AddWithValue(sP, c.Text)

    End If

End Sub
</code>```

Edit: Question about My.Settings.AccessDB

Well, be it desktop, or web based? I just used this:

Project->project properties, and then this:

So, in above, you can click on the "..." button, and that launches the connection builder. And once you save above, then the setting can be used from My.Settings."my setting name here".

So, for things like company name, perhaps a title, or whatever? You can build up and create your own settings. Once done, then these handy settings can be used in code.

Body:
Apologies if my post doesn't follow common practice/rules for coding forums as this is my second question.

I have a button that once clicked, performs a search in an MS Access database for items based on the selected values in combo boxes and adds these items to a data grid. It creates a parameter for each value and adds the relevant combo box item to that parameter.

The CreateSQLStr() function forms the SQL command text based on what combo boxes have a selected value (i.e. if a combo box doesn't have a selected value then it won't specify a condition for that field in the table but if it does it will add AND (TableField = @Parameter) onto the SQL command text).

I've tried changing the "ACTIVE" to a pre-defined string and the same error and I can't think of anything else.

My error is `System.Data.OleDb.OleDbException: 'Parameter @Status has no default value.'

Details:

System.Data.OleDb.OleDbException
  HResult=0x80040E10
  Message=Parameter @Status has no default value.
  Source=System.Data
  StackTrace:
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.OleDb.OleDbCommand.ExecuteReader()
   at WindowsApplication1.frmEmployee.vehiclesearch_Click(Object sender, EventArgs e) in C:\Users\aawad\OneDrive\Documents\QHP\QHP\QHP\frmEmployee.vb:line 79
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
   at WindowsApplication1.My.MyApplication.Main(String[] Args) in :line 81

  This exception was originally thrown at this call stack:
    [External Code]
    WindowsApplication1.frmEmployee.vehiclesearch_Click(Object, System.EventArgs) in frmEmployee.vb
    [External Code]

`

Private Sub vehiclesearch_Click(sender As Object, e As EventArgs) Handles VehicleSearch.Click
    If DbConnect() Then 'This fucntions returns boolean for whether or not database is connecyed
        Dim SQLcmd As New OleDbCommand
        With SQLcmd
            .Connection = cn
            .CommandText = CreateSQLStr() 'Creates command text based on selected combo box items, see below
            .Parameters.AddWithValue("@Make", MakeCBox.SelectedItem)
            .Parameters.AddWithValue("@Model", ModelCBox.SelectedItem)
            .Parameters.AddWithValue("@ClassV", ClassCBox.SelectedItem)
            .Parameters.AddWithValue("@VSeats", SeatsCBox.SelectedItem)
            .Parameters.AddWithValue("@GrBox", GrboxCBox.SelectedItem)
            .Parameters.AddWithValue("@Branch", BranchCBox.SelectedItem)
            .Parameters.AddWithValue("@Status", "ACTIVE")
            Dim rs As OleDbDataReader = .ExecuteReader 'Error occurs at this point
            While rs.Read 'Adding data to data grid
                Dim make, model, year, fuel, vclass, body As String
                make = rs("VMake")
                model = rs("VModel")
                year = rs("VRegYear")
                fuel = rs("VFuel")
                vclass = rs("VClass")
                body = rs("VBody")
                VehDGrid.Rows.Add(make, model, year, fuel, vclass, body)
            End While
            rs.Close()
            cn.Close()
        End With
    Else 'Error message when no vehicle found
        MessageBox.Show("Could not find any vehicles with the selected details. ", "Find vehicle", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End If
End Sub

Function CreateSQLStr() As String
    Dim SQLStr As String
    SQLStr = "Select * FROM Vehicles WHERE (VStatus = @Status)"
    If MakeCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr + " AND (VMake = @Make)"
    End If
    If ModelCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VModel = @Model)"
    End If
    If ClassCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VClass = @ClassV)"
    End If
    If SeatsCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VSeats = @Seats)"
    End If
    If GrboxCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VGearbox = @GrBox)"
    End If
    If BranchCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (BranchID = @Branch)"
    End If
    Return SQLStr
End Function

EDIT: reply to comment

 Dim rs As OleDbDataReader = SQLcmd.ExecuteReader

                While rs.Read
                    VehDGrid.Rows.Add(rs("VehicleID"), rs("VMake"), rs("VModel"), rs("VRegYear"),
                                      rs("VFuel"), rs("VClass"), rs("VBody"), rs("VSeats"),
                                      rs("VGearbox"), rs("VReg"), rs("PPDay"), rs("VColour"))
                End While

Body:
You don't need a loop to file out the data grid.

And I would not mess if the conneciton is open or closed. All code written will have closed the connection, so code based on that assumpiton.

While the "@" name parameters for oleDB does not matter (for Access data engine), however, you might as well use them, since that code can be used in the future for sql server etc.

I would also NOT separate add where clause and THEN separate add parameters. ALWAYS add them both at the SAME time.

That way, you can change the order of the code, or even cut + paste more parts in, and it will always work. Since Access is sensitive to order of parameters, then this advice is EVEN MORE valuable (add sql, and parameters as a group in your code - not in two separate places. That way, you really can't mess up the order, since you pair this process in code.

As noted, you don't need a loop to add the rows to the data grid - it is a data aware code, and you can thus just send it the data table.

eg this:

    Using conn As New OleDbConnection(My.Settings.AccessDB)

        conn.Open()

        Using cmdSQL As New OleDbCommand("", conn)

            pAdd(cmdSQL, "VMake", MakeCBox)
            pAdd(cmdSQL, "Vmodel", ModelCBox)
            pAdd(cmdSQL, "VClass", ClassCBox)
            pAdd(cmdSQL, "VSeats", SeatsCBox)
            pAdd(cmdSQL, "VGearBox", GrboxCBox)
            pAdd(cmdSQL, "BranchID", BranchCBox)

            cmdSQL.CommandText &= " AND (VStatus = @VStatus)"
            cmdSQL.Parameters.AddWithValue("@VStatus", "ACTIVE")

            cmdSQL.CommandText = "SELECT * FROM Vehicles WHERE " & cmdSQL.CommandText
            Console.WriteLine(cmdSQL.CommandText)

            Dim rstData As New DataTable
            rstData.Load(cmdSQL.ExecuteReader)

            If rstData.Rows.Count = 0 Then
                MsgBox("no data")
            Else
                VehDGrid.DataSource = rstData
            End If

        End Using
    End Using

End Sub

Sub pAdd(cmd As OleDbCommand, sColumn As String,  c As ComboBox)

    If c.SelectedItem IsNot Nothing AndAlso c.Text <> "" Then

        Dim sP As String = "@" & sColumn
        If cmd.CommandText <> "" Then cmd.CommandText &= " AND "
        cmd.CommandText &= "(" & sColumn & " = " & sP & ")"
        cmd.Parameters.AddWithValue(sP, c.Text)

    End If

End Sub

Edit: Question about My.Settings.AccessDB

Well, be it desktop, or web based? I just used this:

Project->project properties, and then this:

So, in above, you can click on the "..." button, and that launches the connection builder. And once you save above, then the setting can be used from My.Settings."my setting name here".

So, for things like company name, perhaps a title, or whatever? You can build up and create your own settings. Once done, then these handy settings can be used in code.


问:
disableSelection on everything except input[type=text]
I am looking to use jQuery's "disableSelection()" function because I have a lot of drag and drop on the pages but I do not want to disable selection on input boxes, just everything else.

I have tried

```<code>$('body').disableSelection(); $('input').enableSelection();

$('body').not('input').disableSelection();
</code>```

still DISABLES EVERYTHING ON THE PAGE. Thank you.

答:
With

```<code>$('body').not('input').disableSelection();
</code>```

You disable selection on every instance of body that is not an input. Since body is not an input this will just disable selection on body.

Try this:

```<code>$('body *').not(':has(input)').not('input').disableSelection();
</code>```

However, like other people pointed out it's probably pretty useless disabling selection on things that aren't draggable in the first place. So maybe you should replace body with .drag or however you can select all the objects that are draggable (keeping the rest of the function the same).

Body:
I am looking to use jQuery's "disableSelection()" function because I have a lot of drag and drop on the pages but I do not want to disable selection on input boxes, just everything else.

I have tried

$('body').disableSelection(); $('input').enableSelection();

$('body').not('input').disableSelection();

still DISABLES EVERYTHING ON THE PAGE. Thank you.

Body:
With

$('body').not('input').disableSelection();

You disable selection on every instance of body that is not an input. Since body is not an input this will just disable selection on body.

Try this:

$('body *').not(':has(input)').not('input').disableSelection();

However, like other people pointed out it's probably pretty useless disabling selection on things that aren't draggable in the first place. So maybe you should replace body with .drag or however you can select all the objects that are draggable (keeping the rest of the function the same).


问:
Laravel 8 variable value from aggregate sum of multiple column values
I need to create a variable thats the aggregate sum of multiple values.  I have about 25 values to to add together--below is a small snippet.  The below works, but stringing all the values together with a + seems a bit dirty.  Is there another way?

```<code>// Calculate Modification Points
        $trackPTS = $this->track ? 20 : 0;
        $shockTowerPTS = $this->shock_tower ? 10 : 0;
        $loweringPTS = $this->lowering ? 10 : 0;
        $camberPTS = $this->camber ? 20 : 0;
        $monoballPTS = $this->monoball ? 10 : 0;
        $tubeFramePTS = $this->tube_frame ? 100 : 0;
        $pasmPTS = $this->pasm ? 20 : 0;
        $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;

        $totalModificationPoints = $treadWearPoints + $trackPTS + $shockTowerPTS + $loweringPTS + $camberPTS + $monoballPTS + $tubeFramePTS + $pasmPTS + $rearAxleSteerPTS;
</code>```

答:
This is one other way of doing the same thing.</p>
```<code>$totalModificationPoints = 0; //initial value

$totalModificationPoints += $trackPTS = $this->track ? 20 : 0;
$totalModificationPoints += $shockTowerPTS = $this->shock_tower ? 10 : 0;
$totalModificationPoints += $loweringPTS = $this->lowering ? 10 : 0;
$totalModificationPoints += $camberPTS = $this->camber ? 20 : 0;
$totalModificationPoints += $monoballPTS = $this->monoball ? 10 : 0;
$totalModificationPoints += $tubeFramePTS = $this->tube_frame ? 100 : 0;
$totalModificationPoints += $pasmPTS = $this->pasm ? 20 : 0;
$totalModificationPoints += $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;
</code>```

Body:
I need to create a variable thats the aggregate sum of multiple values.  I have about 25 values to to add together--below is a small snippet.  The below works, but stringing all the values together with a + seems a bit dirty.  Is there another way?

// Calculate Modification Points
        $trackPTS = $this->track ? 20 : 0;
        $shockTowerPTS = $this->shock_tower ? 10 : 0;
        $loweringPTS = $this->lowering ? 10 : 0;
        $camberPTS = $this->camber ? 20 : 0;
        $monoballPTS = $this->monoball ? 10 : 0;
        $tubeFramePTS = $this->tube_frame ? 100 : 0;
        $pasmPTS = $this->pasm ? 20 : 0;
        $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;

        $totalModificationPoints = $treadWearPoints + $trackPTS + $shockTowerPTS + $loweringPTS + $camberPTS + $monoballPTS + $tubeFramePTS + $pasmPTS + $rearAxleSteerPTS;

Body:
This is one other way of doing the same thing.

$totalModificationPoints = 0; //initial value

$totalModificationPoints += $trackPTS = $this->track ? 20 : 0;
$totalModificationPoints += $shockTowerPTS = $this->shock_tower ? 10 : 0;
$totalModificationPoints += $loweringPTS = $this->lowering ? 10 : 0;
$totalModificationPoints += $camberPTS = $this->camber ? 20 : 0;
$totalModificationPoints += $monoballPTS = $this->monoball ? 10 : 0;
$totalModificationPoints += $tubeFramePTS = $this->tube_frame ? 100 : 0;
$totalModificationPoints += $pasmPTS = $this->pasm ? 20 : 0;
$totalModificationPoints += $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;


问:
Google Sheets formula find highest or average from different sheets based on name

Hello stackoverflow, i want to fill  cell on Sheet B based on Sheet A data. i tried some guide "Max If (Max Value with Condition)" but its doesnt work give 0 (zero) value instead.

thank you

答:
try:

```<code>=QUERY(SheetA!B:G; "select B,max(G),avg(G) where G matches '^[0-9]+' group by B")
</code>```

Body:
try:

=QUERY(SheetA!B:G; "select B,max(G),avg(G) where G matches '^[0-9]+' group by B")


问:
translation from Datalog to SQL
I am still thinking on how to translate the recursivity of a Datalog program into SQL, such as

```<code>P(x,y) <- Q(x,y).
Q(x,y) <- P(x,z), A(y).
</code>```

where A/1 is an EDB predicate. This, there is a co-dependency between P and Q. For longer queries, how to solve this problem?

Moreover, is there any system completely implement the translation? If there is, may I know what system or which paper may I refer?

答: Logica does something like this.  It translates a datalog-like language into SQL for Google BigQuery, PostgreSQL and SQLite.</p>

Title: translation from Datalog to SQL

Body:
I am still thinking on how to translate the recursivity of a Datalog program into SQL, such as

P(x,y) <- Q(x,y).
Q(x,y) <- P(x,z), A(y).

where A/1 is an EDB predicate. This, there is a co-dependency between P and Q. For longer queries, how to solve this problem?

Moreover, is there any system completely implement the translation? If there is, may I know what system or which paper may I refer?


问:
Add image to GUI
I'm trying to add an image to a JPanel in IntelliJ's GUI editor. I can't find anywhere that lets me do this.

Anyone have any idea?

答:
You haven't defined what "adding an image" means. Is this a background image and other components will be added on top. Do you want the image to fill the entire panel or should the image be painted at its actual size? The approach will be different depending on the answer. Maybe you can use an existing component or maybe you will need to create a custom component.

See Background Panel for a couple of approaches.

Title: Add image to GUI