问:
Send and Receive JSON with Java
I'm trying to send and receive JSON using java GUI, but, i keep getting some errors (like, 500,405,403) with i use the http://localhost:8080/clienteWebService/test-resbeans.html Them I'm able to use normally, sending and receive JSON with any problems.

For this program that I'm trying to do I also get this error:

```<code>Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://localhost:8080/ClienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1944)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1939)
at java.security.AccessController.doPrivileged(Native Method)
</code>```

I don't know where is the mistake, I tried to make a direct POST request using http://localhost:8080/clienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir

and them I receive the JSON, but, if I get the information with a jTextField doesn't run properly or at all.

This is the code:

```<code>    public static void Inserir () throws Exception {

    ConsumirWs1 http = new ConsumirWs1();
    Gson g = new Gson();
    Cliente u = new Cliente();
    Type ClienteType = new TypeToken<Cliente>() {
    }.getType();

    u.setCad_pes_nome(InterfaceConsu.jTextFieldNOME.getText());
    u.setCad_pes_cpf(InterfaceConsu.jFormattedTextFieldCPF.getText());
    u.setCad_pes_apelido(InterfaceConsu.jTextFieldAPELIDO.getText());
    SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");

                    java.util.Date utilDate = null;
                    try {
                        utilDate = formatter.parse(jFormattedTextFieldDATA.getText());
                    } catch (ParseException ex) {
                        Logger.getLogger(InterfaceConsu.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    u.setCad_pes_data(sqlDate);

    String json = g.toJson(u, ClienteType);
    String url = "http://localhost:8080/clienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir?";

    http.sendPost(url, json, "POST");

}
</code>```

And them the code to send with the Webservice

```<code>private void sendPost(String url, String urlParameters, String method) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod(method);
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    // Send post request
    con.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
        wr.writeBytes(urlParameters);
        wr.flush();
    }

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }

    //print result
    System.out.println(response.toString());

}
</code>```

and if I try GET, I receive this error java.net.ProtocolException: Invalid HTTP method:

答:
The problem was in the String url, here's the code and the format that i needed to make the request in the right link.

```<code>public void Inserir () throws Exception {
    InterfaceConsu2 IFC2 = new InterfaceConsu2();
    ConsumirWS2 http = new ConsumirWS2();
    Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
    Cliente2 u = new Cliente2();
    Type ClienteType = new TypeToken<Cliente2>() {
    }.getType();

    u.setCad_pes_nome(IFC2.jTextFieldNOME.getText());
    u.setCad_pes_cpf(IFC2.jFormattedTextFieldCPF.getText());
    u.setCad_pes_apelido(IFC2.jTextFieldAPELIDO.getText());
    SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");

                    java.util.Date utilDate = null;
                    try {
                        utilDate = formatter.parse(IFC2.jFormattedTextFieldDATA.getText());
                    } catch (ParseException ex) {
                        Logger.getLogger(InterfaceConsu2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    u.setCad_pes_data(sqlDate);

    String json = g.toJson(u, ClienteType);
    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/inserir";
    System.out.println("63 consumir");
    System.out.println(json);

        http.sendPost(url, json, "POST");

}
</code>```

I think there's few minor changes in the code, but this works with zero error

also, with is needed to send a parameter to a the webservice, here's another example that I made by myself figuring out how to do it, any other advice is welcome

```<code>u.setCad_pes_cpf(IFC2.jFormattedTextFieldCPF.getText());
    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/get/" +u.getCad_pes_cpf();
</code>```

In this one, after this i call a GET method

Title: Send and Receive JSON with Java

Body:
I'm trying to send and receive JSON using java GUI, but, i keep getting some errors (like, 500,405,403) with i use the http://localhost:8080/clienteWebService/test-resbeans.html Them I'm able to use normally, sending and receive JSON with any problems.

For this program that I'm trying to do I also get this error:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://localhost:8080/ClienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1944)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1939)
at java.security.AccessController.doPrivileged(Native Method)

I don't know where is the mistake, I tried to make a direct POST request using http://localhost:8080/clienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir

and them I receive the JSON, but, if I get the information with a jTextField doesn't run properly or at all.

This is the code:

    public static void Inserir () throws Exception {

    ConsumirWs1 http = new ConsumirWs1();
    Gson g = new Gson();
    Cliente u = new Cliente();
    Type ClienteType = new TypeToken<Cliente>() {
    }.getType();

    u.setCad_pes_nome(InterfaceConsu.jTextFieldNOME.getText());
    u.setCad_pes_cpf(InterfaceConsu.jFormattedTextFieldCPF.getText());
    u.setCad_pes_apelido(InterfaceConsu.jTextFieldAPELIDO.getText());
    SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");

                    java.util.Date utilDate = null;
                    try {
                        utilDate = formatter.parse(jFormattedTextFieldDATA.getText());
                    } catch (ParseException ex) {
                        Logger.getLogger(InterfaceConsu.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    u.setCad_pes_data(sqlDate);

    String json = g.toJson(u, ClienteType);
    String url = "http://localhost:8080/clienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir?";

    http.sendPost(url, json, "POST");

}

And them the code to send with the Webservice

private void sendPost(String url, String urlParameters, String method) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod(method);
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    // Send post request
    con.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
        wr.writeBytes(urlParameters);
        wr.flush();
    }

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }

    //print result
    System.out.println(response.toString());

}

and if I try GET, I receive this error java.net.ProtocolException: Invalid HTTP method:

Body:
The problem was in the String url, here's the code and the format that i needed to make the request in the right link.

public void Inserir () throws Exception {
    InterfaceConsu2 IFC2 = new InterfaceConsu2();
    ConsumirWS2 http = new ConsumirWS2();
    Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
    Cliente2 u = new Cliente2();
    Type ClienteType = new TypeToken<Cliente2>() {
    }.getType();

    u.setCad_pes_nome(IFC2.jTextFieldNOME.getText());
    u.setCad_pes_cpf(IFC2.jFormattedTextFieldCPF.getText());
    u.setCad_pes_apelido(IFC2.jTextFieldAPELIDO.getText());
    SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");

                    java.util.Date utilDate = null;
                    try {
                        utilDate = formatter.parse(IFC2.jFormattedTextFieldDATA.getText());
                    } catch (ParseException ex) {
                        Logger.getLogger(InterfaceConsu2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    u.setCad_pes_data(sqlDate);

    String json = g.toJson(u, ClienteType);
    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/inserir";
    System.out.println("63 consumir");
    System.out.println(json);

        http.sendPost(url, json, "POST");

}

I think there's few minor changes in the code, but this works with zero error

also, with is needed to send a parameter to a the webservice, here's another example that I made by myself figuring out how to do it, any other advice is welcome

u.setCad_pes_cpf(IFC2.jFormattedTextFieldCPF.getText());
    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/get/" +u.getCad_pes_cpf();

In this one, after this i call a GET method


来源: stackexchange

问:
Adding Google reCAPTCHA to Chrome Extension
I am trying to integrate Google reCAPTCHA in my Chrome Extension.
I see the reCAPTCHA displayed in the Chrome Extension.
But, it has the following written on it : "ERROR for site owner: Invalid domain for site key" .

I understand that I should write the domain of my chrome extension in my captcha domains list. But how should I go about doing it ? Or am I thinking it the wrong way.

EDIT
I have a simple form as below:

<form action="">

        <button id="submitBtn" disabled>Submit</button>
    </form>```

The error captcha image is in the link

答: You need just add your domain on google recaptcha admin console settings</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to integrate Google reCAPTCHA in my Chrome Extension.
I see the reCAPTCHA displayed in the Chrome Extension.
But, it has the following written on it : "ERROR for site owner: Invalid domain for site key" .

I understand that I should write the domain of my chrome extension in my captcha domains list. But how should I go about doing it ? Or am I thinking it the wrong way.

EDIT
I have a simple form as below:

<form action="">

        <button id="submitBtn" disabled>Submit</button>
    </form>

The error captcha image is in the link

ContentLicense: CC BY-SA 4.0


问:
how to check if a php file is obfuscated?
is there any way we can check if a php file has been obfuscated, using php? I was thinking regex maybe (for instance ioncube's encoded file contains a very long alphabet string, etc.</p>

答: One idea is to check for whitespace. The first thing that an obfuscator will do is to remove extra whitespace. Another thing you can look for is the number of characters per line, as obfuscators will put all the code into few (one?) lines.</p>


问:
receiver function returns memory address instead on int
I wrote a receiver function that should return an integer which is the number of an address of a house (a struct that defined). Please see my code below.

When I call the getnumber receiver function, I get what looks like a memory address (0x47dfc0). I should get 200. I cannot figure out why.

If simply do: fmt.Println(foo_house) I get what I expect: {200 Barrington}

```<code>package main

import "fmt"

type house struct {
    number int
    street string
}

// receiver function
func (h house) get_number() int {
    return h.number
}

func main() {
    var foo_house house
    foo_house.number = 200
    foo_house.street = "Barrington"
    n := foo_house.get_number
    fmt.Println(foo_house)
    fmt.Println(n)
}
</code>```

答:
What you are getting is the address of the method get_number:

You need to evaluate get_number to get its value, like:

n := foo_house.get_number()

Body:
I wrote a receiver function that should return an integer which is the number of an address of a house (a struct that defined). Please see my code below.

When I call the getnumber receiver function, I get what looks like a memory address (0x47dfc0). I should get 200. I cannot figure out why.

If simply do: fmt.Println(foo_house) I get what I expect: {200 Barrington}

package main

import "fmt"

type house struct {
    number int
    street string
}

// receiver function
func (h house) get_number() int {
    return h.number
}

func main() {
    var foo_house house
    foo_house.number = 200
    foo_house.street = "Barrington"
    n := foo_house.get_number
    fmt.Println(foo_house)
    fmt.Println(n)
}


问:
qliksense rest api connection to get data out of qliksense
I want to get list of documents available in  Qlik sense using rest api. I am trying to use the api url https://url/api/v1/apps/docs to get the list of documents

But this is not working. Is the url correct in getting the documents in qliksense?

Where can I find the details on the url for getting the docs? I have checked the Qlik website for rest documentation but could not get the details what I am looking for.

Thanks

答:
Not sure what your use case is but will recommend using Qlik Repository Service API to get list of the apps. The url in your question looks like an Engine REST API endpoints but its non-existing in the endpoints list.

Repositository API is a wrapper around the internal PostgreSQL database, which contains all the metadata (list of apps, streams, extensions etc).

List with all Repository API methods can be found at Qlik QRS API reference page.

The Repository API supports few authentication methods

certificates (when using in server-to-server communication. aka backend)

JWT

Header

Session cookie (from the browser)

Have a look at the examples how to test the responses with Postman (few other examples are available there - Powershell, Node.JS, cURL etc.)


问:
onehot encoder in keras
I would like to index the maximum value (onehot encoder) of an instance of inputs in the keras model. I know how to preprocess it but I would like to execute it in the model.

```<code>inputs = [[ 1,2,3,5],
          [ 2,4,6,3],
          [ 0,7,1,2]]
argmax =[3,2,1]
onehot = [[0,0,0,1],
          [0,0,1,0],
          [0,1,0,0]]
concated= [[ 1,2,3,5, 0,0,0,1],
           [ 2,4,6,3, 0,0,1,0],
           [ 0,7,1,2, 0,1,0,0]]

inputs = Input()
argmax = K.argmax(inputs, axis=-1)
onehot = #How to perform this operation with keras ??#
concated = Concat([inputs,onehot], axis=-1)
</code>```

EDITED
Would it be possible something like that code in python?

```<code>argmax = [3,2,1]
eye = np.eye(4)
eye[argmax]
Out[6]:
array([[0., 0., 0., 1.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.]])
</code>```

答:
You could try something like this:

import tensorflow as tf

x = tf.constant([[
                 [ 1,2,3,5],
                 [ 2,4,6,3],
                 [ 0,7,1,2]],
                 [
                 [ 9,2,3,5],
                 [ 2,2,2,3],
                 [ 0,1,5,2]]
                 ])

inputs = tf.keras.layers.Input((3, 4))
argmax = tf.argmax(inputs, axis=-1)
ij = tf.stack(tf.meshgrid(
    tf.range(tf.shape(inputs)[0], dtype=tf.int64),
    tf.range(tf.shape(inputs)[1], dtype=tf.int64),
                              indexing='ij'), axis=-1)
gather_indices = tf.concat([ij, tf.expand_dims(argmax, axis=-1)], axis=-1)

onehot = tf.tensor_scatter_nd_update(tf.zeros_like(x, dtype=tf.float32), gather_indices, tf.ones_like(argmax, dtype=tf.float32))

outputs = tf.keras.layers.Concatenate()([inputs,onehot])
model = tf.keras.Model(inputs, outputs)
print(model(x))
```
```tf.Tensor(
[[[1. 2. 3. 5. 0. 0. 0. 1.]
  [2. 4. 6. 3. 0. 0. 1. 0.]
  [0. 7. 1. 2. 0. 1. 0. 0.]]

 [[9. 2. 3. 5. 1. 0. 0. 0.]
  [2. 2. 2. 3. 0. 0. 0. 1.]
  [0. 1. 5. 2. 0. 0. 1. 0.]]], shape=(2, 3, 8), dtype=float32)
```
<p>An explanation to what <code>tf.meshgrid</code> is and why it is needed can be found here. You can consider wrapping these operations in a custom <code>Keras</code> layer.</p>
<p>If you would use <code>tf.reduce_max</code> instead of <code>tf.argmax</code>, it would be way simpler:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf

x = tf.constant([[
                 [ 1,2,3,5],
                 [ 2,4,6,3],
                 [ 0,7,1,2]],
                 [
                 [ 9,2,3,5],
                 [ 2,2,2,3],
                 [ 0,1,5,2]]
                 ])

inputs = tf.keras.layers.Input((3, 4))
onehot = tf.where(tf.not_equal(inputs, tf.reduce_max(inputs, keepdims=True, axis=-1)), tf.zeros_like(inputs), tf.ones_like(inputs))

outputs = tf.keras.layers.Concatenate()([inputs,onehot])
model = tf.keras.Model(inputs, outputs)
print(model(x))
</code>```
```<code>tf.Tensor(
[[[1. 2. 3. 5. 0. 0. 0. 1.]
  [2. 4. 6. 3. 0. 0. 1. 0.]
  [0. 7. 1. 2. 0. 1. 0. 0.]]

 [[9. 2. 3. 5. 1. 0. 0. 0.]
  [2. 2. 2. 3. 0. 0. 0. 1.]
  [0. 1. 5. 2. 0. 0. 1. 0.]]], shape=(2, 3, 8), dtype=float32)
</code>```

But I guess there is a reason you want to use argmax.

Title: onehot encoder in keras

Body:
I would like to index the maximum value (onehot encoder) of an instance of inputs in the keras model. I know how to preprocess it but I would like to execute it in the model.

inputs = [[ 1,2,3,5],
          [ 2,4,6,3],
          [ 0,7,1,2]]
argmax =[3,2,1]
onehot = [[0,0,0,1],
          [0,0,1,0],
          [0,1,0,0]]
concated= [[ 1,2,3,5, 0,0,0,1],
           [ 2,4,6,3, 0,0,1,0],
           [ 0,7,1,2, 0,1,0,0]]

inputs = Input()
argmax = K.argmax(inputs, axis=-1)
onehot = #How to perform this operation with keras ??#
concated = Concat([inputs,onehot], axis=-1)

EDITED
Would it be possible something like that code in python?

argmax = [3,2,1]
eye = np.eye(4)
eye[argmax]
Out[6]:
array([[0., 0., 0., 1.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.]])

Body:
You could try something like this:

import tensorflow as tf

x = tf.constant([[
                 [ 1,2,3,5],
                 [ 2,4,6,3],
                 [ 0,7,1,2]],
                 [
                 [ 9,2,3,5],
                 [ 2,2,2,3],
                 [ 0,1,5,2]]
                 ])

inputs = tf.keras.layers.Input((3, 4))
argmax = tf.argmax(inputs, axis=-1)
ij = tf.stack(tf.meshgrid(
    tf.range(tf.shape(inputs)[0], dtype=tf.int64),
    tf.range(tf.shape(inputs)[1], dtype=tf.int64),
                              indexing='ij'), axis=-1)
gather_indices = tf.concat([ij, tf.expand_dims(argmax, axis=-1)], axis=-1)

onehot = tf.tensor_scatter_nd_update(tf.zeros_like(x, dtype=tf.float32), gather_indices, tf.ones_like(argmax, dtype=tf.float32))

outputs = tf.keras.layers.Concatenate()([inputs,onehot])
model = tf.keras.Model(inputs, outputs)
print(model(x))

tf.Tensor(
[[[1. 2. 3. 5. 0. 0. 0. 1.]
  [2. 4. 6. 3. 0. 0. 1. 0.]
  [0. 7. 1. 2. 0. 1. 0. 0.]]

 [[9. 2. 3. 5. 1. 0. 0. 0.]
  [2. 2. 2. 3. 0. 0. 0. 1.]
  [0. 1. 5. 2. 0. 0. 1. 0.]]], shape=(2, 3, 8), dtype=float32)

An explanation to what tf.meshgrid is and why it is needed can be found here. You can consider wrapping these operations in a custom Keras layer.

If you would use tf.reduce_max instead of tf.argmax, it would be way simpler:

import tensorflow as tf

x = tf.constant([[
                 [ 1,2,3,5],
                 [ 2,4,6,3],
                 [ 0,7,1,2]],
                 [
                 [ 9,2,3,5],
                 [ 2,2,2,3],
                 [ 0,1,5,2]]
                 ])

inputs = tf.keras.layers.Input((3, 4))
onehot = tf.where(tf.not_equal(inputs, tf.reduce_max(inputs, keepdims=True, axis=-1)), tf.zeros_like(inputs), tf.ones_like(inputs))

outputs = tf.keras.layers.Concatenate()([inputs,onehot])
model = tf.keras.Model(inputs, outputs)
print(model(x))

tf.Tensor(
[[[1. 2. 3. 5. 0. 0. 0. 1.]
  [2. 4. 6. 3. 0. 0. 1. 0.]
  [0. 7. 1. 2. 0. 1. 0. 0.]]

 [[9. 2. 3. 5. 1. 0. 0. 0.]
  [2. 2. 2. 3. 0. 0. 0. 1.]
  [0. 1. 5. 2. 0. 0. 1. 0.]]], shape=(2, 3, 8), dtype=float32)

But I guess there is a reason you want to use argmax.


问:
Visual studio 2019 "Error encountered while pushing to the remote repository: Failed to push to the remote repository..."
In Visual Studio 2019 I have "Unpushed Commits" as seen below:

When I try to push them I get the error and this is what it looks like on the GUI:

note: the yellow label with "Failed to push..." is not clickable.

The Output from Source Control - Git is as follows:

The output window doesn't show me any useful details. Am I looking in the wrong place? Is there a better place to see the actual error?

The answer in this case is that the policy on the branch 'develop' does not allow direct pushes.  I was kinda hoping that the error in the output would state something like 'Failed to push due to a policy constraint on the branch'

答:
This happened to me & it wasn't creating a remote branch in my repo.

I was able to get around this in visual studio by going to Git->Manage Branches->highlight my branch & right click, "Unset upstream branch".


问:
Django retrieve filter value in views.py
I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function).

Example:

models.py

class User(models.Model):
    name = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

    def __str__(self):
        return self.name

```
<p><code>views.py</code></p>
<pre class="lang-py prettyprint-override"><code>
def users(request):
    users= User.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)
</code>```

users.html

{% block content %}

                Name
                E mail
                Address

        {% for i in users%}

                {{i.name}}
                {{i.email}}
                {{i.address}}

        {% endfor %}

{% endblock content%}
```

I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table.

Any idea on how to proceed ?

答:
If I understood correctly, you could make a form like this

```<code><form method="post">
    <label for="users">Choose a user:</label>
    <select name="users" id="users">
        {% for user in users %}
            <option value="{{ user.name }}">{{ user.name }}</option>
        {% endfor %}
    </select>
    <button id="submit" type="submit">Submit</button>

</form>
</code>```

and then when submitted, get the value of selected option using like this

```<code>selected_user = request.POST.get('users')
</code>```

or something along these lines

Body:
I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function).

Example:

models.py

class User(models.Model):
    name = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

    def __str__(self):
        return self.name

views.py

def users(request):
    users= User.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)

users.html

{% block content %}

                Name
                E mail
                Address

        {% for i in users%}

                {{i.name}}
                {{i.email}}
                {{i.address}}

        {% endfor %}

{% endblock content%}

I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table.

Any idea on how to proceed ?

Body:
If I understood correctly, you could make a form like this

<form method="post">
    <label for="users">Choose a user:</label>
    <select name="users" id="users">
        {% for user in users %}
            <option value="{{ user.name }}">{{ user.name }}</option>
        {% endfor %}
    </select>
    <button id="submit" type="submit">Submit</button>

</form>

and then when submitted, get the value of selected option using like this

selected_user = request.POST.get('users')

or something along these lines


问:
Why does my PHP class seem to be looping if I declare a property as an array outside of the method?
I have a class that essentially runs through a matching pair of arrays to do some error correction:

```<code>class PumpErrors {
    public $error = array();
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $i = 0;
        foreach($this->pumpdat as $val){
          if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);
</code>```

I'm feeding the class the array from the form (POST) (its a matched pair of an amount and ID of a pump.  The number of pumps varies depending on who is using the form.)
I then call the errors on the main page to show the errors:

```<code><?php
if(isset($errors)){
?>
    <div class='form-row justify-content-center'><p class='text-danger'>
<?php
    foreach($errors->firstOfAll() as $userErrors) {
        echo $userErrors . '<br />';

?>
        </p>
    </div>
<?php
    }
?>
</code>```

This results in the errors being displayed TWICE.

```<code>Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.
Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.
</code>```

HOWEVER

If I run the class like this:

```<code>class PumpErrors {
    public $error;
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $this->error = array();
        $i = 0;
        foreach($this->pumpdat as $val){

            if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);
</code>```

and display the errors, it only shows up once, as intended.

I'm just looking for an explanation as to WHY this would be happening.

If I declare the property as an array at the beginning, I get doubles on the output.

If I set the property initially as nothing and then set property as an array inside the method, all is good.

I initially thought that perhaps declaring it as an array at the beginning was causing it to be a multidimensional array and somehow the loop through to display it was just going through it twice. But the kint dump didn't look as if that was happening.  If there is more than one error say pump 1 and pump 2, then i get doubles like this:

```<code>Pump 1 (error message)
Pump 2 (error message)

Pump 1 (error message)
Pump 2 (error message)
</code>```

(note:, im doing this as a class out of laziness so i can use the same error display code as rakit validator for the rest of the form, I know there are easier way to run thru the array to check it.  This was more of an exercise to see IF it could be done this way and I stumbled on this weird behavior.)

EDIT: perhaps a version issue? im running it on 7.4.24 locally.

答: If you define the variable as a "Static public $error", this should eliminate this variable from be instantiated each time a new object of the class is created.</p>

Body:
I have a class that essentially runs through a matching pair of arrays to do some error correction:

class PumpErrors {
    public $error = array();
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $i = 0;
        foreach($this->pumpdat as $val){
          if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);

I'm feeding the class the array from the form (POST) (its a matched pair of an amount and ID of a pump.  The number of pumps varies depending on who is using the form.)
I then call the errors on the main page to show the errors:

<?php
if(isset($errors)){
?>

<?php
    foreach($errors->firstOfAll() as $userErrors) {
        echo $userErrors . '
';

?>

<?php
    }
?>

This results in the errors being displayed TWICE.

Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.
Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.

HOWEVER

If I run the class like this:

class PumpErrors {
    public $error;
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $this->error = array();
        $i = 0;
        foreach($this->pumpdat as $val){

            if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);

and display the errors, it only shows up once, as intended.

I'm just looking for an explanation as to WHY this would be happening.

If I declare the property as an array at the beginning, I get doubles on the output.

If I set the property initially as nothing and then set property as an array inside the method, all is good.

I initially thought that perhaps declaring it as an array at the beginning was causing it to be a multidimensional array and somehow the loop through to display it was just going through it twice. But the kint dump didn't look as if that was happening.  If there is more than one error say pump 1 and pump 2, then i get doubles like this:

Pump 1 (error message)
Pump 2 (error message)

Pump 1 (error message)
Pump 2 (error message)

(note:, im doing this as a class out of laziness so i can use the same error display code as rakit validator for the rest of the form, I know there are easier way to run thru the array to check it.  This was more of an exercise to see IF it could be done this way and I stumbled on this weird behavior.)

EDIT: perhaps a version issue? im running it on 7.4.24 locally.


问:
Is there a way I can pass the context using return redirect in Django?
I wanted to pass the context using return redirect since using return render will send the post again when refreshing the page.

This is my code for my return render:

```<code>context = {
        'file_path': file_path+'reviews_processed.csv',
        'file_name': 'reviews_processed.csv',
    }
    messages.add_message(request, messages.SUCCESS, 'Processing done!')
    return render(request, 'vlookup/vlookup.html', context)

</code>```

and this is what I am trying to achieve:

```<code># return redirect(vlookup, context)
</code>```

Thanks!

答:
You can use django messages or session for showing your custom context or message after successfully redirect. somethings will be like that

```<code>messages.add_message(request, messages.SUCCESS, 'Processing done!')
return redirect('your redirect page url')
</code>```

Body:
I wanted to pass the context using return redirect since using return render will send the post again when refreshing the page.

This is my code for my return render:

context = {
        'file_path': file_path+'reviews_processed.csv',
        'file_name': 'reviews_processed.csv',
    }
    messages.add_message(request, messages.SUCCESS, 'Processing done!')
    return render(request, 'vlookup/vlookup.html', context)

and this is what I am trying to achieve:

# return redirect(vlookup, context)

Thanks!

Body:
You can use django messages or session for showing your custom context or message after successfully redirect. somethings will be like that

messages.add_message(request, messages.SUCCESS, 'Processing done!')
return redirect('your redirect page url')


问:
Selenium: Trying to login but the same page is reloaded after click
I am trying to login a page.

I entered the e-mail & password inputs by element.sendKeys() without any error.

After that I need to click the 'loginButton' button. But the button is defined as non keyboard-focusable.

When I run the automation, the button is clicked. But the automation is not continue with the next page (main page); just reloads the same page with empty inputs.

I tried several ways to click the button and also tried to enter by using 'ENTER' key;

```<code>// **1.**
 loginButton.click();

// **2.**
 robot.keyPress(KeyEvent.VK_ENTER);

// **3.**
 Actions act = new Actions(dDriver);
 act.moveToElement(driver.findElement(By.id("loginButton"))).click().build().perform();

// **4.**
 JavascriptExecutor executor;
</code>```

All of them seems that I can click the button but after that as I mentioned, the page is reloaded, not continue with the next page.

What else can I try?

答:
A problem I can think about is that you are typing the information too fast and hit the login button right away.

Try to wait before clicking the Login button 0.3 seconds:

```<code>Thread.Sleep(300);
</code>```

Or even a full second:

```<code>Thread.sleep(1000);
</code>```

Tell me if this solves your issue.

Also, the site might be disabled for automation code so add these to your ChromeOptions:

```<code>ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
WebDriver driver = new ChromeDriver(options);
</code>```

Or

```<code>options.addArguments("disable-infobars");
</code>```

Body:
I am trying to login a page.

I entered the e-mail & password inputs by element.sendKeys() without any error.

After that I need to click the 'loginButton' button. But the button is defined as non keyboard-focusable.

When I run the automation, the button is clicked. But the automation is not continue with the next page (main page); just reloads the same page with empty inputs.

I tried several ways to click the button and also tried to enter by using 'ENTER' key;

// **1.**
 loginButton.click();

// **2.**
 robot.keyPress(KeyEvent.VK_ENTER);

// **3.**
 Actions act = new Actions(dDriver);
 act.moveToElement(driver.findElement(By.id("loginButton"))).click().build().perform();

// **4.**
 JavascriptExecutor executor;

All of them seems that I can click the button but after that as I mentioned, the page is reloaded, not continue with the next page.

What else can I try?

Body:
A problem I can think about is that you are typing the information too fast and hit the login button right away.

Try to wait before clicking the Login button 0.3 seconds:

Thread.Sleep(300);

Or even a full second:

Thread.sleep(1000);

Tell me if this solves your issue.

Also, the site might be disabled for automation code so add these to your ChromeOptions:

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
WebDriver driver = new ChromeDriver(options);

Or

options.addArguments("disable-infobars");


问:
.split() returns list of individual charachters instead of splitting it as the spaces
```<code>n = input("input n: ")
n.split()
print(n, len(n))
</code>```

Say the input is: 100 400, seperated by a space, .split() returns a list of all the individual digits, as well as the space between them, instead of the two numbers such that len(n) = 7, and n[0] = 1 instead of 100.

答:
You're printing the original output of n and not a list of your original variable split. You need to access your list variable after you've split it:

```<code>    n = input("input n: ")
    after = n.split()

    print(after, len(after))
</code>```

Yields:

['100', '400'] 2

If you wanted to access individual indexes, you could iterate through the list after and access each index, like so:

```<code>    n = input("input n: ")
    after = n.split()
        for x in range(0, len(after)):
        print(after[x])

</code>```

Which yields:

```<code>100
400
</code>```

Body:
n = input("input n: ")
n.split()
print(n, len(n))

Say the input is: 100 400, seperated by a space, .split() returns a list of all the individual digits, as well as the space between them, instead of the two numbers such that len(n) = 7, and n[0] = 1 instead of 100.

Body:
You're printing the original output of n and not a list of your original variable split. You need to access your list variable after you've split it:

    n = input("input n: ")
    after = n.split()

    print(after, len(after))

Yields:

['100', '400'] 2

If you wanted to access individual indexes, you could iterate through the list after and access each index, like so:

    n = input("input n: ")
    after = n.split()
        for x in range(0, len(after)):
        print(after[x])

Which yields:

100
400


问:
get previous and next id using mysql
I am trying to create a function in PHP that returns "next_id" and "prev_id", from an sql table.

However, the id is not simply 1,2,3,etc which means if one record id is 50, the previous id might be 22 while the next id might be 81.

I tried, in this way...

```<code>public function prevNext($id)
    {
        "SELECT
            IFNULL(SELECT min(id)
                from table
                where id > t.id ) as next_id
            , IFNULL(SELECT max(id)
                from table
                where id < t.id) as prev_id
        from table as t
        where id = $id";
    }
</code>```

答:
Hi to select the next id you just need to take the minimal id among those who are greater than the current and vice-versa for the previous. Here are the sql requests :

For the next_id : SELECT MIN(id) FROM table WHERE id>current_id

For the previous : SELECT MAX(id) FROM table WHERE id<current_id

Title: get previous and next id using mysql

Body:
I am trying to create a function in PHP that returns "next_id" and "prev_id", from an sql table.

However, the id is not simply 1,2,3,etc which means if one record id is 50, the previous id might be 22 while the next id might be 81.

I tried, in this way...

public function prevNext($id)
    {
        "SELECT
            IFNULL(SELECT min(id)
                from table
                where id > t.id ) as next_id
            , IFNULL(SELECT max(id)
                from table
                where id < t.id) as prev_id
        from table as t
        where id = $id";
    }


问:
Temporary tables in stored procedure for Oracle
I have a stored procedure that runs fine on MS SQL and DB2. But cannot get it to run on Oracle as it uses temporary tables created within the procedure. I would like to know any suggestions on my stored procedure if possible. Please do not suggest execute immediate as i do not have the permission for that. This is a huge procedure so please guide me how i can do this without a temporary table. Please note that creating a temporary table before creating the procedure is also not an option.

Thanks in advance!

```<code>`CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)
is
BEGIN

CREATE TABLE LEADS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE ASSIGNMENTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE MAPRESULTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE COMMAND_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE PROGRESS_STATUS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE DETAILS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE NEEDS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);
if oprtr = 0 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed;

elsif oprtr = 1 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                            AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                            AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed);

elsif oprtr = 2 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed;
end if;

INSERT INTO LEADS_DELETED
SELECT DISTINCT LEADSEQ FROM ASSIGNMENT WHERE SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

if oprtr = 0 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed);

elsif oprtr = 1 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                                         AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                                         AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed));

elsif oprtr = 2 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed);
end if;

SET leadscount = (SELECT COUNT(*) FROM LEADS_DELETED);

INSERT INTO MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

INSERT INTO COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM MAPRESULTS_DELETED);

INSERT INTO PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

INSERT INTO DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

INSERT INTO NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM PROGRESS_STATUS_DELETED);

DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED));

DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
    (SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED));

DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE SALE_DELETED_EX
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

INSERT into SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALEEXTENSIONS WHERE
    SEQID IN (SELECT ID FROM SALE_DELETED_EX);

DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM NEEDS_DELETED UNION SELECT ID FROM DETAILS_DELETED);

DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE LEADS_DELETED_E
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

InSERT into LEADS_DELETED_E Select SEQID FROM LEADEXTENSIONS WHERE
    SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD);

DELETE FROM LEADEXTENSIONS WHERE
    SEQID  IN (SELECT ID FROM LEADS_DELETED_E);

DROP TABLE LEADS_DELETED;

DROP TABLE ASSIGNMENTS_DELETED;

DROP TABLE MAPRESULTS_DELETED;

DROP TABLE COMMAND_DELETED;

DROP TABLE PROGRESS_STATUS_DELETED;

DROP TABLE DETAILS_DELETED;

DROP TABLE NEEDS_DELETED;

DROP TABLE LEADS_DELETED_E;

DROP TABLE SALE_DELETED_EX;

COMMIT;
END LEAD_PURGE;
</code>```

`

答:
You can try, as Ollie says, with Collections. I take only your LEADS_DELETED table.

```<code>CREATE OR REPLACE TYPE Collection_LEADS_DELETED;
CREATE OR REPLACE TYPE TypeObject_LEADS_DELETED
AS OBJECT (ID NUMBER(19));

FUNCTION your_function
   RETURN Collection_LEADS_DELETED PIPELINED
IS
     type t_array is table of number
          index by binary_integer;
     v_data   t_array;
     v_cont   integer;

     CURSOR cur_your_cursor
        IS
            SELECT DISTINCT LEADSEQ
              FROM ASSIGNMENT
             WHERE SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);
        BEGIN
            v_cont := 0;
            FOR i in cur_your_cursor
            LOOP
                    v_cont := v_cont + 1;
                    v_data (v_cont) := i.LEADSEQ;
            END LOOP;
            For x in 1 .. v_data.count
            loop
                pipe row (TypeObject_LEADS_DELETED(v_data(x)));
            end loop;
            RETURN;
        END your_function;
</code>```

Then, you can call this function anywhere, for example:

```<code>select * from table(your_function);
</code>```

If you can't create Object Types (you have no grants, for example), as your temporary tables seems only an array of integers, you could use only the first part, avoiding returning anything or pipelining or creating types outside your procedure. In v_data variable you had all your desired ID's. You can use it, for example, something like this:

```<code>    For x in 1 .. v_data.count
        LOOP
          insert into ASSIGNMENTS_DELETED
             select SEQID FROM ASSIGNMENT
             WHERE LEADSEQ IN (v_data(x))
             AND  SEQID NOT IN
                   (SELECT SEQID FROM ASSIGNMENT
                    WHERE ROLE = 6 AND STATUS = 8
                   AND CLOSINGTIME < closed);
       END LOOP;
</code>```

Body:
I have a stored procedure that runs fine on MS SQL and DB2. But cannot get it to run on Oracle as it uses temporary tables created within the procedure. I would like to know any suggestions on my stored procedure if possible. Please do not suggest execute immediate as i do not have the permission for that. This is a huge procedure so please guide me how i can do this without a temporary table. Please note that creating a temporary table before creating the procedure is also not an option.

Thanks in advance!

`CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)
is
BEGIN

CREATE TABLE LEADS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE ASSIGNMENTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE MAPRESULTS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE COMMAND_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE PROGRESS_STATUS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE DETAILS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

CREATE TABLE NEEDS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);
if oprtr = 0 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed;

elsif oprtr = 1 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                            AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                            AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed);

elsif oprtr = 2 then
INSERT INTO ASSIGNMENTS_DELETED
SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed;
end if;

INSERT INTO LEADS_DELETED
SELECT DISTINCT LEADSEQ FROM ASSIGNMENT WHERE SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

if oprtr = 0 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME < closed);

elsif oprtr = 1 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND EXTRACT(YEAR FROM CLOSINGTIME) = EXTRACT(YEAR FROM closed)
                                                                         AND EXTRACT(MONTH FROM CLOSINGTIME) = EXTRACT(MONTH FROM closed)
                                                                         AND EXTRACT(DAY FROM CLOSINGTIME) = EXTRACT(DAY FROM closed));

elsif oprtr = 2 then
insert into ASSIGNMENTS_DELETED
select SEQID FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED) AND
SEQID NOT IN (SELECT SEQID FROM ASSIGNMENT WHERE ROLE = 6 AND STATUS = 8 AND CLOSINGTIME > closed);
end if;

SET leadscount = (SELECT COUNT(*) FROM LEADS_DELETED);

INSERT INTO MAPRESULTS_DELETED
SELECT ID FROM MAPRESULT WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

INSERT INTO COMMAND_DELETED
SELECT ID FROM EXECUTERULECOMMAND WHERE MAPRESULTID IN (SELECT ID FROM MAPRESULTS_DELETED);

INSERT INTO PROGRESS_STATUS_DELETED
SELECT PROGRESS_STATUS_ID FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

INSERT INTO DETAILS_DELETED
SELECT DETAILID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

INSERT INTO NEEDS_DELETED
SELECT NEEDSID FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM PROGRESS_STATUS WHERE ID IN (SELECT ID FROM PROGRESS_STATUS_DELETED);

DELETE FROM EXECUTERULECOMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM COMMAND WHERE ID IN (SELECT ID FROM COMMAND_DELETED);

DELETE FROM SIMPLECONDITIONAL WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPPREDICATE WHERE ROWBP IN (SELECT ID FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED));

DELETE FROM MAPROW WHERE RESULT IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM MAPRESULT WHERE ID IN (SELECT ID FROM MAPRESULTS_DELETED);

DELETE FROM ASSIGNMENTATTACHMENTS WHERE ASSIGNMENTSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM LEADOBSERVER WHERE ASSIGNSEQ IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM MAPDESTINATIONS WHERE SUGGESTEDASSIGNID IN
    (SELECT ID FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED));

DELETE FROM SUGGESTEDASSIGNMENT WHERE ASSIGNMENT_SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);

DELETE FROM PRODUCTINTEREST WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE SALE_DELETED_EX
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

INSERT into SALE_DELETED_EX SELECT SALEEXSEQ FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALE WHERE SEQID IN (SELECT SALEID FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED));

DELETE FROM SALEEXTENSIONS WHERE
    SEQID IN (SELECT ID FROM SALE_DELETED_EX);

DELETE FROM LEADSALES WHERE LEADID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM NOTES WHERE OBJECTID IN (SELECT ID FROM NEEDS_DELETED) OR OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM HISTORYRECORD WHERE OBJECTID IN (SELECT ID FROM DETAILS_DELETED);

DELETE FROM DETAIL WHERE SEQID IN (SELECT ID FROM NEEDS_DELETED UNION SELECT ID FROM DETAILS_DELETED);

DELETE FROM MESSAGES WHERE PROVIDERID IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM ASSIGNMENT WHERE LEADSEQ IN (SELECT ID FROM LEADS_DELETED);

DELETE FROM LEAD WHERE SEQID IN (SELECT ID FROM LEADS_DELETED);

CREATE TABLE LEADS_DELETED_E
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
);

InSERT into LEADS_DELETED_E Select SEQID FROM LEADEXTENSIONS WHERE
    SEQID NOT IN (SELECT LEADEXSEQ FROM LEAD);

DELETE FROM LEADEXTENSIONS WHERE
    SEQID  IN (SELECT ID FROM LEADS_DELETED_E);

DROP TABLE LEADS_DELETED;

DROP TABLE ASSIGNMENTS_DELETED;

DROP TABLE MAPRESULTS_DELETED;

DROP TABLE COMMAND_DELETED;

DROP TABLE PROGRESS_STATUS_DELETED;

DROP TABLE DETAILS_DELETED;

DROP TABLE NEEDS_DELETED;

DROP TABLE LEADS_DELETED_E;

DROP TABLE SALE_DELETED_EX;

COMMIT;
END LEAD_PURGE;

`

Body:
You can try, as Ollie says, with Collections. I take only your LEADS_DELETED table.

CREATE OR REPLACE TYPE Collection_LEADS_DELETED;
CREATE OR REPLACE TYPE TypeObject_LEADS_DELETED
AS OBJECT (ID NUMBER(19));

FUNCTION your_function
   RETURN Collection_LEADS_DELETED PIPELINED
IS
     type t_array is table of number
          index by binary_integer;
     v_data   t_array;
     v_cont   integer;

     CURSOR cur_your_cursor
        IS
            SELECT DISTINCT LEADSEQ
              FROM ASSIGNMENT
             WHERE SEQID IN (SELECT ID FROM ASSIGNMENTS_DELETED);
        BEGIN
            v_cont := 0;
            FOR i in cur_your_cursor
            LOOP
                    v_cont := v_cont + 1;
                    v_data (v_cont) := i.LEADSEQ;
            END LOOP;
            For x in 1 .. v_data.count
            loop
                pipe row (TypeObject_LEADS_DELETED(v_data(x)));
            end loop;
            RETURN;
        END your_function;

Then, you can call this function anywhere, for example:

select * from table(your_function);

If you can't create Object Types (you have no grants, for example), as your temporary tables seems only an array of integers, you could use only the first part, avoiding returning anything or pipelining or creating types outside your procedure. In v_data variable you had all your desired ID's. You can use it, for example, something like this:

    For x in 1 .. v_data.count
        LOOP
          insert into ASSIGNMENTS_DELETED
             select SEQID FROM ASSIGNMENT
             WHERE LEADSEQ IN (v_data(x))
             AND  SEQID NOT IN
                   (SELECT SEQID FROM ASSIGNMENT
                    WHERE ROLE = 6 AND STATUS = 8
                   AND CLOSINGTIME < closed);
       END LOOP;


问:
Read all data in a registry key
How do you read all the data in a registry key

    void get_reg_value(HKEY handle ,  std::string value_to_read)
    {

        char value[2048];
        DWORD BufferSize = 8192;

        LONG errorcode = RegGetValueA(handle, NULL, value_to_read.c_str(), RRF_RT_REG_MULTI_SZ, NULL, (PVOID)&value, &BufferSize);
        wprintf(L"Value data: %s\n", (PWSTR)value);

    }
```
<p>The key to read is <code>HARDWARE\\DESCRIPTION\\System</code> and the subkey is <code>SystemBiosVersion</code> which has the value</p>
```ALASKA - 1072009
F6
American Megatrends - 5000C

```
<p>but I only get</p>
```Value data: ALASKA - 1072009
```

答:
First off, you are passing in the wrong BufferSize value to RegGetValueA().  You are claiming that you have allocated 8KB of memory, but you have actually allocated only 2KB.  If the Registry data exceeds 2KB, you will overflow your buffer and corrupt memory.  NEVER lie about your buffer sizes.

Also, you are trying to print out a narrow ANSI string as-if it were a wide Unicode string, which it is not, so that is also wrong.

That being said, a REG_MULTI_SZ value is a null-terminated list of multiple null-terminated strings.  You are printing out only the 1st string in the list.  You need to loop through the whole list until you encounter the final null terminator, eg:

void get_reg_value(HKEY handle, std::string value_to_read)
{
    char Buffer[2048];
    DWORD BufferSize = sizeof(Buffer);

    LONG errorcode = RegGetValueA(handle, NULL, value_to_read.c_str(), RRF_RT_REG_MULTI_SZ, NULL, Buffer, &BufferSize);
    if (errorcode == ERROR_SUCCESS) {
        char *value = Buffer;
        while (*value != '\0') {
            printf("Value data: %s\n", value);
            value += (strlen(value) + 1);
        }
    }
    else {
        printf("Error: %ld\n", errorcode);
    }
}
```
<p>Alternatively, if needed, consider using a dynamically allocated buffer, so can handle data values greater than 2KB:</p>
<pre class="lang-cpp prettyprint-override"><code>void get_reg_value(HKEY handle, std::string value_to_read)
{
    std::vector<char> Buffer(2048);
    DWORD BufferSize = Buffer.size();

    LONG errorcode;
    do {
        errorcode = RegGetValueA(handle, NULL, value_to_read.c_str(), RRF_RT_REG_MULTI_SZ, NULL, Buffer, &BufferSize);
        if (errorcode != ERROR_MORE_DATA) break;
        Buffer.resize(BufferSize);
    }
    while (true);

    if (errorcode == ERROR_SUCCESS) {
        char *value = Buffer.data();
        while (*value != '\0') {
            printf("Value data: %s\n", value);
            value += (strlen(value) + 1);
        }
    }
    else {
        printf("Error: %ld\n", errorcode);
    }
}
</code>```

Title: Read all data in a registry key

Body:
How do you read all the data in a registry key

    void get_reg_value(HKEY handle ,  std::string value_to_read)
    {

        char value[2048];
        DWORD BufferSize = 8192;

        LONG errorcode = RegGetValueA(handle, NULL, value_to_read.c_str(), RRF_RT_REG_MULTI_SZ, NULL, (PVOID)&value, &BufferSize);
        wprintf(L"Value data: %s\n", (PWSTR)value);

    }

The key to read is HARDWARE\\DESCRIPTION\\System and the subkey is SystemBiosVersion which has the value

ALASKA - 1072009
F6
American Megatrends - 5000C

but I only get

Value data: ALASKA - 1072009

Body:
First off, you are passing in the wrong BufferSize value to RegGetValueA().  You are claiming that you have allocated 8KB of memory, but you have actually allocated only 2KB.  If the Registry data exceeds 2KB, you will overflow your buffer and corrupt memory.  NEVER lie about your buffer sizes.

Also, you are trying to print out a narrow ANSI string as-if it were a wide Unicode string, which it is not, so that is also wrong.

That being said, a REG_MULTI_SZ value is a null-terminated list of multiple null-terminated strings.  You are printing out only the 1st string in the list.  You need to loop through the whole list until you encounter the final null terminator, eg:

void get_reg_value(HKEY handle, std::string value_to_read)
{
    char Buffer[2048];
    DWORD BufferSize = sizeof(Buffer);

    LONG errorcode = RegGetValueA(handle, NULL, value_to_read.c_str(), RRF_RT_REG_MULTI_SZ, NULL, Buffer, &BufferSize);
    if (errorcode == ERROR_SUCCESS) {
        char *value = Buffer;
        while (*value != '\0') {
            printf("Value data: %s\n", value);
            value += (strlen(value) + 1);
        }
    }
    else {
        printf("Error: %ld\n", errorcode);
    }
}

Alternatively, if needed, consider using a dynamically allocated buffer, so can handle data values greater than 2KB:

void get_reg_value(HKEY handle, std::string value_to_read)
{
    std::vector<char> Buffer(2048);
    DWORD BufferSize = Buffer.size();

    LONG errorcode;
    do {
        errorcode = RegGetValueA(handle, NULL, value_to_read.c_str(), RRF_RT_REG_MULTI_SZ, NULL, Buffer, &BufferSize);
        if (errorcode != ERROR_MORE_DATA) break;
        Buffer.resize(BufferSize);
    }
    while (true);

    if (errorcode == ERROR_SUCCESS) {
        char *value = Buffer.data();
        while (*value != '\0') {
            printf("Value data: %s\n", value);
            value += (strlen(value) + 1);
        }
    }
    else {
        printf("Error: %ld\n", errorcode);
    }
}


问:
What does this warning mean? It happens every time I restart the node process
The warning:

```<code>(process:3380): GLib-GIO-WARNING **: 12:47:10.778: Unexpectedly, UWP app `HaukeGtze.NotepadEditor_1.795.1.0_x64__6bk20wvc8rfx2' (AUMId `HaukeGtze.NotepadEditor_6bk20wvc8rfx2!notepad') supports 182 extensions but has no verbs
</code>```

I think the part before the word 'Unexpectedly' is the time, but what does the rest mean?

The last thing I was doing before this started was installing canvas with npm install canvas --save.

So is there a way for me to stop this?

I also noticed it says NotepadEditor there but what does that have to do with anything? It doesn't crash the process, and doesn't seem to affect anything, but it's annoying.

EDIT : it was caused by require('canvas') rather than installing it. So how can I require it without getting the warning?

答: I had the same problem when using Python weasyprint package. It was complaining about Windows PDF X app. GLib-GIO-WARNING **: 11:31:57.620: Unexpectedly, UWP app `6760NGPDFLab.PDFX_1.3.13.0_x64__sbe4t8mqwq93a'. I simply uninstalled the app and the problem went away.</p>

Body:
The warning:

(process:3380): GLib-GIO-WARNING **: 12:47:10.778: Unexpectedly, UWP app `HaukeGtze.NotepadEditor_1.795.1.0_x64__6bk20wvc8rfx2' (AUMId `HaukeGtze.NotepadEditor_6bk20wvc8rfx2!notepad') supports 182 extensions but has no verbs

I think the part before the word 'Unexpectedly' is the time, but what does the rest mean?

The last thing I was doing before this started was installing canvas with npm install canvas --save.

So is there a way for me to stop this?

I also noticed it says NotepadEditor there but what does that have to do with anything? It doesn't crash the process, and doesn't seem to affect anything, but it's annoying.

EDIT : it was caused by require('canvas') rather than installing it. So how can I require it without getting the warning?


问:
Looking for help to make npm/pdfjs-dist work with Webpack and Django
I've been trying for a few hours replacing a link-based pdf.js with an npm install of pdfjs-dist, since I noticed that my links were not meant to be used as cdns and could become unstable as described here.

I could not find much documentation on how to make that work other than a few examples, and when Webpack is involved they are mostly with React, while I am simply using ES6 in a Django framework (static compiling on the desired django directory, without using the webpack-plugin.)

After exchanging several messages with one of the guys that work on pdf.js it seemed that my compiling errors were probably due to how Webpack handles internally the library. Here's what I am seeing:

```<code>WARNING in ./node_modules/worker-loader/dist/index.js
Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileAsyncWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist'
 @ ./node_modules/worker-loader/dist/index.js
 @ ./node_modules/worker-loader/dist/cjs.js
 @ ./node_modules/pdfjs-dist/webpack.js
 @ ./src/js/views/pdfViews.js
 @ ./src/js/index.js

WARNING in ./node_modules/worker-loader/dist/index.js
Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist'
 @ ./node_modules/worker-loader/dist/index.js
 @ ./node_modules/worker-loader/dist/cjs.js
 @ ./node_modules/pdfjs-dist/webpack.js
 @ ./src/js/views/pdfViews.js
 @ ./src/js/index.js

ERROR in (webpack)/lib/node/NodeTargetPlugin.js
Module not found: Error: Can't resolve 'module' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/webpack/lib/node'
 @ (webpack)/lib/node/NodeTargetPlugin.js 11:1-18
 @ ./node_modules/worker-loader/dist/index.js
 @ ./node_modules/worker-loader/dist/cjs.js
 @ ./node_modules/pdfjs-dist/webpack.js
 @ ./src/js/views/pdfViews.js
 @ ./src/js/index.js
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/src-select.html] 4.57 KiB {HtmlWebpackPlugin_0} [built]
Child worker-loader node_modules/pdfjs-dist/build/pdf.worker.js:
              Asset      Size      Chunks             Chunk Names
    index.worker.js  1.33 MiB  pdf.worker  [emitted]  pdf.worker
    Entrypoint pdf.worker = index.worker.js
    [./node_modules/pdfjs-dist/build/pdf.worker.js] 1.25 MiB {pdf.worker} [built]
    [./node_modules/process/browser.js] 5.29 KiB {pdf.worker} [built]
ℹ ｢wdm｣: Failed to compile.
</code>```

Theoretically the pdfjs-dist should come with a zero configuration file, without even needing to set up a worker for it, so code like the one below should work:

```<code>import pdfjsLib from 'pdfjs-dist/webpack'

////////////////////////////////////////////
//// instantiate pdf
export const pdfView = () => {
  // pdfjsLib.GlobalWorkerOptions.workerSrc = 'index.worker.js';

  // var defined through a Django template tag
  const loadingTask = pdfjsLib.getDocument(pdfData.myPdfDoc)

  pdfData.myPdf = loadingTask.promise.then(pdf => {
    pdfData.pdfTotalPageN = pdf.numPages;
    return pdf;
  })
}

</code>```

but it doesn't get compiled, and I would really appreciate some pointers.
Thanks in advance

答:
if webpack is failing because of optional chaining consider pointing to the legacy version which omits modern syntax.

import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.js'

instead of

import * as pdfjs from 'pdfjs-dist'

Body:
I've been trying for a few hours replacing a link-based pdf.js with an npm install of pdfjs-dist, since I noticed that my links were not meant to be used as cdns and could become unstable as described here.

I could not find much documentation on how to make that work other than a few examples, and when Webpack is involved they are mostly with React, while I am simply using ES6 in a Django framework (static compiling on the desired django directory, without using the webpack-plugin.)

After exchanging several messages with one of the guys that work on pdf.js it seemed that my compiling errors were probably due to how Webpack handles internally the library. Here's what I am seeing:

WARNING in ./node_modules/worker-loader/dist/index.js
Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileAsyncWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist'
 @ ./node_modules/worker-loader/dist/index.js
 @ ./node_modules/worker-loader/dist/cjs.js
 @ ./node_modules/pdfjs-dist/webpack.js
 @ ./src/js/views/pdfViews.js
 @ ./src/js/index.js

WARNING in ./node_modules/worker-loader/dist/index.js
Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist'
 @ ./node_modules/worker-loader/dist/index.js
 @ ./node_modules/worker-loader/dist/cjs.js
 @ ./node_modules/pdfjs-dist/webpack.js
 @ ./src/js/views/pdfViews.js
 @ ./src/js/index.js

ERROR in (webpack)/lib/node/NodeTargetPlugin.js
Module not found: Error: Can't resolve 'module' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/webpack/lib/node'
 @ (webpack)/lib/node/NodeTargetPlugin.js 11:1-18
 @ ./node_modules/worker-loader/dist/index.js
 @ ./node_modules/worker-loader/dist/cjs.js
 @ ./node_modules/pdfjs-dist/webpack.js
 @ ./src/js/views/pdfViews.js
 @ ./src/js/index.js
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/src-select.html] 4.57 KiB {HtmlWebpackPlugin_0} [built]
Child worker-loader node_modules/pdfjs-dist/build/pdf.worker.js:
              Asset      Size      Chunks             Chunk Names
    index.worker.js  1.33 MiB  pdf.worker  [emitted]  pdf.worker
    Entrypoint pdf.worker = index.worker.js
    [./node_modules/pdfjs-dist/build/pdf.worker.js] 1.25 MiB {pdf.worker} [built]
    [./node_modules/process/browser.js] 5.29 KiB {pdf.worker} [built]
ℹ ｢wdm｣: Failed to compile.

Theoretically the pdfjs-dist should come with a zero configuration file, without even needing to set up a worker for it, so code like the one below should work:

import pdfjsLib from 'pdfjs-dist/webpack'

////////////////////////////////////////////
//// instantiate pdf
export const pdfView = () => {
  // pdfjsLib.GlobalWorkerOptions.workerSrc = 'index.worker.js';

  // var defined through a Django template tag
  const loadingTask = pdfjsLib.getDocument(pdfData.myPdfDoc)

  pdfData.myPdf = loadingTask.promise.then(pdf => {
    pdfData.pdfTotalPageN = pdf.numPages;
    return pdf;
  })
}

but it doesn't get compiled, and I would really appreciate some pointers.
Thanks in advance


问:
remote-exec provisioner in terraform gives timeout
I am trying to spin up an EC2 instance using an ubuntu image. I want to provide ssh access to the instance, install and run the apache server, and open up port 80, all through terraform.

I have the following code for remote-exec for my EC2

```<code>provisioner "remote-exec" {
  inline = [
    "sudo apt update -y",
    "sudo apt upgrade -y",
    "sudo apt install apache2 -y",
    "sudo systemctl status apache2"
  ]
}
</code>```

however, after all commands are executed successfully i.e. systemctl shows the correct response, my prompt hangs at aws_instance.web_server_instance: Still creating...

my full code

```<code>terraform {
  required_version = "~> 1.1.5"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "3.74.1"
    }

    local = {
      source  = "hashicorp/local"
      version = "2.1.0"
    }

    tls = {
      source  = "hashicorp/tls"
      version = "3.1.0"
    }
  }
}

provider "aws" {
  profile = "terraform"
  region  = "us-east-1"
}

locals {
  application_name = "web_server"
}

# ssh key

resource "tls_private_key" "web_server_key_pair_gen" {
  algorithm = "RSA"
}

resource "local_file" "web_server_private_key" {
  content  = tls_private_key.web_server_key_pair_gen.private_key_pem
  filename = "${local.application_name}_private_key.pem"
}

resource "aws_key_pair" "web_server_public_key" {
  key_name   = "${local.application_name}_public_key"
  public_key = tls_private_key.web_server_key_pair_gen.public_key_openssh
}

# security group

resource "aws_security_group" "web_server_security_group" {
  name = "${local.application_name}_security_group"

  dynamic "ingress" {
    for_each = [
      { port = 22, description = "ssh" },
      { port = 80, description = "http" },
    ]
    content {
      description      = ingress.value.description
      from_port        = ingress.value.port
      to_port          = ingress.value.port
      protocol         = "tcp"
      cidr_blocks      = ["0.0.0.0/0"]
      ipv6_cidr_blocks = []
      prefix_list_ids  = []
      security_groups  = []
      self             = false
    }
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${local.application_name}_security_group"
  }
}

# ami lookup

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}

# ec2 instance

resource "aws_instance" "web_server_instance" {
  ami                         = data.aws_ami.ubuntu.id
  instance_type               = "t2.micro"
  vpc_security_group_ids      = [aws_security_group.web_server_security_group.id]
  key_name                    = aws_key_pair.web_server_public_key.key_name
  associate_public_ip_address = true

  connection {
    user        = "ubuntu"
    private_key = tls_private_key.web_server_key_pair_gen.private_key_pem
    host        = self.public_ip
  }

  provisioner "local-exec" {
    command = "chmod 600 ${local_file.web_server_private_key.filename}"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt update -y",
      "sudo apt upgrade -y",
      "sudo apt install apache2 -y",
      "sudo systemctl status apache2"
    ]
  }

  tags = {
    Name = "${local.application_name}_instance"
  }
}

output "server_public_ip" {
  value = aws_instance.web_server_instance.public_ip
}
</code>```

答:
While you probably should follow advice given in comments, your specific case is probably due to systemctl output being piped through the pager (less), so it waits to receive q to quit.

https://man7.org/linux/man-pages/man1/systemctl.1.html:

```<code>   $SYSTEMD_PAGER
       Pager to use when --no-pager is not given; overrides $PAGER.
       If neither $SYSTEMD_PAGER nor $PAGER are set, a set of
       well-known pager implementations are tried in turn, including
       less(1) and more(1), until one is found. If no pager
       implementation is discovered no pager is invoked. Setting
       this environment variable to an empty string or the value
       "cat" is equivalent to passing --no-pager.
</code>```

Using --no-pager option should help here.

Body:
I am trying to spin up an EC2 instance using an ubuntu image. I want to provide ssh access to the instance, install and run the apache server, and open up port 80, all through terraform.

I have the following code for remote-exec for my EC2

provisioner "remote-exec" {
  inline = [
    "sudo apt update -y",
    "sudo apt upgrade -y",
    "sudo apt install apache2 -y",
    "sudo systemctl status apache2"
  ]
}

however, after all commands are executed successfully i.e. systemctl shows the correct response, my prompt hangs at aws_instance.web_server_instance: Still creating...

my full code

terraform {
  required_version = "~> 1.1.5"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "3.74.1"
    }

    local = {
      source  = "hashicorp/local"
      version = "2.1.0"
    }

    tls = {
      source  = "hashicorp/tls"
      version = "3.1.0"
    }
  }
}

provider "aws" {
  profile = "terraform"
  region  = "us-east-1"
}

locals {
  application_name = "web_server"
}

# ssh key

resource "tls_private_key" "web_server_key_pair_gen" {
  algorithm = "RSA"
}

resource "local_file" "web_server_private_key" {
  content  = tls_private_key.web_server_key_pair_gen.private_key_pem
  filename = "${local.application_name}_private_key.pem"
}

resource "aws_key_pair" "web_server_public_key" {
  key_name   = "${local.application_name}_public_key"
  public_key = tls_private_key.web_server_key_pair_gen.public_key_openssh
}

# security group

resource "aws_security_group" "web_server_security_group" {
  name = "${local.application_name}_security_group"

  dynamic "ingress" {
    for_each = [
      { port = 22, description = "ssh" },
      { port = 80, description = "http" },
    ]
    content {
      description      = ingress.value.description
      from_port        = ingress.value.port
      to_port          = ingress.value.port
      protocol         = "tcp"
      cidr_blocks      = ["0.0.0.0/0"]
      ipv6_cidr_blocks = []
      prefix_list_ids  = []
      security_groups  = []
      self             = false
    }
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${local.application_name}_security_group"
  }
}

# ami lookup

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}

# ec2 instance

resource "aws_instance" "web_server_instance" {
  ami                         = data.aws_ami.ubuntu.id
  instance_type               = "t2.micro"
  vpc_security_group_ids      = [aws_security_group.web_server_security_group.id]
  key_name                    = aws_key_pair.web_server_public_key.key_name
  associate_public_ip_address = true

  connection {
    user        = "ubuntu"
    private_key = tls_private_key.web_server_key_pair_gen.private_key_pem
    host        = self.public_ip
  }

  provisioner "local-exec" {
    command = "chmod 600 ${local_file.web_server_private_key.filename}"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt update -y",
      "sudo apt upgrade -y",
      "sudo apt install apache2 -y",
      "sudo systemctl status apache2"
    ]
  }

  tags = {
    Name = "${local.application_name}_instance"
  }
}

output "server_public_ip" {
  value = aws_instance.web_server_instance.public_ip
}

Body:
While you probably should follow advice given in comments, your specific case is probably due to systemctl output being piped through the pager (less), so it waits to receive q to quit.

https://man7.org/linux/man-pages/man1/systemctl.1.html:

   $SYSTEMD_PAGER
       Pager to use when --no-pager is not given; overrides $PAGER.
       If neither $SYSTEMD_PAGER nor $PAGER are set, a set of
       well-known pager implementations are tried in turn, including
       less(1) and more(1), until one is found. If no pager
       implementation is discovered no pager is invoked. Setting
       this environment variable to an empty string or the value
       "cat" is equivalent to passing --no-pager.

Using --no-pager option should help here.


问:
Form fields stability when using jquery to create the form
I am using json to fill the options of select tag, when I choose the country, system synchronously fill the combobox of cities

```<code><label class="AddressLable">الدوله</label>
                <select name="country"  id="countryCB">
                <option >اختر</option>
                <?php $cntr=0;
                while($cntr < count($countries))
                {
                ?>
                    <option value="<?php echo $countries[$cntr]['countryNo']?>" <?php echo $_POST['country']==$countries[$cntr]['countryNo']?'selected':''?>> <?php echo $countries[$cntr]['countryName'];?></option>

                <?php
                $cntr++;
                }
                ?>
                </select>

                <label class="AddressLable">المدينة</label>
                <select name="city" id="cityCB">

                </select>
</code>```

//here is the jquery script

```<code>$("#countryCB").change(function(){
    var countryNo=$(this).val();
    var param={"action":"getCities",
                "countryNo":countryNo
    };
    $.getJSON("controllers/Customer.controller.php",param,function(result){
        input=$("#cityCB");
        $('>option',input).remove();
        $("#cityCB").append('<option> اختر</option>');
        $.each(result,function(i,val){

        var option = $('<option />');
        option.attr("value",val.cityNo);
        option.text(val.cityName);
        $("#cityCB").append(option);
        })
    });
</code>```

How can I make something like this:

```<code><?php echo $_POST['country']==$countries[$cntr]['countryNo']?'selected':''?>
</code>```

in jquery?

答:
```<code>$("cityCB option[value='your_value']").attr("selected", true);
</code>```

Run it after you append all of the options.

Body:
I am using json to fill the options of select tag, when I choose the country, system synchronously fill the combobox of cities

الدوله
                <select name="country"  id="countryCB">
                <option >اختر</option>
                <?php $cntr=0;
                while($cntr < count($countries))
                {
                ?>
                    <option value="<?php echo $countries[$cntr]['countryNo']?>" <?php echo $_POST['country']==$countries[$cntr]['countryNo']?'selected':''?>> <?php echo $countries[$cntr]['countryName'];?></option>

                <?php
                $cntr++;
                }
                ?>
                </select>

                المدينة
                <select name="city" id="cityCB">

                </select>

//here is the jquery script

$("#countryCB").change(function(){
    var countryNo=$(this).val();
    var param={"action":"getCities",
                "countryNo":countryNo
    };
    $.getJSON("controllers/Customer.controller.php",param,function(result){
        input=$("#cityCB");
        $('>option',input).remove();
        $("#cityCB").append('<option> اختر</option>');
        $.each(result,function(i,val){

        var option = $('<option />');
        option.attr("value",val.cityNo);
        option.text(val.cityName);
        $("#cityCB").append(option);
        })
    });

How can I make something like this:

<?php echo $_POST['country']==$countries[$cntr]['countryNo']?'selected':''?>

in jquery?

Body:
$("cityCB option[value='your_value']").attr("selected", true);

Run it after you append all of the options.


问:
Split up date range into chunks to join back into one table KDB+/Q
I have a table that is being joined like so

```<code>result: select from table where date within (sd;ed)
</code>```

where sd and ed span multiple months (like sd:2021.07.01 ed:2021.09.30). The table that I'm querying from has a break if you take more than a month, so to get the result I need, I have to do something like the following:

```<code>result: uj(uj(select from table where date within (2021.07.01;2021.07.30);select from table where date within (2021.08.01;2021.08.31));select from table where date within (2021.09.01;2021.09.30))
</code>```

How can I make this dynamic for any sd and ed? That is, how can I break up time range into first days of months, last days of months, and join them all into one table cleanly? My initial idea was to divide the days in the range x amount of time, to be input by a user, then add the number of days that results to the sd to get frames, but that got messy.

答:
Something like this should chunk it for you:

```<code>raze{select from t where date within x}each(first;last)@\:/:d group"m"$d:sd+til 1+ed-sd
</code>```

Do not use where date.month=x as you had suggested - at least not for historical queries

Body:
I have a table that is being joined like so

result: select from table where date within (sd;ed)

where sd and ed span multiple months (like sd:2021.07.01 ed:2021.09.30). The table that I'm querying from has a break if you take more than a month, so to get the result I need, I have to do something like the following:

result: uj(uj(select from table where date within (2021.07.01;2021.07.30);select from table where date within (2021.08.01;2021.08.31));select from table where date within (2021.09.01;2021.09.30))

How can I make this dynamic for any sd and ed? That is, how can I break up time range into first days of months, last days of months, and join them all into one table cleanly? My initial idea was to divide the days in the range x amount of time, to be input by a user, then add the number of days that results to the sd to get frames, but that got messy.

Body:
Something like this should chunk it for you:

raze{select from t where date within x}each(first;last)@\:/:d group"m"$d:sd+til 1+ed-sd

Do not use where date.month=x as you had suggested - at least not for historical queries


问:
How to properly mix sequential steps within parallel execution in an Airflow DAG?
I have an Airflow DAG I am writing where step_1 and step_2 run sequentially, and then in parallel kicked off three additional steps: X, Y, Z. Once those three steps completed, they run a final step, step_3. My DAG was written as:

step_1 >> step_2 >> [X, Y, Z] >> step_3

This worked just fine. However, I realized that X actually has two dependencies, we'll call them A and B, that need to run first. What I wanted to do was have those three - A, B, and X - run sequentially within one parallel lane, alongside Y and Z.

I wrote the DAG wiring as:

step_1 >> step_2 >> [A >> B >> X, Y, Z] >> step_3

This does not seem to have the expected results. I wanted A to be kicked off after step_2 ran, but it appears step_2 is still wired directly to X, with A and B just kind of... unlinked to either step_1 or step_2.

Does anyone know of a way to do this?

I know that I could pull A and B out of parallelism:

step_1 >> step_2 >> A >> B >> [X, Y, Z] >> step_3

But if possible I'd like to figure out a better approach. I have also read about subDAGs, but those seem overwrought for the simple tasks these steps are running.

答:
Looks like I found the proper way to write the wiring:

```<code>step_1 >> step_2 >> [A, Y, Z]

A >> B >> X >> step_3
Y >> step_3
Z >> step_3
</code>```

You transition from step_2 into the parallel operator, listing the first action that must be taken along each parallel path (in two of the three cases, they're the only action). Then you list each of those first actions, and write up the wiring for each path, with each path ending with the step on which they join.

Hope this helps someone else in the future.

Body:
Looks like I found the proper way to write the wiring:

step_1 >> step_2 >> [A, Y, Z]

A >> B >> X >> step_3
Y >> step_3
Z >> step_3

You transition from step_2 into the parallel operator, listing the first action that must be taken along each parallel path (in two of the three cases, they're the only action). Then you list each of those first actions, and write up the wiring for each path, with each path ending with the step on which they join.

Hope this helps someone else in the future.


问:
How can I remove double quotations surrounding a list imported from a file in Python?
I'm trying to create a food storage application that tracks the items put in a food storage facility and recalls them for the user. This is a very early prototype of the program, only capable of tracking the information locally, but I ran into some problems with it. So my apologies if this code is unreadable, I just can't find a solution to my problem explained below.

```<code>print("Food Storage Application V1.0 - LOCAL ONLY")
UPC_List = []
with open('UPCList.txt', 'r') as file:
    for UPCentry in file:
        location = UPCentry[:-1]
        UPC_List.append(location)
print(UPC_List)

global i
i = 0
UPC_Input = ''
UPC_Count = 0
while True:
    UPC_Found = False
    UPC_Input = input("Enter UPC or enter 'end' to quit: ")
    if UPC_Input == "end":
        with open("UPCList.txt", "w") as file:
            for UPCsave in UPC_List:
                file.write('%s\n' % UPCsave)
        break
    try:
        UPC_Input = int(UPC_Input)
    except ValueError as v:
        print(f"Input '{UPC_Input}' is not an acceptable UPC")
        continue

    # print(UPC_List) # for debugging

    def newProduct(UPC):
        global UPC_Count
        product_name = input(f"Enter name of item {UPC}: ")
        product_quantity = input(f"Enter quantity of item {UPC}: ")
        try:
            product_quantity = int(product_quantity)
        except ValueError as v:
            print("Invalid quantity. Please enter a number.")
            newProduct(UPC_Input)
        product_unit = input(f"Enter unit type (box, bunch, can, etc...) of item {UPC}: ")
        print(f"You have added: \n {product_name} \n {UPC} \n Quantity: {product_quantity} \n Unit: {product_unit}")
        UPC_List.insert(UPC_Count, [UPC, product_name, product_quantity, product_unit])
        UPC_Count += 1

    def existingProduct(UPC):
        for sublist in UPC_List:
            if str(UPC) in str(sublist):
                UPC = int(UPC)
                print(f"Position: {UPC_List.index(sublist)} {sublist.index(UPC)}")
                position = UPC_List.index(sublist)
                addition = input(f"Enter the number of items to add to '{UPC_List[position][1]}' (Default entry: +1): ")
                try:
                    addition = int(addition)
                except ValueError as v:
                    addition = 0

                if addition == 0:
                    UPC_List[position][2] += 1
                else:
                    UPC_List[position][2] += addition
                print(f"New Quantity for item '{UPC_List[position][1]}': {UPC_List[position][2]}")

    #Find if UPC Exists
    for UPC in UPC_List:
        if UPC[0] ==  UPC_Input:
            print("UPC Found")
            existingProduct(UPC_Input)
            UPC_Found = True
    if UPC_Found == False:
        newProduct(UPC_Input)
</code>```

This is my code so far. I made a version of it without the read and writing to file lines and it worked great, but I'm stumped on getting the code to read a list from a file and use it in the code. It saves the list, but it won't retrieve it correctly. I found what I think is the problem by using that print(UPC_List) line, which prints ["[2, 'banana', 2, 'bunch']"] (that was a test entry I loaded into the file using the program). I think the problem lies in the double quotes on the outside of the list. This is a nested list, so those quotation marks lead to an index error when I try to access the list.

If this isn't enough info, I can try to provide more. I'm very new to python and coding in general so this was my best attempt at the script.

答:
You are reading each list in as a string.

You can use the python eval function to convert a string into its evaluated form:

```<code>my_list_string = "['item1', 'item2']"
my_list = eval(my_list_string)
</code>```

Body:
I'm trying to create a food storage application that tracks the items put in a food storage facility and recalls them for the user. This is a very early prototype of the program, only capable of tracking the information locally, but I ran into some problems with it. So my apologies if this code is unreadable, I just can't find a solution to my problem explained below.

print("Food Storage Application V1.0 - LOCAL ONLY")
UPC_List = []
with open('UPCList.txt', 'r') as file:
    for UPCentry in file:
        location = UPCentry[:-1]
        UPC_List.append(location)
print(UPC_List)

global i
i = 0
UPC_Input = ''
UPC_Count = 0
while True:
    UPC_Found = False
    UPC_Input = input("Enter UPC or enter 'end' to quit: ")
    if UPC_Input == "end":
        with open("UPCList.txt", "w") as file:
            for UPCsave in UPC_List:
                file.write('%s\n' % UPCsave)
        break
    try:
        UPC_Input = int(UPC_Input)
    except ValueError as v:
        print(f"Input '{UPC_Input}' is not an acceptable UPC")
        continue

    # print(UPC_List) # for debugging

    def newProduct(UPC):
        global UPC_Count
        product_name = input(f"Enter name of item {UPC}: ")
        product_quantity = input(f"Enter quantity of item {UPC}: ")
        try:
            product_quantity = int(product_quantity)
        except ValueError as v:
            print("Invalid quantity. Please enter a number.")
            newProduct(UPC_Input)
        product_unit = input(f"Enter unit type (box, bunch, can, etc...) of item {UPC}: ")
        print(f"You have added: \n {product_name} \n {UPC} \n Quantity: {product_quantity} \n Unit: {product_unit}")
        UPC_List.insert(UPC_Count, [UPC, product_name, product_quantity, product_unit])
        UPC_Count += 1

    def existingProduct(UPC):
        for sublist in UPC_List:
            if str(UPC) in str(sublist):
                UPC = int(UPC)
                print(f"Position: {UPC_List.index(sublist)} {sublist.index(UPC)}")
                position = UPC_List.index(sublist)
                addition = input(f"Enter the number of items to add to '{UPC_List[position][1]}' (Default entry: +1): ")
                try:
                    addition = int(addition)
                except ValueError as v:
                    addition = 0

                if addition == 0:
                    UPC_List[position][2] += 1
                else:
                    UPC_List[position][2] += addition
                print(f"New Quantity for item '{UPC_List[position][1]}': {UPC_List[position][2]}")

    #Find if UPC Exists
    for UPC in UPC_List:
        if UPC[0] ==  UPC_Input:
            print("UPC Found")
            existingProduct(UPC_Input)
            UPC_Found = True
    if UPC_Found == False:
        newProduct(UPC_Input)

This is my code so far. I made a version of it without the read and writing to file lines and it worked great, but I'm stumped on getting the code to read a list from a file and use it in the code. It saves the list, but it won't retrieve it correctly. I found what I think is the problem by using that print(UPC_List) line, which prints ["[2, 'banana', 2, 'bunch']"] (that was a test entry I loaded into the file using the program). I think the problem lies in the double quotes on the outside of the list. This is a nested list, so those quotation marks lead to an index error when I try to access the list.

If this isn't enough info, I can try to provide more. I'm very new to python and coding in general so this was my best attempt at the script.

Body:
You are reading each list in as a string.

You can use the python eval function to convert a string into its evaluated form:

my_list_string = "['item1', 'item2']"
my_list = eval(my_list_string)