问:
How to get the position of the currently focussed input?
I need to know the position of the currently focussed input to make some calculations. At the end I want to call .measure() on it.

What I got:

```<code>import { TextInput } from 'react-native';

const { State: TextInputState } = TextInput;
var currentlyFocussedField      = TextInputState.currentlyFocusedField();

console.log('currentlyFocussedField', currentlyFocussedField);
</code>```

But this only returns the id of the text field (like 394, and the next field is 395). How can I access the real element/object or how do I get its position on the screen?

答:
Instead of:

var currentlyFocussedField      = TextInputState.currentlyFocusedField();

use:

var currentlyFocussedField      = TextInputState.currentlyFocusedInput();

Then you can:

currentlyFocussedField.measure(...)

Body:
I need to know the position of the currently focussed input to make some calculations. At the end I want to call .measure() on it.

What I got:

import { TextInput } from 'react-native';

const { State: TextInputState } = TextInput;
var currentlyFocussedField      = TextInputState.currentlyFocusedField();

console.log('currentlyFocussedField', currentlyFocussedField);

But this only returns the id of the text field (like 394, and the next field is 395). How can I access the real element/object or how do I get its position on the screen?


来源: stackexchange

问:
How to fix the error `found no layout file for "HTML" for "page"` in Hugo CMS?
I recently imported content from my WordPress page into Hugo. When I run hugo serve I get following error messages:

```<code>WARN 2020/02/17 20:51:06 found no layout file for "HTML" for "page": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
</code>```

The page in question starts like this:

```<code>---
linktitle: "The Title of the Post"
title: "The Title of the Post"
author: "Franz Drollig"
type: post
date: 2020-01-09T14:41:55+00:00
url: /the-title-of-post/
categories:
  - Uncategorized
weight: 10

---

This is the content of the post. This is the second sentence of the post.
</code>```

It is located in mysite/content/posts/YYYY-MM-DD-title.md.

The layouts directory is empty. However, the themes directory contains the book theme. This theme is also configured in the config.toml.

Another post, starting like shown below, is rendered correctly.

```<code>---
author: "Michael Henderson"
date: 2014-09-28
linktitle: Creating a New Theme
menu:
  main:
    parent: tutorials
next: /tutorials/github-pages-blog
prev: /tutorials/automated-deployments
title: Creating a New Theme
weight: 10
---

## Introduction
</code>```

Why is my post not rendered properly? How can I fix it?

答:
In my case, I missed this step:

```<code>echo theme = \"hugo-future-imperfect-slim\" >> config.toml
</code>```

Which adds your theme to the configuration.  After that, it was using the right Kinds / Layout elements from the theme.  More info in the quick start: https://gohugo.io/getting-started/quick-start/

ContentLicense: CC BY-SA 4.0

Body:
I recently imported content from my WordPress page into Hugo. When I run hugo serve I get following error messages:

WARN 2020/02/17 20:51:06 found no layout file for "HTML" for "page": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.

The page in question starts like this:

---
linktitle: "The Title of the Post"
title: "The Title of the Post"
author: "Franz Drollig"
type: post
date: 2020-01-09T14:41:55+00:00
url: /the-title-of-post/
categories:
  - Uncategorized
weight: 10

---

This is the content of the post. This is the second sentence of the post.

It is located in mysite/content/posts/YYYY-MM-DD-title.md.

The layouts directory is empty. However, the themes directory contains the book theme. This theme is also configured in the config.toml.

Another post, starting like shown below, is rendered correctly.

---
author: "Michael Henderson"
date: 2014-09-28
linktitle: Creating a New Theme
menu:
  main:
    parent: tutorials
next: /tutorials/github-pages-blog
prev: /tutorials/automated-deployments
title: Creating a New Theme
weight: 10
---

## Introduction

Why is my post not rendered properly? How can I fix it?

Body:
In my case, I missed this step:

echo theme = \"hugo-future-imperfect-slim\" >> config.toml

Which adds your theme to the configuration.  After that, it was using the right Kinds / Layout elements from the theme.  More info in the quick start: https://gohugo.io/getting-started/quick-start/


问:
Bazel: submodule in project does not use bazel , pushing to git doesnt include locally added BUILD file in submodule, how do i build?
I am just starting to learn how to use bazel following this tutorial

One thing I am unsure how to do is how to use a submodule, from my own repo for example. where I do not use bazel. The repo just has some c/h files that I need to pull in. To make things work locally I added a BUILD file in folder pulled in from submodules. However after I commit and push my changes the BUILD file is obviously not there. How do I add the c/h files from the submodule folder to my build. Bazel seems to be looking for a BUILD folder in that directory and there will be none, if for example someone else clones this repo.

currently my "main" Directory has this build file:

```<code>cc_library(
  name = "uCShell-main",
  srcs = ["main.c"],
  deps = ["//uCShell:uCShell-lib" ],
)

cc_binary(
   name = "uCShell-bin",
   deps = [":uCShell-main" , "//uCShell:uCShell-lib" ]
)
</code>```

and the folder with the pulled in submodule has this locally added BUILD file:

```<code>cc_library(
    name = "uCShell-lib",
    srcs = glob(["*.c"]),
    hdrs = glob(["*.h"]),
    visibility = ["//visibility:public"],
)
</code>```

This works and compiles just fine. However do correct any issues or misuse of Bazel you see here, I'd like to learn.
Ultimately to reiterate the issue, when I push this project the locally added BUILD file will not be in the project because it is not in the original submodule. So how can I inlcude the c/h files in that submodule in order to build my main. And I would like to leave it as a submodule. Ultimately I can just add a BUILD file for the submodule's repo, but would like to find a better way, for example what if this was not my repo where I can just add a BUILD file.

答:
If you use new_local_repository with a relative path to import the submodule, you can set build_file or build_file_content to add the BUILD file. You should be able to use that same  BUILD file as-is.

Because it will be in a different external repository, you'll need to access it via the corresponding label.

For example, if you put the BUILD file at build/BUILD.my_lib.bazel and this in WORKSPACE:

new_local_repository(
    name = "my_lib",
    path = "submodules/my_lib",
    build_file = "@//build:BUILD.my_lib.bazel",
)
```

then you can put @my_lib//:uCShell-lib in deps of any other target and it will all work.

Body:
I am just starting to learn how to use bazel following this tutorial

One thing I am unsure how to do is how to use a submodule, from my own repo for example. where I do not use bazel. The repo just has some c/h files that I need to pull in. To make things work locally I added a BUILD file in folder pulled in from submodules. However after I commit and push my changes the BUILD file is obviously not there. How do I add the c/h files from the submodule folder to my build. Bazel seems to be looking for a BUILD folder in that directory and there will be none, if for example someone else clones this repo.

currently my "main" Directory has this build file:

cc_library(
  name = "uCShell-main",
  srcs = ["main.c"],
  deps = ["//uCShell:uCShell-lib" ],
)

cc_binary(
   name = "uCShell-bin",
   deps = [":uCShell-main" , "//uCShell:uCShell-lib" ]
)

and the folder with the pulled in submodule has this locally added BUILD file:

cc_library(
    name = "uCShell-lib",
    srcs = glob(["*.c"]),
    hdrs = glob(["*.h"]),
    visibility = ["//visibility:public"],
)

This works and compiles just fine. However do correct any issues or misuse of Bazel you see here, I'd like to learn.
Ultimately to reiterate the issue, when I push this project the locally added BUILD file will not be in the project because it is not in the original submodule. So how can I inlcude the c/h files in that submodule in order to build my main. And I would like to leave it as a submodule. Ultimately I can just add a BUILD file for the submodule's repo, but would like to find a better way, for example what if this was not my repo where I can just add a BUILD file.

Body:
If you use new_local_repository with a relative path to import the submodule, you can set build_file or build_file_content to add the BUILD file. You should be able to use that same  BUILD file as-is.

Because it will be in a different external repository, you'll need to access it via the corresponding label.

For example, if you put the BUILD file at build/BUILD.my_lib.bazel and this in WORKSPACE:

new_local_repository(
    name = "my_lib",
    path = "submodules/my_lib",
    build_file = "@//build:BUILD.my_lib.bazel",
)

then you can put @my_lib//:uCShell-lib in deps of any other target and it will all work.


问:
How to set java version in the Azure hdinsight while creating a cluster
We are creating a cluster in Azure we need to upgrade the java version.
Here is the command -
az hdinsight create --name test_cluster --resource-group $resource_group --type spark --cluster-tier Standard --component-version Spark=$component_version --headnode-size $headnode_size --location $location --http-password $http_password --http-user $http_user --ssh-user $ssh_user --ssh-public-key "$ssh_pub_key" --storage-account $storage_account_name --storage-account-key $storage_account_key --storage-container $storage_container --subnet $subnet_name --vnet-name $vnet_name --version $version --workernode-count $workernode_count --workernode-size $workernode_size --tags Name=$cluster_name

Do we have an option to set the java version ?

答:
```<code>`Do we have an option to set the java version ?`
</code>```

No, We don't have an option to set the java version using Azure cli cmdlet.

We can only update the tags of the specified HDInsight cluster using below cmdlet.

```<code>az hdinsight update --name MyCluster --resource-group rg --tags key=value
</code>```

For more information about the supported az commands to Manage HDInsight resources, refer this document.

Body:
`Do we have an option to set the java version ?`

No, We don't have an option to set the java version using Azure cli cmdlet.

We can only update the tags of the specified HDInsight cluster using below cmdlet.

az hdinsight update --name MyCluster --resource-group rg --tags key=value

For more information about the supported az commands to Manage HDInsight resources, refer this document.


问:
Gunicorn worker terminated with signal 9
I am running a Flask application and hosting it on Kubernetes from a Docker container. Gunicorn is managing workers that reply to API requests.

The following warning message is a regular occurrence, and it seems like requests are being canceled for some reason. On Kubernetes, the pod is showing no odd behavior or restarts and stays within 80% of its memory and CPU limits.

```<code>[2021-03-31 16:30:31 +0200] [1] [WARNING] Worker with pid 26 was terminated due to signal 9
</code>```

How can we find out why these workers are killed?

答:
I encountered the same warning message when I limit the docker's memory, use like -m 3000m.

see docker-memory

and

gunicorn-Why are Workers Silently Killed?

The simple way to avoid this is set a high memory for docker or not set.

Body:
I am running a Flask application and hosting it on Kubernetes from a Docker container. Gunicorn is managing workers that reply to API requests.

The following warning message is a regular occurrence, and it seems like requests are being canceled for some reason. On Kubernetes, the pod is showing no odd behavior or restarts and stays within 80% of its memory and CPU limits.

[2021-03-31 16:30:31 +0200] [1] [WARNING] Worker with pid 26 was terminated due to signal 9

How can we find out why these workers are killed?


问:
How can we pass argument to function which itself is passed as argument in javascript
```<code>function fun (a, b)  {
        console.log(a + ' ' + b);
        return a == b;
 }

function test(condition) {

    for(let i = 0; i < 1; i++) {
        if(condition()){
            break;
        }
    }
}
</code>```

How can we pass function fun as an argument inside function test with the argument a and b (a and b are variable). writing test(fun('a', 'b')); is resulting in an error.

答:
You can use a closure like this:

test(function(){ return fun('a', 'b'); });
```

Body:
function fun (a, b)  {
        console.log(a + ' ' + b);
        return a == b;
 }

function test(condition) {

    for(let i = 0; i < 1; i++) {
        if(condition()){
            break;
        }
    }
}

How can we pass function fun as an argument inside function test with the argument a and b (a and b are variable). writing test(fun('a', 'b')); is resulting in an error.


问:
React using REDUX useSelector error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'projectname')
I am getting this error when I load data using useSelector, however it returns the correct information. I gather that the data is loaded after the error, but how can I avoid it?:

```<code>           const dispatch = useDispatch();
            const { identify } = useParams();

            //set loader
            const [loaderthis, setLoaderthis] = useState(true);
            const [breadCrumb, setBreadCrumb] = useState("");

            //send identify to REDUX to obtain this ID project
            useEffect(() => {
                if (identify) {
                const fetchData = () => {
                    return dispatch(getProjectById(identify));
                };
                fetchData();
                }
            }, []);

            //get this project from REDUX
            const getProj = useSelector(
                (state: RootState) => state.projectreducer.detail
            );
            //HERE WHEN I LOG getProj i get the data objet right!!!
            console.log(getProj)

            //set loading to false when proyecto is valid
            useEffect(() => {
                setTimeout(() => {
                const fetchBread = async () => {
                    let namePro = getProj.projectname;  //ERROR HERE??
                    return setBreadCrumb(namePro || "");
                };
                fetchBread();
                setLoaderthis(false);
                }, 500);
            }, [loaderthis]);
</code>```

EDIT: this is the object it returns

答: I guess the getProj state slice is populated after an API call. So it's undefined before the API call responds, try using the optional chain getProj?.projectname; And, add getProj as dependences of useEffect hook, so that when getProj changes, the useEffect will execute again.

Body:
I am getting this error when I load data using useSelector, however it returns the correct information. I gather that the data is loaded after the error, but how can I avoid it?:

           const dispatch = useDispatch();
            const { identify } = useParams();

            //set loader
            const [loaderthis, setLoaderthis] = useState(true);
            const [breadCrumb, setBreadCrumb] = useState("");

            //send identify to REDUX to obtain this ID project
            useEffect(() => {
                if (identify) {
                const fetchData = () => {
                    return dispatch(getProjectById(identify));
                };
                fetchData();
                }
            }, []);

            //get this project from REDUX
            const getProj = useSelector(
                (state: RootState) => state.projectreducer.detail
            );
            //HERE WHEN I LOG getProj i get the data objet right!!!
            console.log(getProj)

            //set loading to false when proyecto is valid
            useEffect(() => {
                setTimeout(() => {
                const fetchBread = async () => {
                    let namePro = getProj.projectname;  //ERROR HERE??
                    return setBreadCrumb(namePro || "");
                };
                fetchBread();
                setLoaderthis(false);
                }, 500);
            }, [loaderthis]);

EDIT: this is the object it returns


问:
How to attache a volume to kubernetes pod container like in docker?
I am new to Kubernetes but familiar with docker.

Docker Use Case

Usually, when I want to persist data I just create a volume with a name then attach it to the container, and even when I stop it then start another one with the same image I can see the data persisting.
So this is what i used to do in docker

docker volume create nginx-storage
run -it --rm -v nginx-storage:/usr/share/nginx/html -p 80:80 nginx:1.14.2
```

then I:

Create a new html file in /usr/share/nginx/html

Stop container

Run the same docker run command again (will create another container with same volume)

html file exists (which means data persisted in that volume)

Kubernetes Use Case

Usually, when I work with Kubernetes volumes I specify a PVC (PersistentVolumeClaim) and PV (PersistentVolume) using hostPath which will bind mount directory or a file from the host machine to the container.

what I want to do is reproduce the same behavior specified in the previous example (Docker Use Case) so how can I do that? Is Kubernetes creating volumes process is different from Docker? and if possible providing a YAML file would help me understand.

答:
I managed to do that by creating a PVC only this is how I did it (with an Nginx image):

nginx-pvc.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nginx-data
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 100Mi
```
<p><strong>nginx-deployment.yaml</strong></p>
<pre class="lang-yaml prettyprint-override"><code># Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template: # template for the pods
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.14.2
          volumeMounts:
            - mountPath: /usr/share/nginx/html
              name: nginx-data
      volumes:
        - name: nginx-data
          persistentVolumeClaim:
            claimName: nginx-data
      restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: nginx
  ports:
    - name: http
      port: 80
      nodePort: 30080
  type: NodePort
</code>```

Once I run kubectl apply on the PVC then on the deployment going to localhost:30080 will show 404 not found page means that all data in the /usr/share/nginx/html  was deleted once the container gets started and that's because it's bind mounting a dir from the k8s cluster node to that container as a volume:

```<code>/usr/share/nginx/html <-- dir in volume
/var/lib/k8s-pvs/nginx2-data/pvc-9ba811b0-e6b6-4564-b6c9-4a32d04b974f <-- dir from node (was automatically created)
</code>```

I tried adding a new file into that container in the html dir as a new index.html file, then deleted the container, a new container was created by the pod and checking localhost:30080 worked with the newly created home page

I tried deleting the deployment and reapplying it (without deleting the PVC) checked localhost:30080 and everything still persists.

An alternative solution specified in the comments kubernetes.io/docs/tasks/configure-pod-container/… by
larsks

Body:
I am new to Kubernetes but familiar with docker.

Docker Use Case

Usually, when I want to persist data I just create a volume with a name then attach it to the container, and even when I stop it then start another one with the same image I can see the data persisting.
So this is what i used to do in docker

docker volume create nginx-storage
run -it --rm -v nginx-storage:/usr/share/nginx/html -p 80:80 nginx:1.14.2

then I:

Create a new html file in /usr/share/nginx/html

Stop container

Run the same docker run command again (will create another container with same volume)

html file exists (which means data persisted in that volume)

Kubernetes Use Case

Usually, when I work with Kubernetes volumes I specify a PVC (PersistentVolumeClaim) and PV (PersistentVolume) using hostPath which will bind mount directory or a file from the host machine to the container.

what I want to do is reproduce the same behavior specified in the previous example (Docker Use Case) so how can I do that? Is Kubernetes creating volumes process is different from Docker? and if possible providing a YAML file would help me understand.

Body:
I managed to do that by creating a PVC only this is how I did it (with an Nginx image):

nginx-pvc.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nginx-data
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 100Mi

nginx-deployment.yaml

# Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template: # template for the pods
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.14.2
          volumeMounts:
            - mountPath: /usr/share/nginx/html
              name: nginx-data
      volumes:
        - name: nginx-data
          persistentVolumeClaim:
            claimName: nginx-data
      restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: nginx
  ports:
    - name: http
      port: 80
      nodePort: 30080
  type: NodePort

Once I run kubectl apply on the PVC then on the deployment going to localhost:30080 will show 404 not found page means that all data in the /usr/share/nginx/html  was deleted once the container gets started and that's because it's bind mounting a dir from the k8s cluster node to that container as a volume:

/usr/share/nginx/html <-- dir in volume
/var/lib/k8s-pvs/nginx2-data/pvc-9ba811b0-e6b6-4564-b6c9-4a32d04b974f <-- dir from node (was automatically created)

I tried adding a new file into that container in the html dir as a new index.html file, then deleted the container, a new container was created by the pod and checking localhost:30080 worked with the newly created home page

I tried deleting the deployment and reapplying it (without deleting the PVC) checked localhost:30080 and everything still persists.

An alternative solution specified in the comments kubernetes.io/docs/tasks/configure-pod-container/… by
larsks


问:
how can I get the function to return index of 2 numbers that add up to a target value
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(</p>
```<code>def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex] + list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex + 1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)
</code>```

答:
Not so sure about the approach in general to the task you are trying to solve, depending on the algorithm you implement and the starting parameters you may receive multiple results and not one single value.

Looking at your example list and target value, the pairs (1,4) (2,3) would both solve for the target value.

In principle, in case you're not using any IDE that keeps track of the variable values or don't want to use any library to keep things very lightweight, I'd recommend to use pen and paper and walk through the variable values of your loop or have printouts in the code itself as a simple means to debug, like this:

def solution(list, target):
firstindex = 0
secondindex = -1

```<code>while(firstindex <= len(list)-1):
    print(firstindex)
    print(secondindex)

    if list[firstindex] + list[secondindex] == target:
        print(f"The sum was found at index {firstindex} and {secondindex}")
        break

    else:
        firstindex = firstindex + 1
        secondindex = secondindex - 1
</code>```

#I am calling the function here
solution([1,2,3,4,5, 6], 5)

What you will find is that your second index starting at -1 will decrement simultaneously to the first index, while it does not stay fixed while iterating through the first index. Hope that helps a bit in the debugging.
Really, try to solve this question algorithmically on paper first.

Cheers,
Let me know how it goes

Edit: I utterly messed up my thinking, as Python does indeed use negative indices for starting with the last item of the list and walking back. Need to stop thinking C...

Body:
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(

def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex] + list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex + 1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)

Body:
Not so sure about the approach in general to the task you are trying to solve, depending on the algorithm you implement and the starting parameters you may receive multiple results and not one single value.

Looking at your example list and target value, the pairs (1,4) (2,3) would both solve for the target value.

In principle, in case you're not using any IDE that keeps track of the variable values or don't want to use any library to keep things very lightweight, I'd recommend to use pen and paper and walk through the variable values of your loop or have printouts in the code itself as a simple means to debug, like this:

def solution(list, target):
firstindex = 0
secondindex = -1

while(firstindex <= len(list)-1):
    print(firstindex)
    print(secondindex)

    if list[firstindex] + list[secondindex] == target:
        print(f"The sum was found at index {firstindex} and {secondindex}")
        break

    else:
        firstindex = firstindex + 1
        secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)

What you will find is that your second index starting at -1 will decrement simultaneously to the first index, while it does not stay fixed while iterating through the first index. Hope that helps a bit in the debugging.
Really, try to solve this question algorithmically on paper first.

Cheers,
Let me know how it goes

Edit: I utterly messed up my thinking, as Python does indeed use negative indices for starting with the last item of the list and walking back. Need to stop thinking C...


问:
Share extension ios swift
I have created a share extension with some buttons in it and inherited that extension with UIViewcontroller. when I create @IBAction of those UIButtons it never gets called on clicking the button.

```<code>import UIKit
import Social

class ShareViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

//    override func isContentValid() -> Bool {
//        // Do validation of contentText and/or NSExtensionContext attachments here
//        return true
//    }
//
//    override func didSelectPost() {
//        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
//
//        // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
//        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
//    }
//
//    override func configurationItems() -> [Any]! {
//        // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
//        return []
//    }

    @IBAction func btnBackClicked(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func btnCancleClicked(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func btnSaveClicked(_ sender: Any) {

    }
}
</code>```

答:
I think your button actions are being called, just that calling self.dismiss(animated: true, completion: nil) will not actually dismiss your share extension.

With reference to this answer, you should be using:

self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)

OR

self.extensionContext!.cancelRequest(withError:NSError(domain: Bundle.main.bundleIdentifier!, code: 0))

Title: Share extension ios swift

Body:
I have created a share extension with some buttons in it and inherited that extension with UIViewcontroller. when I create @IBAction of those UIButtons it never gets called on clicking the button.

import UIKit
import Social

class ShareViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

//    override func isContentValid() -> Bool {
//        // Do validation of contentText and/or NSExtensionContext attachments here
//        return true
//    }
//
//    override func didSelectPost() {
//        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
//
//        // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
//        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
//    }
//
//    override func configurationItems() -> [Any]! {
//        // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
//        return []
//    }

    @IBAction func btnBackClicked(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func btnCancleClicked(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func btnSaveClicked(_ sender: Any) {

    }
}


问:
Yii2 GridView hide column conditionally
I am displaying some columns in Yii2 GridView widget, 'Executive Name' is one of those but it should be displayed only when a Supervisor is logged in not when Executive logged in.

When I am hard coding visible to zero it is not displaying as follows:

```<code>[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => '0',
],
</code>```

But I want to display it conditionally something like this:

```<code>[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => function ($data) {
        if ($data->hc_customersupport->is_supervisor) {
            return '1'; // or return true;
        } else {
            return '0'; // or return false;
        }
    },
],
</code>```

Please tell if this approach is correct.

答:
visible is boolean, you dont need use function.
you can add condition like this

```<code>'visible'=> ($data=="supervisor"),
</code>```

if true will be hidden , if false will be visible.
vice versa

```<code>'visible'=> ($data!="supervisor"),
</code>```

ContentLicense: CC BY-SA 3.0

Title: Yii2 GridView hide column conditionally

Body:
I am displaying some columns in Yii2 GridView widget, 'Executive Name' is one of those but it should be displayed only when a Supervisor is logged in not when Executive logged in.

When I am hard coding visible to zero it is not displaying as follows:

[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => '0',
],

But I want to display it conditionally something like this:

[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => function ($data) {
        if ($data->hc_customersupport->is_supervisor) {
            return '1'; // or return true;
        } else {
            return '0'; // or return false;
        }
    },
],

Please tell if this approach is correct.

Body:
visible is boolean, you dont need use function.
you can add condition like this

'visible'=> ($data=="supervisor"),

if true will be hidden , if false will be visible.
vice versa

'visible'=> ($data!="supervisor"),


问:
Collecting multiple unknown inputs
Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.

Ex: If the input is:

15 20 0 5
the output is:

10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!

```<code>nums = []
for i in range(0, 4):
    number = int(input('Enter number'))
    nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)
</code>```

答:
One solution is to have the user specify how many numbers they want to take the average of.  For instance:

```<code>nums = []
n = int(input('How many numbers: '))
for i in range(n):
    number = int(input('Enter number: '))
    nums.append(number)
avg = sum(nums) / n
print(max(nums), avg)
</code>```

Alternatively, if you want a function that itself takes a variable number of arguments, you'll need to use the "*args" operator. For instance,

```<code>def my_average(*args):
    return sum(args)/len(args)
</code>```

An example usage:

```<code>print(my_average(1),my_average(1,2),my_average(1,2,3))
</code>```

Result:

```<code>1.0 1.5 2.0
</code>```

Title: Collecting multiple unknown inputs

Body:
Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.

Ex: If the input is:

15 20 0 5
the output is:

10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!

nums = []
for i in range(0, 4):
    number = int(input('Enter number'))
    nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)

Body:
One solution is to have the user specify how many numbers they want to take the average of.  For instance:

nums = []
n = int(input('How many numbers: '))
for i in range(n):
    number = int(input('Enter number: '))
    nums.append(number)
avg = sum(nums) / n
print(max(nums), avg)

Alternatively, if you want a function that itself takes a variable number of arguments, you'll need to use the "*args" operator. For instance,

def my_average(*args):
    return sum(args)/len(args)

An example usage:

print(my_average(1),my_average(1,2),my_average(1,2,3))

Result:

1.0 1.5 2.0


问:
webpack & ES6 - conditional import and export
I have some configuration keys like below:

```<code>/config
  /db
    /dev.js
    /index.js
    /prod.js
</code>```

I import keys like this:

```<code>import dbConfig from './config/db'
</code>```

But in index.js, I use CommonJS syntax to export module conditionally. Is it possible to do it with ES6? If yes, how?

```<code>module.exports = process.env.NODE_ENV === 'production'
  ? require('./prod')
  : require('./dev');
</code>```

I am using webpack ^4.6.0. Tried my luck with babel-plugin-dynamic-import-webpack but it didn't work.

I may not aware of some best practices or plugins that I can use, so I'd appreciate your thoughts.

答:
I don't believe you actually need to worry about this. There are tree-trimming algorithms in modern build systems that should ensure you end up with only one version in dev or production.

```<code># mockValue.js
const mockValue = 'mock';

export default mockValue;

# realValue.js
const realValue = 'real';

export default realValue;

# test.js
import mockValue from 'mockValue';
import realValue from 'realValue';

let test;
if (process.env.NODE_ENV === 'production') {
  test = realValue;
} else {
  test = mockValue;
}

export default test;

# index.js
import test from 'test';

console.log(test);
</code>```

During development, realValue should get trimmed. During a production build, mockValue should get trimmed. To verify this, you could build the test project above and inspect the output for 'mock' (but you're not likely to find it).

Body:
I have some configuration keys like below:

/config
  /db
    /dev.js
    /index.js
    /prod.js

I import keys like this:

import dbConfig from './config/db'

But in index.js, I use CommonJS syntax to export module conditionally. Is it possible to do it with ES6? If yes, how?

module.exports = process.env.NODE_ENV === 'production'
  ? require('./prod')
  : require('./dev');

I am using webpack ^4.6.0. Tried my luck with babel-plugin-dynamic-import-webpack but it didn't work.

I may not aware of some best practices or plugins that I can use, so I'd appreciate your thoughts.

Body:
I don't believe you actually need to worry about this. There are tree-trimming algorithms in modern build systems that should ensure you end up with only one version in dev or production.

# mockValue.js
const mockValue = 'mock';

export default mockValue;

# realValue.js
const realValue = 'real';

export default realValue;

# test.js
import mockValue from 'mockValue';
import realValue from 'realValue';

let test;
if (process.env.NODE_ENV === 'production') {
  test = realValue;
} else {
  test = mockValue;
}

export default test;

# index.js
import test from 'test';

console.log(test);

During development, realValue should get trimmed. During a production build, mockValue should get trimmed. To verify this, you could build the test project above and inspect the output for 'mock' (but you're not likely to find it).


问:
ScrollView horizontal pagination only works on Android doesn't work on IOS react native expo cli
Everyone.
I need your help.
I made one app with react native expo cli.
But one issue occurred.
I used the ScrollView for horizontal pagination.

```<code>*<SafeAreaView>
      <ScrollView
        snapToInterval={wp("100%")}
        horizontal
        pagingEnabled
        nestedScrollEnabled
        decelerationRate="fast"
      >
        {[...Array(this.state.pageCount)].map((num, index) => {
          return (
            <View
              key={"view" + index}
              style={{
                width: wp("100%"),
                height: "100%",
                display: "flex",
                flexDirection: "row",
                flexWrap: "wrap",
                alignContent: "center",
                justifyContent: "center",
              }}
            >
              {this.state.categories
                .slice(index * 6, index * 6 + 6)
                .map((item, key) => (
                  <TouchableOpacity
                    key={"touch" + key}
                    style={styles.itemStyle}
                    onPress={() => this.openModal(item)}
                    onLongPress={() => this.selectItem(item)}
                  >
                    <Image
                      source={{ uri: item.Foto }}
                      style={{ height: 120, width: "90%" }}
                      resizeMode="cover"
                    />
                    <Text style={{ fontSize: 18 }}>{item.Precio}</Text>
                    <Text style={{ fontSize: 12 }}>{item.Gemas}</Text>
                  </TouchableOpacity>
                ))}
            </View>
          );
        })}
      </ScrollView>
    </SafeAreaView>*
</code>```

But the pagination only works on Android Phone and doesn't work on iPhone.
Please help me.

答:
Your <ScrollView> should have style flex: 1, to allow the view fit the screen size.

The width of the Views inside the Scroll should have a numerical value. A width of 100% inside a scrollview is undefined. Your approach should be related to the dimension of the screen.

```<code>// import dimensions lib
import Dimensions from 'react-native';

...
...
...

// capture the width of the screen
const screenWidth = Dimensions.get('screen').width;

...
...
...

{[...Array(this.state.pageCount)].map((num, index) => {
  return (
    <View
      key={"view" + index}
      style={{
        width: screenWidth,
        height: "100%",
        display: "flex",
        flexDirection: "row",
        flexWrap: "wrap",
        alignContent: "center",
        justifyContent: "center",
      }}
    >
      {this.state.categories
        .slice(index * 6, index * 6 + 6)
        .map((item, key) => (
          <TouchableOpacity
            key={"touch" + key}
            style={styles.itemStyle}
            onPress={() => this.openModal(item)}
            onLongPress={() => this.selectItem(item)}
          >
            <Image
              source={{ uri: item.Foto }}
              style={{ height: 120, width: "90%" }}
              resizeMode="cover"
            />
            <Text style={{ fontSize: 18 }}>{item.Precio}</Text>
            <Text style={{ fontSize: 12 }}>{item.Gemas}</Text>
          </TouchableOpacity>
        ))}
    </View>
  );
})}
</code>```

Body:
Everyone.
I need your help.
I made one app with react native expo cli.
But one issue occurred.
I used the ScrollView for horizontal pagination.

*<SafeAreaView>
      <ScrollView
        snapToInterval={wp("100%")}
        horizontal
        pagingEnabled
        nestedScrollEnabled
        decelerationRate="fast"
      >
        {[...Array(this.state.pageCount)].map((num, index) => {
          return (
            <View
              key={"view" + index}
              style={{
                width: wp("100%"),
                height: "100%",
                display: "flex",
                flexDirection: "row",
                flexWrap: "wrap",
                alignContent: "center",
                justifyContent: "center",
              }}
            >
              {this.state.categories
                .slice(index * 6, index * 6 + 6)
                .map((item, key) => (
                  <TouchableOpacity
                    key={"touch" + key}
                    style={styles.itemStyle}
                    onPress={() => this.openModal(item)}
                    onLongPress={() => this.selectItem(item)}
                  >
                    <Image
                      source={{ uri: item.Foto }}
                      style={{ height: 120, width: "90%" }}
                      resizeMode="cover"
                    />
                    <Text style={{ fontSize: 18 }}>{item.Precio}</Text>
                    <Text style={{ fontSize: 12 }}>{item.Gemas}</Text>
                  </TouchableOpacity>
                ))}
            </View>
          );
        })}
      </ScrollView>
    </SafeAreaView>*

But the pagination only works on Android Phone and doesn't work on iPhone.
Please help me.

Body:
Your <ScrollView> should have style flex: 1, to allow the view fit the screen size.

The width of the Views inside the Scroll should have a numerical value. A width of 100% inside a scrollview is undefined. Your approach should be related to the dimension of the screen.

// import dimensions lib
import Dimensions from 'react-native';

...
...
...

// capture the width of the screen
const screenWidth = Dimensions.get('screen').width;

...
...
...

{[...Array(this.state.pageCount)].map((num, index) => {
  return (
    <View
      key={"view" + index}
      style={{
        width: screenWidth,
        height: "100%",
        display: "flex",
        flexDirection: "row",
        flexWrap: "wrap",
        alignContent: "center",
        justifyContent: "center",
      }}
    >
      {this.state.categories
        .slice(index * 6, index * 6 + 6)
        .map((item, key) => (
          <TouchableOpacity
            key={"touch" + key}
            style={styles.itemStyle}
            onPress={() => this.openModal(item)}
            onLongPress={() => this.selectItem(item)}
          >
            <Image
              source={{ uri: item.Foto }}
              style={{ height: 120, width: "90%" }}
              resizeMode="cover"
            />
            <Text style={{ fontSize: 18 }}>{item.Precio}</Text>
            <Text style={{ fontSize: 12 }}>{item.Gemas}</Text>
          </TouchableOpacity>
        ))}
    </View>
  );
})}


问:
What is the equivalent of Rust's Vec<u8> in Java/Kotlin?
What is the equivalent type of Vec in rust to Java/kotlin?

Vec<u8> return [48, 130, 6, 55, 2, 1, 3, 48, 130, 5, 253, 6, 9, 42, 134, 72, 134, ...] in rust.

I tried using ByteArray in kotlin but as you can see few elements are out of byte range it gives out of bounds. Should we use IntArray? Or something else?

答:
The ByteArray in Kotlin is for signed bytes. If you want unsigned bytes (0-255), you can use the experimental UByteArray

val b = ubyteArrayOf(48u,130u,6u,200u)
```
<p>or to return it from a function</p>
<pre class="lang-kotlin prettyprint-override"><code>fun getBytes(): UByteArray {
    return ubyteArrayOf(48u,130u,6u,200u)
}
</code>```

Body:
The ByteArray in Kotlin is for signed bytes. If you want unsigned bytes (0-255), you can use the experimental UByteArray

val b = ubyteArrayOf(48u,130u,6u,200u)

or to return it from a function

fun getBytes(): UByteArray {
    return ubyteArrayOf(48u,130u,6u,200u)
}


问:
Pandas Python - How to create new columns with MultiIndex from pivot table
I have created a pivot table with 2 different types of values i) Number of apples from 2017-2020, ii) Number of people from 2017-2020. I want to create additional columns to calculate iii) Apples per person from 2017-2020. How can I do so?

Current code for pivot table:

```<code>tdf = df.pivot_table(index="States",
                     columns="Year",
                     values=["Number of Apples","Number of People"],
                     aggfunc= lambda x: len(x.unique()),
                     margins=True)
tdf
</code>```

Here is my current pivot table:

```<code>                Number of Apples                  Number of People
                2017    2018    2019    2020      2017    2018    2019    2020
California        10      18      20      25         2       3       4       5
West Virginia      8      35      25      12         2       5       5       4
...
</code>```

I want my pivot table to look like this, where I add additional columns to divide Number of Apples by Number of People.

```<code>                Number of Apples                  Number of People                  Number of Apples per Person
                2017    2018    2019    2020      2017    2018    2019    2020      2017    2018    2019    2020
California        10      18      20      25         2       3       4       5       5       6       5       5
West Virginia      8      35      25      12         2       5       5       4       4       7       5       3
</code>```

I've tried a few things, such as:

Creating a new column via assigning new column names, but does not work with multiple column index tdf["Number of Apples per Person"][2017] = tdf["Number of Apples"][2017] / tdf["Number of People"][2017]

Tried the other assignment method tdf.assign(tdf["Number of Apples per Person"][2017] = tdf["Enrollment ID"][2017] / tdf["Student ID"][2017]); got this error SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Appreciate any help! Thanks

答:
What you can do here is stack(), do your thing, and then unstack():

```<code>s = df.stack()
s['Number of Apples per Person'] = s['Number of Apples'] / s['Number of People']
df = s.unstack()
</code>```

Output:

```<code>>>> df
              Number of Apples                Number of People                Number of Apples per Person
                          2017 2018 2019 2020             2017 2018 2019 2020                        2017 2018 2019 2020
California                  10   18   20   25                2    3    4    5                         5.0  6.0  5.0  5.0
West Virginia                8   35   25   12                2    5    5    4                         4.0  7.0  5.0  3.0
</code>```

One-liner:

```<code>df = df.stack().pipe(lambda x: x.assign(**{'Number of Apples per Person': x['Number of Apples'] / x['Number of People']})).unstack()
</code>```

Body:
I have created a pivot table with 2 different types of values i) Number of apples from 2017-2020, ii) Number of people from 2017-2020. I want to create additional columns to calculate iii) Apples per person from 2017-2020. How can I do so?

Current code for pivot table:

tdf = df.pivot_table(index="States",
                     columns="Year",
                     values=["Number of Apples","Number of People"],
                     aggfunc= lambda x: len(x.unique()),
                     margins=True)
tdf

Here is my current pivot table:

                Number of Apples                  Number of People
                2017    2018    2019    2020      2017    2018    2019    2020
California        10      18      20      25         2       3       4       5
West Virginia      8      35      25      12         2       5       5       4
...

I want my pivot table to look like this, where I add additional columns to divide Number of Apples by Number of People.

                Number of Apples                  Number of People                  Number of Apples per Person
                2017    2018    2019    2020      2017    2018    2019    2020      2017    2018    2019    2020
California        10      18      20      25         2       3       4       5       5       6       5       5
West Virginia      8      35      25      12         2       5       5       4       4       7       5       3

I've tried a few things, such as:

Creating a new column via assigning new column names, but does not work with multiple column index tdf["Number of Apples per Person"][2017] = tdf["Number of Apples"][2017] / tdf["Number of People"][2017]

Tried the other assignment method tdf.assign(tdf["Number of Apples per Person"][2017] = tdf["Enrollment ID"][2017] / tdf["Student ID"][2017]); got this error SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Appreciate any help! Thanks

Body:
What you can do here is stack(), do your thing, and then unstack():

s = df.stack()
s['Number of Apples per Person'] = s['Number of Apples'] / s['Number of People']
df = s.unstack()

Output:

>>> df
              Number of Apples                Number of People                Number of Apples per Person
                          2017 2018 2019 2020             2017 2018 2019 2020                        2017 2018 2019 2020
California                  10   18   20   25                2    3    4    5                         5.0  6.0  5.0  5.0
West Virginia                8   35   25   12                2    5    5    4                         4.0  7.0  5.0  3.0

One-liner:

df = df.stack().pipe(lambda x: x.assign(**{'Number of Apples per Person': x['Number of Apples'] / x['Number of People']})).unstack()


问:
Why can we use the .length property in string types?
Hello I'm new to JS and object-oriented programming in general.
I have two questions considering this

```<code>let arr = [1,2,3]
let a = 'hi'
</code>```

When I run typeof(), arr is 'object' and a is 'string' right?

So my question is ,

When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?

Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.

答:
When you declare [1,2,...] you are declaring an object of class Array, which, in it's prototype, has a "length" property. Think of it as a variable that gets updated when you add or remove elements from the array.

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Strings are also objects in Javascript, and a string is also considered an array of characters, thus having the "length" property as well.

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

Body:
Hello I'm new to JS and object-oriented programming in general.
I have two questions considering this

let arr = [1,2,3]
let a = 'hi'

When I run typeof(), arr is 'object' and a is 'string' right?

So my question is ,

When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?

Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.


问:
"You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter
"You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without 'android:exported' property set. This file can't be installed on Android 12 or higher."

My Client is getting this error while uploading my App on Play Store. I have resolved the issue on on my side. but how Can I test this on Android Studio. As I was not getting the error earlier as well? (How I solved this ? I defined android:exported Property in Manifest.xml).

Complied SDK : 31
minSDK : 19

答: It's a change in Android as of 12.  Exported used to have a default.  For greater security it no longer has a default and you must specify the value. See https://developer.android.com/about/versions/12/behavior-changes-12 for more details.</p>


问:
No reverse match. Ideas how to fix?
Can anyone figure out why I'm getting a no reverse match error here:

urls.py:

```<code>urlpatterns = [
    path('', views.ReservationsFormView.as_view(), name='reservations'),
    path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"),
    path('reservation_complete/', ReservationCompleteView.as_view(),
name="reservation_complete"),
    path('reservations_account/', ReservationAccountView.as_view(),
name="reservations_account"),
    path('delete/<slug:pk>/', DeleteReservationView.as_view(),
name="delete_reservation"),
]
</code>```

It's only happening, so far, on my edit/delete paths (the one's with the <slug:pk>)

views.py:

```<code>class ReservationsFormView(CreateView):
    model = Reservations
    template_name = "reservations/reservations.html"
    form_class = ReservationForm
    success_url = "reservation_complete/"

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    form_class = ReservationForm
    template_name = 'reservations/edit_reservation.html'
    success_url = "/reservations_account/"
    model = Reservations

    def test_func(self):
        return self.request.user == self.get_object().user

class ReservationCompleteView(CreateView):
    template_name = "reservations/reservation_complete.html"
    success_url = "/reservation_complete/"
    form_class = ReservationForm
    model = Reservations

class ReservationAccountView(ListView):
    template_name = "reservations/reservations_account.html"
    model = Reservations

    def get_context_data(self, **kwargs):
        context = {
            'reservations': self.model.objects.filter(user=self.request.user),
        }
        return context

class DeleteReservationView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    """ A view to delete an reservation """
    model = Reservations
    success_url = "/reservations_account/"

    def test_func(self):
        return self.request.user == self.get_object().user
</code>```

Models.py File:

```<code>class Reservations(models.Model):

    """ reservation form categories and attributes """
    user = models.OneToOneField(User, on_delete=models.CASCADE,
unique=True)
    name = models.CharField(max_length=50)
    phone_number = models.CharField(validators=[phoneNumberRegex],
max_length=16, unique=True)
    email = models.EmailField()
    date = models.DateField()
    time = models.CharField(choices=time_options, default="12pm",
max_length=10)
    number_of_party = models.IntegerField(choices=party_size,
default=1)
    reservation_id = models.UUIDField(primary_key=True,
default=uuid.uuid4, editable=False)
</code>```

Corresponding Html is:

```<code><button href="{% url 'edit_reservation' reservation.id %}" type="button" class="btn btn-dark">Edit</a>
<button href="{% url 'delete_reservation' reservation.id %}" type="button" class="btn btn-dark">Delete</a>
</code>```

Error Message:

```<code>NoReverseMatch: Reverse for 'delete_reservation' with no arguments not found. 1 pattern(s) tried: ['reservations/delete/(?P<pk>[-a-zA-Z0-9_]+)/$']
</code>```

Really hoping it's something simple.
Any help is appreciated.
If you need to see more code, let me know and i'll update with what's needeed.

答:
If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.

So you should use pk or reservation_id.

also pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or reservation_id or whatever.

```<code><button href="{% url 'edit_reservation' reservation.reservation_id %}" type="button" class="btn btn-dark">Edit</a>
<button href="{% url 'delete_reservation' reservation.reservation_id %}" type="button" class="btn btn-dark">Delete</a>
</code>```

or use pk:

```<code><button href="{% url 'edit_reservation' reservation.pk %}" type="button" class="btn btn-dark">Edit</a>
    <button href="{% url 'delete_reservation' reservation.pk %}" type="button" class="btn btn-dark">Delete</a>
</code>```

Title: No reverse match. Ideas how to fix?

Body:
Can anyone figure out why I'm getting a no reverse match error here:

urls.py:

urlpatterns = [
    path('', views.ReservationsFormView.as_view(), name='reservations'),
    path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"),
    path('reservation_complete/', ReservationCompleteView.as_view(),
name="reservation_complete"),
    path('reservations_account/', ReservationAccountView.as_view(),
name="reservations_account"),
    path('delete/<slug:pk>/', DeleteReservationView.as_view(),
name="delete_reservation"),
]

It's only happening, so far, on my edit/delete paths (the one's with the <slug:pk>)

views.py:

class ReservationsFormView(CreateView):
    model = Reservations
    template_name = "reservations/reservations.html"
    form_class = ReservationForm
    success_url = "reservation_complete/"

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    form_class = ReservationForm
    template_name = 'reservations/edit_reservation.html'
    success_url = "/reservations_account/"
    model = Reservations

    def test_func(self):
        return self.request.user == self.get_object().user

class ReservationCompleteView(CreateView):
    template_name = "reservations/reservation_complete.html"
    success_url = "/reservation_complete/"
    form_class = ReservationForm
    model = Reservations

class ReservationAccountView(ListView):
    template_name = "reservations/reservations_account.html"
    model = Reservations

    def get_context_data(self, **kwargs):
        context = {
            'reservations': self.model.objects.filter(user=self.request.user),
        }
        return context

class DeleteReservationView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    """ A view to delete an reservation """
    model = Reservations
    success_url = "/reservations_account/"

    def test_func(self):
        return self.request.user == self.get_object().user

Models.py File:

class Reservations(models.Model):

    """ reservation form categories and attributes """
    user = models.OneToOneField(User, on_delete=models.CASCADE,
unique=True)
    name = models.CharField(max_length=50)
    phone_number = models.CharField(validators=[phoneNumberRegex],
max_length=16, unique=True)
    email = models.EmailField()
    date = models.DateField()
    time = models.CharField(choices=time_options, default="12pm",
max_length=10)
    number_of_party = models.IntegerField(choices=party_size,
default=1)
    reservation_id = models.UUIDField(primary_key=True,
default=uuid.uuid4, editable=False)

Corresponding Html is:

<button href="{% url 'edit_reservation' reservation.id %}" type="button" class="btn btn-dark">Edit
<button href="{% url 'delete_reservation' reservation.id %}" type="button" class="btn btn-dark">Delete

Error Message:

NoReverseMatch: Reverse for 'delete_reservation' with no arguments not found. 1 pattern(s) tried: ['reservations/delete/(?P<pk>[-a-zA-Z0-9_]+)/$']

Really hoping it's something simple.
Any help is appreciated.
If you need to see more code, let me know and i'll update with what's needeed.

Body:
If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.

So you should use pk or reservation_id.

also pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or reservation_id or whatever.

<button href="{% url 'edit_reservation' reservation.reservation_id %}" type="button" class="btn btn-dark">Edit</a>
<button href="{% url 'delete_reservation' reservation.reservation_id %}" type="button" class="btn btn-dark">Delete</a>

or use pk:

<button href="{% url 'edit_reservation' reservation.pk %}" type="button" class="btn btn-dark">Edit</a>
    <button href="{% url 'delete_reservation' reservation.pk %}" type="button" class="btn btn-dark">Delete</a>


问:
Get all pixels within a rectangle using corner x,y coordinates
I have a 500 pixel by 500 pixel image that I am using to pull data from a 250,000 index array where each index represents 1 pixel.

The user is able to draw a rectangle at any orientation, and I am capturing the coordinates for each corner.

I am trying to capture each pixel within the rectangle to reference the data array and extract the related data.

I looked at Bresenham algorithm in Javascript and while I can get all the points between each of the coordinates using this solution, I am unable to loop through these points as the paths do not always contain the same number of pixels.

An example of the values I'm looking for using the following coordinates would be:

```<code>corner1 = [100,100]
corner2 = [100,105]
corner3 = [105,105]
corner4 = [105,100]
</code>```

And the result (sort order is not important):

```<code>pixelsInRectangle = [
  [100,100],[100,101],[100,102],[100,103],[100,104],[100,105],
  [101,100],[101,101],[101,102],[101,103],[101,104],[101,105],
  [102,100],[102,101],[102,102],[102,103],[102,104],[102,105],
  [103,100],[103,101],[103,102],[103,103],[103,104],[103,105],
  [104,100],[104,101],[104,102],[104,103],[104,104],[104,105],
  [105,100],[105,101],[105,102],[105,103],[105,104],[105,105]
]
</code>```

One set of coordinates I'm trying to solve for are:

```<code>corner1 = [183,194]
corner2 = [190,189]
corner3 = [186,184]
corner4 = [179,190]
</code>```

Any recommendations would be greatly appreciated!

答:
If rectangle is not axis aligned:

Sort vertices by Y-coordinate.

Get the lowest one. From two next Y-coordinates choose left and right ones.

Start simple line rasterization scan along left edge and along right edge simultaneously: for current integer Y value calculate corresponding rounded X-coordinate for left edge, for right edge, and output all horizonatal line between (xleft, y)-(xright,y)

For edge between vertices (x0,y0)-(x1,y1) formula is

```<code>x = x0 + (x1-x0)*(y-y0)/(y1-y0)
</code>```

(example for triangle exploiting the same technique)

When some vertex is reached, change equation of corresponding edge, continue.

Using this way, you fill triangle, parallelogramm, another triangle (or just two triangles if two vertices share the same Y)

(You can use Bresenham or DDA, or another line rasterization algorithm if necessary)

Body:
I have a 500 pixel by 500 pixel image that I am using to pull data from a 250,000 index array where each index represents 1 pixel.

The user is able to draw a rectangle at any orientation, and I am capturing the coordinates for each corner.

I am trying to capture each pixel within the rectangle to reference the data array and extract the related data.

I looked at Bresenham algorithm in Javascript and while I can get all the points between each of the coordinates using this solution, I am unable to loop through these points as the paths do not always contain the same number of pixels.

An example of the values I'm looking for using the following coordinates would be:

corner1 = [100,100]
corner2 = [100,105]
corner3 = [105,105]
corner4 = [105,100]

And the result (sort order is not important):

pixelsInRectangle = [
  [100,100],[100,101],[100,102],[100,103],[100,104],[100,105],
  [101,100],[101,101],[101,102],[101,103],[101,104],[101,105],
  [102,100],[102,101],[102,102],[102,103],[102,104],[102,105],
  [103,100],[103,101],[103,102],[103,103],[103,104],[103,105],
  [104,100],[104,101],[104,102],[104,103],[104,104],[104,105],
  [105,100],[105,101],[105,102],[105,103],[105,104],[105,105]
]

One set of coordinates I'm trying to solve for are:

corner1 = [183,194]
corner2 = [190,189]
corner3 = [186,184]
corner4 = [179,190]

Any recommendations would be greatly appreciated!

Body:
If rectangle is not axis aligned:

Sort vertices by Y-coordinate.

Get the lowest one. From two next Y-coordinates choose left and right ones.

Start simple line rasterization scan along left edge and along right edge simultaneously: for current integer Y value calculate corresponding rounded X-coordinate for left edge, for right edge, and output all horizonatal line between (xleft, y)-(xright,y)

For edge between vertices (x0,y0)-(x1,y1) formula is

x = x0 + (x1-x0)*(y-y0)/(y1-y0)

(example for triangle exploiting the same technique)

When some vertex is reached, change equation of corresponding edge, continue.

Using this way, you fill triangle, parallelogramm, another triangle (or just two triangles if two vertices share the same Y)

(You can use Bresenham or DDA, or another line rasterization algorithm if necessary)