问:
Hide all but selected connected nodes in D3 (v4) force graph
I have created a dynamically built force graph in D3. When I click on one of the links I want to only show that and all the connected links/nodes.

This Plunkr is a simplified version of what I have: http://plnkr.co/edit/TiKKmvydqXNipe103juL?p=preview (EDIT: I have updated this and is now a complete solution).

As you can see there are 3 separate 'groups' of connected nodes, in my real data set there are several hundred nodes and I want to be able to isolate an individual 'group' and only show that when the link which is part of that group is clicked on (it can't be the node that is clicked on as this shows a pop-up with more info).

I have been able to colour/hide connected links by pre-processing my data and using a rather complicated and long winded algorithm to determine whether the links are in the same connected group.

I have also been able to change the node that is clicked on or all the nodes/links by changing the dragstart function, this feels like I am getting close, but I don't think it recognises any link relationships.

```<code>function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    // Changes all nodes/links
    d3.select("circle").classed("others",true).style("display","none");
    // Trying different ways to hide only 'other' nodes
    d3.selectAll("circle").classed("others",true).style("display","none");
    d3.selectAll("line").classed("others",true).style("display","none");

    d.fx = d.x;
    d.fy = d.y;
}
</code>```

(I am aware of this question/answer how to highlight(change color) of all connected(neighbours) nodes and links in a d3 force directed graph but I don't think it really helps).

Any help would be appreciated.

答:
OK, this might be beyond me, but I think you somehow need to group your links into the same sorts of groups as your nodes. If you could somehow add the "group" attribute of the source node to the link, then when you click on the link something like this might work:

```<code>d3.selectAll("line")function fade(){if
(group = "selected", "opacity" = 1)
else
("opacity" = 0)
};
</code>```

alternatively, if you can sort the links into groups before the data is loaded (in your PHP etc. script), then you could append 3 (or n) groups of lines with separate classes.

Sorry, JS isn't my strongsuit, hopefully someone more experienced will sort that out for us...

Body:
I have created a dynamically built force graph in D3. When I click on one of the links I want to only show that and all the connected links/nodes.

This Plunkr is a simplified version of what I have: http://plnkr.co/edit/TiKKmvydqXNipe103juL?p=preview (EDIT: I have updated this and is now a complete solution).

As you can see there are 3 separate 'groups' of connected nodes, in my real data set there are several hundred nodes and I want to be able to isolate an individual 'group' and only show that when the link which is part of that group is clicked on (it can't be the node that is clicked on as this shows a pop-up with more info).

I have been able to colour/hide connected links by pre-processing my data and using a rather complicated and long winded algorithm to determine whether the links are in the same connected group.

I have also been able to change the node that is clicked on or all the nodes/links by changing the dragstart function, this feels like I am getting close, but I don't think it recognises any link relationships.

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    // Changes all nodes/links
    d3.select("circle").classed("others",true).style("display","none");
    // Trying different ways to hide only 'other' nodes
    d3.selectAll("circle").classed("others",true).style("display","none");
    d3.selectAll("line").classed("others",true).style("display","none");

    d.fx = d.x;
    d.fy = d.y;
}

(I am aware of this question/answer how to highlight(change color) of all connected(neighbours) nodes and links in a d3 force directed graph but I don't think it really helps).

Any help would be appreciated.

Body:
OK, this might be beyond me, but I think you somehow need to group your links into the same sorts of groups as your nodes. If you could somehow add the "group" attribute of the source node to the link, then when you click on the link something like this might work:

d3.selectAll("line")function fade(){if
(group = "selected", "opacity" = 1)
else
("opacity" = 0)
};

alternatively, if you can sort the links into groups before the data is loaded (in your PHP etc. script), then you could append 3 (or n) groups of lines with separate classes.

Sorry, JS isn't my strongsuit, hopefully someone more experienced will sort that out for us...


来源: stackexchange

问:
c# why is my coroutine Executing only once regardless of condition for while loop?
I'm trying to execute a coroutine which destroys from a queue of gameobjects with a pause in between each execution until the Queue of game objects has been cleared, I have tried putting it in the start function and the update function and both give the same results of it only running once. coroutine works fine without clearDestroyStack function.

All the code is in a script attached to the game objects that are in the queue.

This is the call

```<code>if (lightningListFilled) {
        StartCoroutine ("clearLighteningTargets");
        lightningListFilled = false;
    }
    else {
    }
</code>```

The following is the coroutine.

```<code>IEnumerator clearLighteningTargets(){
    while (lighteningDestroyList.Count > 0) {
        Debug.Log ("From clear: "+lighteningDestroyList.Count);
        refScript.destroyStack.Push (lighteningDestroyList.Dequeue ());
        refScript.clearDestroyStack ();

        yield return new WaitForSeconds (0.5f);
        Debug.Log ("From clear: "+lighteningDestroyList.Count);

    }
}
</code>```

this is the code for the clearDestroyStack function

```<code>public void clearDestroyStack (){
    while (destroyStack.Count != 0) {
        GameObject ballToDestroy = destroyStack.Pop ();
        List<GameObject> ballToDestroyParents = ballToDestroy.GetComponent<MoveToCenter> ().parents;
        List<GameObject> ballToDestroyChildren = ballToDestroy.GetComponent<MoveToCenter> ().children;
        foreach (GameObject parent in ballToDestroyParents) {
            if (parent != null) {
                if (parent.GetComponent<MoveToCenter> ().children.Contains (ballToDestroy)) {
                    parent.GetComponent<MoveToCenter> ().children.Remove (ballToDestroy);
                }
            }

        }
        foreach (GameObject child in ballToDestroyChildren) {
            if (child != null) {
                if (child.GetComponent<MoveToCenter> ().parents.Contains (ballToDestroy)) {
                    child.GetComponent<MoveToCenter> ().parents.Remove (ballToDestroy);
                }
            }

        }
        GameObject[] allBalls = GameObject.FindGameObjectsWithTag ("ball");

        foreach (GameObject ball in allBalls) {
            ball.GetComponent<MoveToCenter> ().isSafe = false;
        }
        Destroy (ballToDestroy);
        //startSafeScan ();
        //deleteUnsafeBalls ();
        //clearDestroyStack ();
    }
}
</code>```

答: Coroutines stop if the object they are attached to is destroyed.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to execute a coroutine which destroys from a queue of gameobjects with a pause in between each execution until the Queue of game objects has been cleared, I have tried putting it in the start function and the update function and both give the same results of it only running once. coroutine works fine without clearDestroyStack function.

All the code is in a script attached to the game objects that are in the queue.

This is the call

if (lightningListFilled) {
        StartCoroutine ("clearLighteningTargets");
        lightningListFilled = false;
    }
    else {
    }

The following is the coroutine.

IEnumerator clearLighteningTargets(){
    while (lighteningDestroyList.Count > 0) {
        Debug.Log ("From clear: "+lighteningDestroyList.Count);
        refScript.destroyStack.Push (lighteningDestroyList.Dequeue ());
        refScript.clearDestroyStack ();

        yield return new WaitForSeconds (0.5f);
        Debug.Log ("From clear: "+lighteningDestroyList.Count);

    }
}

this is the code for the clearDestroyStack function

public void clearDestroyStack (){
    while (destroyStack.Count != 0) {
        GameObject ballToDestroy = destroyStack.Pop ();
        List<GameObject> ballToDestroyParents = ballToDestroy.GetComponent<MoveToCenter> ().parents;
        List<GameObject> ballToDestroyChildren = ballToDestroy.GetComponent<MoveToCenter> ().children;
        foreach (GameObject parent in ballToDestroyParents) {
            if (parent != null) {
                if (parent.GetComponent<MoveToCenter> ().children.Contains (ballToDestroy)) {
                    parent.GetComponent<MoveToCenter> ().children.Remove (ballToDestroy);
                }
            }

        }
        foreach (GameObject child in ballToDestroyChildren) {
            if (child != null) {
                if (child.GetComponent<MoveToCenter> ().parents.Contains (ballToDestroy)) {
                    child.GetComponent<MoveToCenter> ().parents.Remove (ballToDestroy);
                }
            }

        }
        GameObject[] allBalls = GameObject.FindGameObjectsWithTag ("ball");

        foreach (GameObject ball in allBalls) {
            ball.GetComponent<MoveToCenter> ().isSafe = false;
        }
        Destroy (ballToDestroy);
        //startSafeScan ();
        //deleteUnsafeBalls ();
        //clearDestroyStack ();
    }
}


问:
Rails 5 nested form find or create
I have two models Run and Patient.  Run belongs_to Patient and Patient has_many runs.

On the Run model I'm using accepts_nested_attributes in which to enter a patient's information into a run via a regular Rails form using fields_for.

Right now I have a basic form (stripped down version) that looks like this:

```<code><%= form_for(@run) do |f| %>
   <%= f.fields_for :patient do |p| %>
     <%= p.text_field :patient_name, placeholder: 'John Doe', class: 'form-control' %>
    <% end %>
<% end %>
</code>```

I'm able to create a patient inside of the form and reject the associated/nested object created inside of the model.  But what i'm looking to do is:

1.) Have a search/select box where I can type a patient name in and it will autocomplete

2.) If it finds the patient, it selects the patient and uses it for the run.

3.) If it does not find the patient or it's not the right patient, I'd like to be able to use first_or_create somehow to create the new patient record tied to the run.

I have searched for some examples on this and have come up short except an old Railscast espisode which wasn't very helpful and uses jQuery autocomplete which I'd like to avoid (use selectize or select2 instead).

I will continue working on examples that I find online, but any suggestions on how to do this is what I'm looking for.  I feel that I can instantiate the patients from a collection within the controller and use those in a selectize/select2 box to choose the patient and the associated nested field of patient_id.  So selecting the patient would not be a problem, but I'm unsure as to how to tackle the creation of a patient that does not match.

答:
This answered my question:

https://gorails.com/episodes/select-or-create-with-selectize-js

I was able to get the behavior down that I needed using this.

Title: Rails 5 nested form find or create

Body:
I have two models Run and Patient.  Run belongs_to Patient and Patient has_many runs.

On the Run model I'm using accepts_nested_attributes in which to enter a patient's information into a run via a regular Rails form using fields_for.

Right now I have a basic form (stripped down version) that looks like this:

<%= form_for(@run) do |f| %>
   <%= f.fields_for :patient do |p| %>
     <%= p.text_field :patient_name, placeholder: 'John Doe', class: 'form-control' %>
    <% end %>
<% end %>

I'm able to create a patient inside of the form and reject the associated/nested object created inside of the model.  But what i'm looking to do is:

1.) Have a search/select box where I can type a patient name in and it will autocomplete

2.) If it finds the patient, it selects the patient and uses it for the run.

3.) If it does not find the patient or it's not the right patient, I'd like to be able to use first_or_create somehow to create the new patient record tied to the run.

I have searched for some examples on this and have come up short except an old Railscast espisode which wasn't very helpful and uses jQuery autocomplete which I'd like to avoid (use selectize or select2 instead).

I will continue working on examples that I find online, but any suggestions on how to do this is what I'm looking for.  I feel that I can instantiate the patients from a collection within the controller and use those in a selectize/select2 box to choose the patient and the associated nested field of patient_id.  So selecting the patient would not be a problem, but I'm unsure as to how to tackle the creation of a patient that does not match.


问: When and how do browsers render

Title: When and how do browsers render <style> tag in <body>?

Body: I noticed that if I place

Body:
So it looks to me that the css is processed when the page is loaded, similar behavior to javascript document ready event. Am I right?

No. The stylesheet is modified with the new CSS code when that code is added to the DOM. There's no delay until the rest of the DOM has finished loading. If there was you'd see a FOUC.

which order would multiple <style> tags be processed?

The order they appear in. Then the normal rules of the cascade apply.


问:
Jersey throws NPE for each call after using ContainerRequestContext.abortWith()
I have a RESTful endpoint which I secured with a simple authorization check via a custom ContainerRequestFilter. The filter checks if all the information contained in the HTTP session is correct and if not it executes this:

```<code>requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
.entity("Forbidden").build());
</code>```

This is all fine and dandy. The strange thing is that when I make the same GET request again the Jersey server reports an NPE and does not return anything.

The NPE stacktrace:

```<code>Jul 20, 2016 5:27:53 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse
SEVERE: An I/O error has occurred while writing a response message entity to the container output stream.
java.lang.IllegalStateException: The output stream has already been closed.
    at org.glassfish.jersey.message.internal.CommittingOutputStream.setStreamProvider(CommittingOutputStream.java:147)
    at org.glassfish.jersey.message.internal.OutboundMessageContext.setStreamProvider(OutboundMessageContext.java:803)
    at org.glassfish.jersey.server.ContainerResponse.setStreamProvider(ContainerResponse.java:372)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:694)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:384)
    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:224)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)
</code>```

What is happening? I dont want to close the output stream. I only need a method to return a http return code + message to the requester.

答:
You need not use requestContext.abortWith() inside the filter method. Instead, do the following.

```<code>    String authCredentials = containerRequest.getHeaderString(HttpHeaders.AUTHORIZATION);
</code>```

The header sent from your REST client [browser/postman/SoapUI/jersey client program] will be of the format "Basic encodedString". The encodedString can be easily decoded using java.util.Base64. After decoding it at server end, the string will be of format username:password. Use String.split(":");to separate user name and password. Proceed to validation.
If validation turns false, throw WebApplicationException from the ContainerRequestFilter's filter method that you are overriding here.

Body:
I have a RESTful endpoint which I secured with a simple authorization check via a custom ContainerRequestFilter. The filter checks if all the information contained in the HTTP session is correct and if not it executes this:

requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
.entity("Forbidden").build());

This is all fine and dandy. The strange thing is that when I make the same GET request again the Jersey server reports an NPE and does not return anything.

The NPE stacktrace:

Jul 20, 2016 5:27:53 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse
SEVERE: An I/O error has occurred while writing a response message entity to the container output stream.
java.lang.IllegalStateException: The output stream has already been closed.
    at org.glassfish.jersey.message.internal.CommittingOutputStream.setStreamProvider(CommittingOutputStream.java:147)
    at org.glassfish.jersey.message.internal.OutboundMessageContext.setStreamProvider(OutboundMessageContext.java:803)
    at org.glassfish.jersey.server.ContainerResponse.setStreamProvider(ContainerResponse.java:372)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:694)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:384)
    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:224)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

What is happening? I dont want to close the output stream. I only need a method to return a http return code + message to the requester.

Body:
You need not use requestContext.abortWith() inside the filter method. Instead, do the following.

    String authCredentials = containerRequest.getHeaderString(HttpHeaders.AUTHORIZATION);

The header sent from your REST client [browser/postman/SoapUI/jersey client program] will be of the format "Basic encodedString". The encodedString can be easily decoded using java.util.Base64. After decoding it at server end, the string will be of format username:password. Use String.split(":");to separate user name and password. Proceed to validation.
If validation turns false, throw WebApplicationException from the ContainerRequestFilter's filter method that you are overriding here.


问:
How to document functions within a module using jsdoc?
```<code>/**
* Displays the list of autolab commands along with their functions.
* @module lib/help
*/
var Table = require('cli-table');
var chalk = require('chalk');
var helpjson = {
    'init'              : 'Initializes local repository and authenticates',
    'exit'              : 'Wipes off the credentials from the system',
    'git create'        : 'Creates a repository on Gitlab',
    'git delete'        : 'Deletes the specified repository from Gitlab',
    'git changeserver'  : 'To change the host of Gitlab',
    'git changelang'    : 'To change the language of the code submission',
    'git push'          : 'Adds, commits, pushes the code',
    'submit'            : 'To submit the code to JavaAutolab and fetch the results',
    'help'              : 'Print help manual'
};
module.exports = function() {
    /**
    * Displays the list of autolab commands along with their functions.
    * @function
    * @param {null}
    */
    console.log('\n' + chalk.blue('Usage:') + ' autolab [OPTIONS]');
    var table = new Table({
        head: ['Options:', ''],
        colWidths: [20,70]
    });
    for (var key in helpjson)
    table.push(
        [key,helpjson[key]]
        );
    console.log(table.toString());
};
</code>```

I tried this but the html page only shows lib/help and then a blank page. I also wanted to use @exports to mention what the module exports. Also is there a way to document the purpose and overview of the object in JSDoc.

答:
JSDoc comment block should be before your function declaration...

```<code>    /**
    * Displays the list of autolab commands along with their functions.
    * @module lib/help
    */
    var Table = require('cli-table');
    var chalk = require('chalk');
    var helpjson = {
        'init': 'Initializes local repository and authenticates',
        'exit': 'Wipes off the credentials from the system',
        'git create': 'Creates a repository on Gitlab',
        'git delete': 'Deletes the specified repository from Gitlab',
        'git changeserver': 'To change the host of Gitlab',
        'git changelang': 'To change the language of the code submission',
        'git push': 'Adds, commits, pushes the code',
        'submit': 'To submit the code to JavaAutolab and fetch the results',
        'help': 'Print help manual'
    };
    /**
    * Displays the list of autolab commands along with their functions.
    * @function
    * @param {null}
    */
    module.exports = function () {
        console.log('\n' + chalk.blue('Usage:') + ' autolab [OPTIONS]');
        var table = new Table({
            head: ['Options:', ''],
            colWidths: [20, 70]
        });
        for (var key in helpjson)
            table.push(
                [key, helpjson[key]]
                );
        console.log(table.toString());
    };
</code>```

Also is there a way to document the purpose and overview of the object in JSDoc

The @file tag provides a description for a file. Use the tag in a JSDoc comment at the beginning of the file.

Try to get familiar with JSDoc by reading a bit more of documentation.

Body:
/**
* Displays the list of autolab commands along with their functions.
* @module lib/help
*/
var Table = require('cli-table');
var chalk = require('chalk');
var helpjson = {
    'init'              : 'Initializes local repository and authenticates',
    'exit'              : 'Wipes off the credentials from the system',
    'git create'        : 'Creates a repository on Gitlab',
    'git delete'        : 'Deletes the specified repository from Gitlab',
    'git changeserver'  : 'To change the host of Gitlab',
    'git changelang'    : 'To change the language of the code submission',
    'git push'          : 'Adds, commits, pushes the code',
    'submit'            : 'To submit the code to JavaAutolab and fetch the results',
    'help'              : 'Print help manual'
};
module.exports = function() {
    /**
    * Displays the list of autolab commands along with their functions.
    * @function
    * @param {null}
    */
    console.log('\n' + chalk.blue('Usage:') + ' autolab [OPTIONS]');
    var table = new Table({
        head: ['Options:', ''],
        colWidths: [20,70]
    });
    for (var key in helpjson)
    table.push(
        [key,helpjson[key]]
        );
    console.log(table.toString());
};

I tried this but the html page only shows lib/help and then a blank page. I also wanted to use @exports to mention what the module exports. Also is there a way to document the purpose and overview of the object in JSDoc.

Body:
JSDoc comment block should be before your function declaration...

    /**
    * Displays the list of autolab commands along with their functions.
    * @module lib/help
    */
    var Table = require('cli-table');
    var chalk = require('chalk');
    var helpjson = {
        'init': 'Initializes local repository and authenticates',
        'exit': 'Wipes off the credentials from the system',
        'git create': 'Creates a repository on Gitlab',
        'git delete': 'Deletes the specified repository from Gitlab',
        'git changeserver': 'To change the host of Gitlab',
        'git changelang': 'To change the language of the code submission',
        'git push': 'Adds, commits, pushes the code',
        'submit': 'To submit the code to JavaAutolab and fetch the results',
        'help': 'Print help manual'
    };
    /**
    * Displays the list of autolab commands along with their functions.
    * @function
    * @param {null}
    */
    module.exports = function () {
        console.log('\n' + chalk.blue('Usage:') + ' autolab [OPTIONS]');
        var table = new Table({
            head: ['Options:', ''],
            colWidths: [20, 70]
        });
        for (var key in helpjson)
            table.push(
                [key, helpjson[key]]
                );
        console.log(table.toString());
    };

Also is there a way to document the purpose and overview of the object in JSDoc

The @file tag provides a description for a file. Use the tag in a JSDoc comment at the beginning of the file.

Try to get familiar with JSDoc by reading a bit more of documentation.


问:
Generating a signal that transforms from sine to rectangular shape using Matlab
I want to generate a signal that transforms from sine to rectangular shape with an increasing parameter f using Matlab.

For f = 0, the signal sould be a sine whereas for f = 1, the signal should be a rectangular signal with the same frequency. For increasing values between 0 and 1, the signal should become increasing similar to a rectangular signal.

Unfortunately, I don't know how to realise that using Matlab. Does anyone have an idea how to do that?

My idea was to use the Fourier series of a rectangular signal and - dependent on the parameter f - to consider a distinct number of summands of it.

答:
You can generate a purely square wave with period 2π using square.

You could do a weighted average of the square wave and sin wave, as an alternative to signal clipping as suggested by Luis in the comments.

```<code>t = 0:0.1:2*pi;
hold on
f = 0;    % entirely sine wave
plot(t, (square(t)*f + sin(t)*(1-f)))
f = 0.5;  % half and half
plot(t, (square(t)*f + sin(t)*(1-f)))
f = 1;    % entirely square wave
plot(t, (square(t)*f + sin(t)*(1-f)))
</code>```

Output:

Body:
You can generate a purely square wave with period 2π using square.

You could do a weighted average of the square wave and sin wave, as an alternative to signal clipping as suggested by Luis in the comments.

t = 0:0.1:2*pi;
hold on
f = 0;    % entirely sine wave
plot(t, (square(t)*f + sin(t)*(1-f)))
f = 0.5;  % half and half
plot(t, (square(t)*f + sin(t)*(1-f)))
f = 1;    % entirely square wave
plot(t, (square(t)*f + sin(t)*(1-f)))

Output:


问:
Can't INSERT INTO access database
I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.

Code:

```<code>Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader

conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
</code>```

I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database?  I can insert this query by running query directly in Access.

答:
Here is an example where data operations are in a separate class from form code.

Calling from a form

```<code>Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
    MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
</code>```

Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.

```<code>Public Class Operations1
    Private Builder As New OleDbConnectionStringBuilder With
    {
        .Provider = "Microsoft.ACE.OLEDB.12.0",
        .DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
    }
    Public Function AddNewRow(
        ByVal CompanyName As String,
        ByVal ContactName As String,
        ByRef Identfier As Integer) As Boolean

        Dim Success As Boolean = True
        Dim Affected As Integer = 0

        Try
            Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
                Using cmd As New OleDbCommand With {.Connection = cn}
                    cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (@CompanyName, @ContactName)"
                    cmd.Parameters.AddWithValue("@CompanyName", CompanyName)
                    cmd.Parameters.AddWithValue("@ContactName", ContactName)

                    cn.Open()

                    Affected = cmd.ExecuteNonQuery()
                    If Affected = 1 Then
                        cmd.CommandText = "Select @@Identity"
                        Identfier = CInt(cmd.ExecuteScalar)
                        Success = True
                    End If
                End Using
            End Using
        Catch ex As Exception
            Success = False
        End Try

        Return Success

    End Function
End Class
</code>```

Title: Can't INSERT INTO access database

Body:
I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.

Code:

Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader

conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()

I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database?  I can insert this query by running query directly in Access.

Body:
Here is an example where data operations are in a separate class from form code.

Calling from a form

Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
    MessageBox.Show($"New Id for Jim {newIdentifier}")
End If

Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.

Public Class Operations1
    Private Builder As New OleDbConnectionStringBuilder With
    {
        .Provider = "Microsoft.ACE.OLEDB.12.0",
        .DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
    }
    Public Function AddNewRow(
        ByVal CompanyName As String,
        ByVal ContactName As String,
        ByRef Identfier As Integer) As Boolean

        Dim Success As Boolean = True
        Dim Affected As Integer = 0

        Try
            Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
                Using cmd As New OleDbCommand With {.Connection = cn}
                    cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (@CompanyName, @ContactName)"
                    cmd.Parameters.AddWithValue("@CompanyName", CompanyName)
                    cmd.Parameters.AddWithValue("@ContactName", ContactName)

                    cn.Open()

                    Affected = cmd.ExecuteNonQuery()
                    If Affected = 1 Then
                        cmd.CommandText = "Select @@Identity"
                        Identfier = CInt(cmd.ExecuteScalar)
                        Success = True
                    End If
                End Using
            End Using
        Catch ex As Exception
            Success = False
        End Try

        Return Success

    End Function
End Class


问:
mismatched input '.' in rule
I am new to drools .I am writing a new rule.But i am getting Error as follow:

mismatched input '.' in rule "StopTextRule" in pattern

My rule is

```<code>package com.******.*****;

import java.lang.Number;

rule "StopTextRule"
    dialect "mvel"
    salience 20
    lock-on-active true
    when
        RoutingData( messageBody != null && (
                        (messageBody.trim().equalsIgnoreCase("stop") || messageBody.trim().equalsIgnoreCase("\"stop\"") || messageBody.trim().equalsIgnoreCase("stop.") || messageBody.trim().equalsIgnoreCase("\"stop.\""))
                            || (messageBody.trim().equalsIgnoreCase("quit")|| messageBody.trim().equalsIgnoreCase("\"quit\"") || messageBody.trim().equalsIgnoreCase("quit.")|| messageBody.trim().equalsIgnoreCase("\"quit.\""))
                            || (messageBody.trim().equalsIgnoreCase("cancel")|| messageBody.trim().equalsIgnoreCase("\"cancel\"") || messageBody.trim().equalsIgnoreCase("cancel.")|| messageBody.trim().equalsIgnoreCase("\"cancel.\""))
                            || (messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE\"") || messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE.")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE.\"")))
                            && incomingMessageProtocol != null && incomingMessageProtocol.trim().equalsIgnoreCase("X"))
        routingResp : RoutingRuleResponse( isStop == false )
    then
        modify( routingResp ) {
                setIsStop( true )
        }
end
</code>```

答:
This compiles using Drools 6.4.0. I think that you are using an older version where Java expressions had to be enclosed in eval.

It would be simpler in any case to rewrite this pattern like so:

```<code>rule x
when
   X( messageBody != null &&
      messageBody matches "\\s*(\"?)(?i:stop|quit|cancel|unsubscribe)\\.?\\1\\s*" &&
      incomingMessageProtocol != null &&
      incomingMessageProtocol matches "\\s*(?i:X)\\s*") )
then
   // ...
end
</code>```

Title: mismatched input '.' in rule

Body:
I am new to drools .I am writing a new rule.But i am getting Error as follow:

mismatched input '.' in rule "StopTextRule" in pattern

My rule is

package com.******.*****;

import java.lang.Number;

rule "StopTextRule"
    dialect "mvel"
    salience 20
    lock-on-active true
    when
        RoutingData( messageBody != null && (
                        (messageBody.trim().equalsIgnoreCase("stop") || messageBody.trim().equalsIgnoreCase("\"stop\"") || messageBody.trim().equalsIgnoreCase("stop.") || messageBody.trim().equalsIgnoreCase("\"stop.\""))
                            || (messageBody.trim().equalsIgnoreCase("quit")|| messageBody.trim().equalsIgnoreCase("\"quit\"") || messageBody.trim().equalsIgnoreCase("quit.")|| messageBody.trim().equalsIgnoreCase("\"quit.\""))
                            || (messageBody.trim().equalsIgnoreCase("cancel")|| messageBody.trim().equalsIgnoreCase("\"cancel\"") || messageBody.trim().equalsIgnoreCase("cancel.")|| messageBody.trim().equalsIgnoreCase("\"cancel.\""))
                            || (messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE\"") || messageBody.trim().equalsIgnoreCase("UNSUBSCRIBE.")|| messageBody.trim().equalsIgnoreCase("\"UNSUBSCRIBE.\"")))
                            && incomingMessageProtocol != null && incomingMessageProtocol.trim().equalsIgnoreCase("X"))
        routingResp : RoutingRuleResponse( isStop == false )
    then
        modify( routingResp ) {
                setIsStop( true )
        }
end

Body:
This compiles using Drools 6.4.0. I think that you are using an older version where Java expressions had to be enclosed in eval.

It would be simpler in any case to rewrite this pattern like so:

rule x
when
   X( messageBody != null &&
      messageBody matches "\\s*(\"?)(?i:stop|quit|cancel|unsubscribe)\\.?\\1\\s*" &&
      incomingMessageProtocol != null &&
      incomingMessageProtocol matches "\\s*(?i:X)\\s*") )
then
   // ...
end


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答:
C is one of the most common languages for Linux programming, so you should know it. I would advise against using C++, maybe once you've done a project in C.

I use vim + gcc + gdb

Others use IDE's like Code::Blocks, KDevelop, or Eclipse.

My first advice would be: make Makefiles for anything you do.

ContentLicense: CC BY-SA 2.5

Title: Tools used for programming in Linux


问:
Is it possible to emulate a polarization filter during image processing, using C++ or OpenCV?
I've looked all over Stack and other sources, but I haven't seen any code that seems to successfully emulate what a polarization filter does, reducing glare. The application I want for this code won't allow for a physical filter, so I was wondering if anyone had tried this. </p>

<p>I'm using OpenCV image processing (mat) in C++ on an Android platform, and glare is interfering with the results I'm trying to get. Imagine a lost object you're trying to find based on a finite set of Red/Green/Blue values; if the object is smooth, glare would render bad results. And that's my current problem. </p>

答:
OK, no, there's no virtual polarization that can be accomplished just with code. It's possible to find (via image color saturation) glare spots on shiny objects, and those can be overwritten with nearby pixels without glare, but that's not the same thing as real polarization. That requires a physical, metal mesh in front of the lens, or sensor, to eliminate those stray light waves that create glare. </p>

<p>Tell you what. The person who invents the virtual polarization filter, using just code, will be an instant billionaire since every cell phone and digital camera company will want to license the patent. </p>

Body:
I've looked all over Stack and other sources, but I haven't seen any code that seems to successfully emulate what a polarization filter does, reducing glare. The application I want for this code won't allow for a physical filter, so I was wondering if anyone had tried this.

I'm using OpenCV image processing (mat) in C++ on an Android platform, and glare is interfering with the results I'm trying to get. Imagine a lost object you're trying to find based on a finite set of Red/Green/Blue values; if the object is smooth, glare would render bad results. And that's my current problem.

Body:
OK, no, there's no virtual polarization that can be accomplished just with code. It's possible to find (via image color saturation) glare spots on shiny objects, and those can be overwritten with nearby pixels without glare, but that's not the same thing as real polarization. That requires a physical, metal mesh in front of the lens, or sensor, to eliminate those stray light waves that create glare.

Tell you what. The person who invents the virtual polarization filter, using just code, will be an instant billionaire since every cell phone and digital camera company will want to license the patent.


问:
Unable to get the list in the fragments (Android Studio)
Why I am unable to get listview in the fragment. I have created the list along with the items. I have added items but unable to understand this. Please help me out to understand it. I have copied it and edited it.

Here's my code:

```<code>public class NewsFragment extends Fragment {
private ListView mListView;
private List<String> mNewsList;

public NewsFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View frag = inflater.inflate(R.layout.fragment_news, container,                                                                                false);
    mListView = (ListView) frag.findViewById(R.id.MyListView);

    mNewsList = new ArrayList<String>();
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");

 //   mListView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,mNewsList));
    mListView.setAdapter(new MyAdapter());
    return frag;

}
private class MyAdapter extends BaseAdapter{

    @Override
    public int getCount() {
        return mNewsList.size();
    }

    @Override
    public Object getItem(int position) {
        return mNewsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowview = getActivity().getLayoutInflater().inflate(R.layout.row,null);
        return rowview;
    }
  }
}
</code>```

Any suggestions?

答:
You are just adding adapter to listview but no data resourcing are there is adapter..

```<code>mListView.setAdapter(new MyAdapters());
</code>```

try to use arrayAdapter for data-source like String array

```<code>mListView.setAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, mNewsList));
</code>```

and mNewsList should be String[].

Body:
Why I am unable to get listview in the fragment. I have created the list along with the items. I have added items but unable to understand this. Please help me out to understand it. I have copied it and edited it.

Here's my code:

public class NewsFragment extends Fragment {
private ListView mListView;
private List<String> mNewsList;

public NewsFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View frag = inflater.inflate(R.layout.fragment_news, container,                                                                                false);
    mListView = (ListView) frag.findViewById(R.id.MyListView);

    mNewsList = new ArrayList<String>();
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");

 //   mListView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,mNewsList));
    mListView.setAdapter(new MyAdapter());
    return frag;

}
private class MyAdapter extends BaseAdapter{

    @Override
    public int getCount() {
        return mNewsList.size();
    }

    @Override
    public Object getItem(int position) {
        return mNewsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowview = getActivity().getLayoutInflater().inflate(R.layout.row,null);
        return rowview;
    }
  }
}

Any suggestions?

Body:
You are just adding adapter to listview but no data resourcing are there is adapter..

mListView.setAdapter(new MyAdapters());

try to use arrayAdapter for data-source like String array

mListView.setAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, mNewsList));

and mNewsList should be String[].


问:
Why won't React production build run on the browser?
I'm trying to build my react app using react's build tool. When I try to "npm start", the app works fine.

```<code>npm start
</code>```

On http://localhost:3000 => I can access the application.

But when I build the application and try to access "index.html" file on the build folder, it doesn't work and I encounter with a white blank screen.

```<code>npm run build
</code>```

http://myreact-app/build/index.html => White blank screen.

This is the build folder which has been created after run npm run build.

And this is the index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>React App</title>
    <link href="/static/css/main.9a0fe4f1.css" rel="stylesheet">
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript" src="/static/js/main.46d8cd76.js"></script>
  </body>
</html>
</code>```

Am I doing something wrong? Can't I access the built index.html file on my apache web server?

答:
Probably you've not noticed yet but I don't think your html file is able to import css and script files correctly. When I look at your file structure, I see the everything about build is under the build folder. But in your html file, there are slashes ("/") before the file paths. That's why browser is looking for those files under the parent of the "build". Try to remove slashes.</p>

```<code><!DOCTYPE html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
      <meta name="theme-color" content="#000000">
      <link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico">
      <title>React App</title>
      <style></style>
      <link href="static/css/main.65027555.css" rel="stylesheet">
    </head>
    <body
      <noscript>You need to enable JavaScript to run this app.</noscript>
      <div id="root"></div>
      <script type="text/javascript" src="static/js/main.316f1156.js"></script>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build my react app using react's build tool. When I try to "npm start", the app works fine.

npm start

On http://localhost:3000 => I can access the application.

But when I build the application and try to access "index.html" file on the build folder, it doesn't work and I encounter with a white blank screen.

npm run build

http://myreact-app/build/index.html => White blank screen.

This is the build folder which has been created after run npm run build.

And this is the index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>React App</title>
    <link href="/static/css/main.9a0fe4f1.css" rel="stylesheet">

    You need to enable JavaScript to run this app.

Am I doing something wrong? Can't I access the built index.html file on my apache web server?

Body:
Probably you've not noticed yet but I don't think your html file is able to import css and script files correctly. When I look at your file structure, I see the everything about build is under the build folder. But in your html file, there are slashes ("/") before the file paths. That's why browser is looking for those files under the parent of the "build". Try to remove slashes.

<!DOCTYPE html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
      <meta name="theme-color" content="#000000">
      <link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico">
      <title>React App</title>
      <style></style>
      <link href="static/css/main.65027555.css" rel="stylesheet">
    </head>
    <body
      <noscript>You need to enable JavaScript to run this app.</noscript>
      <div id="root"></div>
      <script type="text/javascript" src="static/js/main.316f1156.js"></script>
    </body>
</html>


问:
Python/Psychopy: Instantiating multiple circle objects from a class
I've made a class that contains a circle (a Psychopy Circle object). I want to know how I can instantiate 2 circle objects using this class, each for example, with a different fill color.

```<code>class Circle(object):
    def __init__(self):
        self.circle = visual.Circle(win, units = 'deg', pos=(1,1),
        radius=1, lineColor="black", fillColor="red")

        self.components = [self.circle]

    def draw(self):
        [component.draw() for component in self.components]

circle=Circle() #red colour
circle2=Circle() #blue colour if possible
</code>```

Is there a way for me to instantiate circle2 whilst accessing some of the visual.circle parameters e.g. to change it's position or fill color? This is my first use of classes. Currently, If I draw 'circle' and 'cirle2' to the screen, one simply overlays the other, as one is merely a copy of the other.

Cheers,
Jon

答: You can change the constructor of the class (the __init__ method) adding an atribute color and in the fillColor change the value to the variable color. With the position you can do the same.

Body:
I've made a class that contains a circle (a Psychopy Circle object). I want to know how I can instantiate 2 circle objects using this class, each for example, with a different fill color.

class Circle(object):
    def __init__(self):
        self.circle = visual.Circle(win, units = 'deg', pos=(1,1),
        radius=1, lineColor="black", fillColor="red")

        self.components = [self.circle]

    def draw(self):
        [component.draw() for component in self.components]

circle=Circle() #red colour
circle2=Circle() #blue colour if possible

Is there a way for me to instantiate circle2 whilst accessing some of the visual.circle parameters e.g. to change it's position or fill color? This is my first use of classes. Currently, If I draw 'circle' and 'cirle2' to the screen, one simply overlays the other, as one is merely a copy of the other.

Cheers,
Jon


问:
Using linear index to map to 4D array
I am just starting with CUDA programming and I am bewildered by the speeds compared to normal CPUs. However, I am now getting running in a simple logical consideration. I am in device code, and I have 4D to inspect. I made a constant variable and I use atomicAdd to add through each iteration through the device code.

```<code>//get global counter
int global_index = atomicAdd(&counter, 1);
</code>```

I then consider a 4D volume, and I attempt to map the linear index to the 4D volume. I know that for 2D ad 3D, there is an effective way of converting from 1D index to 3D mapping. However, I do not know how this methodology expands into a higher dimension.

```<code>int x = gcfg->dimlen.x;
int y = gcfg->dimlen.y / x;
int z = gcfg->dimlen.z / gcfg->dimlen.y;
int photons = numberofphotons[1];
</code>```

Here is my 4 dimensions' lengths. So, to reiterate the problem I am having: I have an index that I want to map to a 4D array with lengths specified by the above 4 dimensions (x,y,z,numberofphotons)

答:
I'm not sure I've understood the meanings of the variables in your question, but following code is for the case where first dimension length(x) == second dimension length(y) == third dimension length(z) == 4. It converts linear index i into indices for each dimension: first_index, second_index, third_index, fourth_index.

```<code>int main()
{
    int x = 4;
    int y = 4;
    int z = 4;

    for (int i = 0; i < 100; i++) {
        int fourth_index = i / (x * y * z);
        int third_index = i % (x * y * z) / (x * y);
        int second_index = i % (x * y * z) % (x * y) / x;
        int first_index = i % (x * y * z) % (x * y) % x;

        printf("%d: (%d, %d, %d, %d)\n", i, first_index, second_index, third_index, fourth_index);
    }
}
</code>```

Or you can go the other way round.

```<code>int main()
{
    int x = 4;
    int y = 4;
    int z = 4;

    for (int i = 0; i < 100; i++) {
        int first_index = i % x;
        int second_index = i / x % y;
        int third_index = i / x / y % z;
        int fourth_index = i / x / y / z;

        printf("%d: (%d, %d, %d, %d)\n", i, first_index, second_index, third_index, fourth_index);
    }
}
</code>```

Title: Using linear index to map to 4D array

Body:
I am just starting with CUDA programming and I am bewildered by the speeds compared to normal CPUs. However, I am now getting running in a simple logical consideration. I am in device code, and I have 4D to inspect. I made a constant variable and I use atomicAdd to add through each iteration through the device code.

//get global counter
int global_index = atomicAdd(&counter, 1);

I then consider a 4D volume, and I attempt to map the linear index to the 4D volume. I know that for 2D ad 3D, there is an effective way of converting from 1D index to 3D mapping. However, I do not know how this methodology expands into a higher dimension.

int x = gcfg->dimlen.x;
int y = gcfg->dimlen.y / x;
int z = gcfg->dimlen.z / gcfg->dimlen.y;
int photons = numberofphotons[1];

Here is my 4 dimensions' lengths. So, to reiterate the problem I am having: I have an index that I want to map to a 4D array with lengths specified by the above 4 dimensions (x,y,z,numberofphotons)

Body:
I'm not sure I've understood the meanings of the variables in your question, but following code is for the case where first dimension length(x) == second dimension length(y) == third dimension length(z) == 4. It converts linear index i into indices for each dimension: first_index, second_index, third_index, fourth_index.

int main()
{
    int x = 4;
    int y = 4;
    int z = 4;

    for (int i = 0; i < 100; i++) {
        int fourth_index = i / (x * y * z);
        int third_index = i % (x * y * z) / (x * y);
        int second_index = i % (x * y * z) % (x * y) / x;
        int first_index = i % (x * y * z) % (x * y) % x;

        printf("%d: (%d, %d, %d, %d)\n", i, first_index, second_index, third_index, fourth_index);
    }
}

Or you can go the other way round.

int main()
{
    int x = 4;
    int y = 4;
    int z = 4;

    for (int i = 0; i < 100; i++) {
        int first_index = i % x;
        int second_index = i / x % y;
        int third_index = i / x / y % z;
        int fourth_index = i / x / y / z;

        printf("%d: (%d, %d, %d, %d)\n", i, first_index, second_index, third_index, fourth_index);
    }
}


问:
failure to send email by SendInBlue
i'm using SendInBlue Java Api to send email, i write this code en scala:

```<code>object SendInBlueApi extends App{
  val http : Sendinblue= new Sendinblue("https://api.sendinblue.com/v2.0","API_KEY");
  var data: Map[String, Any]= Map[String, Any]()
  data += ("to" -> "test1@gmail.com")
  data += ("from" -> "test2@gmail.com")
  data += ("subject" -> "My subject")
  data += ("text" -> "This is text")
  val str = http.send_email(data)
  println(str.toString)
}
</code>```

but i get this error:
{"code":"failure","message":"valid 'to' email address required","data":[]}

答:
This is another way of adding elements in a map:</p>

```<code>object SendInBlueApi extends App{
  val http : Sendinblue= new Sendinblue("https://api.sendinblue.com/v2.0","API_KEY");
  var data: Map[String, Any] = Map[String, Any](
    data("to") -> "test1@gmail.com",
    data("from") -> "test2@gmail.com",
    data("subject") -> "My subject",
    data("text") -> "This is text"
  )
        println(str.toString)
}
</code>```

Title: failure to send email by SendInBlue

Body:
i'm using SendInBlue Java Api to send email, i write this code en scala:

object SendInBlueApi extends App{
  val http : Sendinblue= new Sendinblue("https://api.sendinblue.com/v2.0","API_KEY");
  var data: Map[String, Any]= Map[String, Any]()
  data += ("to" -> "test1@gmail.com")
  data += ("from" -> "test2@gmail.com")
  data += ("subject" -> "My subject")
  data += ("text" -> "This is text")
  val str = http.send_email(data)
  println(str.toString)
}

but i get this error:
{"code":"failure","message":"valid 'to' email address required","data":[]}

Body:
This is another way of adding elements in a map:

object SendInBlueApi extends App{
  val http : Sendinblue= new Sendinblue("https://api.sendinblue.com/v2.0","API_KEY");
  var data: Map[String, Any] = Map[String, Any](
    data("to") -> "test1@gmail.com",
    data("from") -> "test2@gmail.com",
    data("subject") -> "My subject",
    data("text") -> "This is text"
  )
        println(str.toString)
}


问:
How do you uninstall in *nix?
One of the things I still can't wrap my head around is rules of thumb to uninstall programs in *nix environments. Most of the time I'm happy to let the sleeping dogs lie and not uninstall software that I no longer need. But from time to time I end up with several Apaches, svn, etc.

So far here's what I know about dealing with this:

1) if you installed using apt-get or yum, there's an uninstall command. Very rarely there's an uninstall script somewhere in the app's folder, something like uninstall.sh

2) to figure out which particular install is being called from the command line use "type -a" command

3) use "sudo find / | grep" to find where else stuff might be installed (from what I understand type only looks for things that are in the PATH variable)

4) Add/change order of things in PATH to make the desireable version of the app to be first in line or add an alias to .bashrc

5) delete the stuff I no longer want. This one is easy if the application was installed only in one folder, but tricky if there are multiple. One trick that I've heard of is running a find with a time range to find all the files that changed arount the time when the install happened - that roughly shows what was changed and added.

Do you have anything to add/correct?

答: If you didn't use a package manager (rpm, apt, etc), then you probably installed from source. To install, you performed a process along the lines of ./configure && make && make install. If the application is well-behaved, that "install" make target should be coupled with an "uninstall" target. So extract the sources again, configure again (with the same paths), and make uninstall.</p>

OwnerDisplayName: deadprogrammer

Title: How do you uninstall in *nix?

LastEditorDisplayName: deadprogrammer

OwnerDisplayName: Tyler McHenry


问:
What do DateTime? and using(var x = new y()) mean?
I don't understand what the following lines mean, please explain them to me.

1.

```<code>DateTime? pInsertDate;
</code>```

At this variable declaration, What does ? mean?

2.

```<code>using (TransactionScope scope = new TransactionScope())
</code>```

At this object creation, What does using mean?

答:
SomeType? is syntactic sugar for Nullable<SomeType>. It can only be applied to value types (not reference types) and indicates that the variable will also be able to store a value equivalent to what null is for reference types.  (Value types cannot be null, so the Nullable<T> type was added to allow for such cases.  It's extremely useful in database binding code, where nullable columns are common.)

using (SomeType x = y) { ... } is syntactic sugar for:

```<code>SomeType x = y;
try {
    ...
} finally {
    if (x != null)
        ((IDisposable)x).Dispose();
}
</code>```

This pattern is common when using objects whose classes implement IDisposable, as a way to automatically clean up such objects when they are about to fall out of use.

Body:
I don't understand what the following lines mean, please explain them to me.

1.

DateTime? pInsertDate;

At this variable declaration, What does ? mean?

2.

using (TransactionScope scope = new TransactionScope())

At this object creation, What does using mean?

Body:
SomeType? is syntactic sugar for Nullable<SomeType>. It can only be applied to value types (not reference types) and indicates that the variable will also be able to store a value equivalent to what null is for reference types.  (Value types cannot be null, so the Nullable<T> type was added to allow for such cases.  It's extremely useful in database binding code, where nullable columns are common.)

using (SomeType x = y) { ... } is syntactic sugar for:

SomeType x = y;
try {
    ...
} finally {
    if (x != null)
        ((IDisposable)x).Dispose();
}

This pattern is common when using objects whose classes implement IDisposable, as a way to automatically clean up such objects when they are about to fall out of use.


问:
How could I improve the security of this php code?
I have created the PHP code:

```<code><?php

  include("../config.php");

  if(!isset($_COOKIE["sessionid"])) {
      header("location:../error_pages/403.php");
  } else {
      $value = $_COOKIE["sessionid"];
      $query = "SELECT * FROM users WHERE sessionid = ?";

      $stmt = $conn->prepare($query);
      $stmt->bind_param("s",$value);
      $stmt->execute();
      $result = $stmt->get_result();

      $rowcount = $result->num_rows;
      if ($rowcount != 1 ) {
          header("location:../error_pages/403.php");
      } else {
          $file = "/path/to/file/";
          header('Content-Description: File Transfer');
          header('Content-Disposition: attachment; filename='.basename("File_Name"));
          ob_clean();
          flush();
          readfile($file);
      }
  };
?>
</code>```

I'm wondering if there is a way the sessionid cookie could be manipulated to allow for SQL injection. As well as whether this download is secure. The file is not stored in a publicly accessible folder.

To prevent session stealing I'm serving the login page only over TLS, is there another method sessions could be stolen?

答:
By using a query parameter, you're safe from SQL injection.

Your code might be vulnerable to session hijacking. Here are some tips and resources:

Use TLS (https) for all requests, this defeats packet sniffers.

http://phpsecurity.org/ has a free sample chapter about session management. Or get the whole book, it's good.

What is the best way to prevent session hijacking?

https://www.owasp.org/index.php/Session_Management_Cheat_Sheet

Body:
I have created the PHP code:

<?php

  include("../config.php");

  if(!isset($_COOKIE["sessionid"])) {
      header("location:../error_pages/403.php");
  } else {
      $value = $_COOKIE["sessionid"];
      $query = "SELECT * FROM users WHERE sessionid = ?";

      $stmt = $conn->prepare($query);
      $stmt->bind_param("s",$value);
      $stmt->execute();
      $result = $stmt->get_result();

      $rowcount = $result->num_rows;
      if ($rowcount != 1 ) {
          header("location:../error_pages/403.php");
      } else {
          $file = "/path/to/file/";
          header('Content-Description: File Transfer');
          header('Content-Disposition: attachment; filename='.basename("File_Name"));
          ob_clean();
          flush();
          readfile($file);
      }
  };
?>

I'm wondering if there is a way the sessionid cookie could be manipulated to allow for SQL injection. As well as whether this download is secure. The file is not stored in a publicly accessible folder.

To prevent session stealing I'm serving the login page only over TLS, is there another method sessions could be stolen?


问:
How to Iterate through arithmetic operators across a static, excecutable formula in Python?
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

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

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

```<code>1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...
</code>```

arises and gives results of the equation.

How might I go about doing this?

答:
Not an elegant one (made on knee) but works, just to point out my logic.
The idea is to reduce the list one by one in correct order. E.g.:

Data: 1 * 2 + 3 * 4

After Step 1 ( first * evaluated ): 2 + 3 * 4

After Step 2 ( second * evaluated ): 2 + 12

After Step 3 ( + evaluated ): 14

The code:

```<code>import operator
import itertools

data = [1.0, 2.0, 3.0, 4.0]
operators_1 = [operator.mul, operator.div] # this operators have priority over that below
operators_2 = [operator.add, operator.sub]

def processOps(formula, data, operators):
    res_formula = list(formula)
    result = list(data)
    for op in formula:
        if op not in operators: continue

        i = res_formula.index(op)
        result = result[:i] + [op(result[i], result[i + 1])] + result[i + 2:]
        res_formula.remove(op)

        if len(result) == 1:
            break

    return (res_formula, result)

for f in itertools.product(operators_1 + operators_2, repeat=len(data)-1):
    result = list(data)
    formula = list(f)
    formula, result = processOps(formula, result, operators_1)
    formula, result = processOps(formula, result, operators_2)
    print f, result
</code>```

UDP This updated logic handles cases like (1 * 2) + (3 / 4) correctly.

Body:
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

1
1,2
1,3
2,3
1,2,3

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...

arises and gives results of the equation.

How might I go about doing this?

Body:
Not an elegant one (made on knee) but works, just to point out my logic.
The idea is to reduce the list one by one in correct order. E.g.:

Data: 1 * 2 + 3 * 4

After Step 1 ( first * evaluated ): 2 + 3 * 4

After Step 2 ( second * evaluated ): 2 + 12

After Step 3 ( + evaluated ): 14

The code:

import operator
import itertools

data = [1.0, 2.0, 3.0, 4.0]
operators_1 = [operator.mul, operator.div] # this operators have priority over that below
operators_2 = [operator.add, operator.sub]

def processOps(formula, data, operators):
    res_formula = list(formula)
    result = list(data)
    for op in formula:
        if op not in operators: continue

        i = res_formula.index(op)
        result = result[:i] + [op(result[i], result[i + 1])] + result[i + 2:]
        res_formula.remove(op)

        if len(result) == 1:
            break

    return (res_formula, result)

for f in itertools.product(operators_1 + operators_2, repeat=len(data)-1):
    result = list(data)
    formula = list(f)
    formula, result = processOps(formula, result, operators_1)
    formula, result = processOps(formula, result, operators_2)
    print f, result

UDP This updated logic handles cases like (1 * 2) + (3 / 4) correctly.


问:
BoxLayout inner JPannels alignment - how can I set them to left?
I have been struggling with BoxLayout. I have one JPanel containing 3 inner panels. The external panel is set to BoxLayout with vertical axis, the first and second inner panels were set to set to GridBagLayout and the last one to the flowLayout (left).

The result is that first and second inner containers are aligned to the center(I guess that is is caused by the default behavior of GBL without setting the weightx). How can I align them to the left?

Do I understand correctly that anchor would work inside a cell but not align the whole grid? And that weightx would distribute the space among the cells, but not move the whole container to the left? If that is the true, should I use another component as a wrapper, or is there another way?

```<code>panAdv1 = new JPanel();
add(panAdv1);
panAdv1.setLayout(new BoxLayout(panAdv1, BoxLayout.PAGE_AXIS));

// PANEL 1 //
panel1 = new JPanel();
panAdv1.add(panel1);
panel1.setLayout(new GridBagLayout());
</code>```

....

```<code>// PANEL 2 //

panel2 = new JPanel();
panAdv1.add(panel2);
panel2.setLayout(new GridBagLayout());
</code>```

...

```<code>//PANEL 5 - buttons //
panel5 = new JPanel();
panAdv1.add(panel5);
panel5.setLayout(new FlowLayout(FlowLayout.LEFT));
</code>```

答:
Read the section from the Swing tutorial on Fixing Alignment Problems. The BoxLayout respects the "alignment" property of the component.

How can I align them to the left?

The default for a JPanel would be to have the panel center aligned, so you will need to change the alignment to be left aligned.

Body:
I have been struggling with BoxLayout. I have one JPanel containing 3 inner panels. The external panel is set to BoxLayout with vertical axis, the first and second inner panels were set to set to GridBagLayout and the last one to the flowLayout (left).

The result is that first and second inner containers are aligned to the center(I guess that is is caused by the default behavior of GBL without setting the weightx). How can I align them to the left?

Do I understand correctly that anchor would work inside a cell but not align the whole grid? And that weightx would distribute the space among the cells, but not move the whole container to the left? If that is the true, should I use another component as a wrapper, or is there another way?

panAdv1 = new JPanel();
add(panAdv1);
panAdv1.setLayout(new BoxLayout(panAdv1, BoxLayout.PAGE_AXIS));

// PANEL 1 //
panel1 = new JPanel();
panAdv1.add(panel1);
panel1.setLayout(new GridBagLayout());

....

// PANEL 2 //

panel2 = new JPanel();
panAdv1.add(panel2);
panel2.setLayout(new GridBagLayout());

...

//PANEL 5 - buttons //
panel5 = new JPanel();
panAdv1.add(panel5);
panel5.setLayout(new FlowLayout(FlowLayout.LEFT));


问:
Converted all drawables to WebP, apk size stayed the same
Very confused. I just converted a lot of drawables in my res folder to the lossless WebP format. As I did it, Android Studio told me I saved 6mb, however I just build an production-release apk, one for the branch with WebP images and one with everything still as PNG, the difference is negligible. The PNG apk size is 23.2MB, the WebP apk size is 21.3.

I ran the apk analyzer tool, and I can see that the big difference is my res folder is now 7MB smaller, yet that wasn't translated to the apk size?

Here is the apk analyzer results, firstly the old apk (PNGs) Left number is uncompressed, right value is compressed, so what goes out to users in the apk:

Secondly here is the new apk (WebP):

The drawable files are quite clearly smaller, my biggest folder inside res is now 200kb.

Can someone who has played with WebP in Android offer some information on why this didn't work? No other numbers have changed in the apk analyzer.

Edit: Sorry about the small images, view in new tab to see clearer

答:
Solved why it was happened.

I have shrinkResources set to true on my release builds in my build.gradle, so compression was already taking place.

Makes a lot of sense, mistake on my part, totally forgot about it.


答:
It depends on what sort of applications you intend to produce.

C/C++ is suitable with embedded/OS
applications (Vim + GCC).

Java is suitable with business applications (Eclipse + J2SE)

PS: Visual Studio isn't supposed to be run on Linux.

Title: Tools used for programming in Linux

Body:
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?


问:
Long press on Android menu item?
Is it possible to perform a long press on a menu item to perform a certain action?
I'm trying to have a menu dropdown when I long press a certain item.

Here's the menu xml

```<code><item
    android:id="@+id/add_item"
    android:icon="@drawable/ic_add_black_24dp"
    android:showAsAction="ifRoom"
    android:title="Add Item">
</item>

<item
    android:id="@+id/open_menu"
    android:icon="@drawable/ic_menu_black_24dp"
    android:showAsAction="ifRoom|withText"
    android:title="Open Menu">
</item>
</code>```

I want to have a dropdown appear when the first item is long pressed

答:
You can do this with Handler and Runnable. Inside run() method, get the View of your desired MenuItem and set onLongClick listener to View.

Here is the working code:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            final View view = findViewById(R.id.add_item);

            if (view != null) {
                view.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {

                        // Do something...

                        Toast.makeText(getApplicationContext(), "Long pressed", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                });
            }
        }
    });

    return super.onCreateOptionsMenu(menu);
}
</code>```

OUTPUT:

Title: Long press on Android menu item?

Body:
Is it possible to perform a long press on a menu item to perform a certain action?
I'm trying to have a menu dropdown when I long press a certain item.

Here's the menu xml

<item
    android:id="@+id/add_item"
    android:icon="@drawable/ic_add_black_24dp"
    android:showAsAction="ifRoom"
    android:title="Add Item">
</item>

<item
    android:id="@+id/open_menu"
    android:icon="@drawable/ic_menu_black_24dp"
    android:showAsAction="ifRoom|withText"
    android:title="Open Menu">
</item>

I want to have a dropdown appear when the first item is long pressed

Body:
You can do this with Handler and Runnable. Inside run() method, get the View of your desired MenuItem and set onLongClick listener to View.

Here is the working code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            final View view = findViewById(R.id.add_item);

            if (view != null) {
                view.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {

                        // Do something...

                        Toast.makeText(getApplicationContext(), "Long pressed", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                });
            }
        }
    });

    return super.onCreateOptionsMenu(menu);
}

OUTPUT:


问:
MongoDB Fails Because Key Too Large To Index
I have been attempting to save a MongoDB document, and am getting a strange error concerning the key being too large to index.  I have provided an example of a functional document below, as well as one that creates an error:

Functional:

```<code>{ uniquenumber: 'Valid Until Addition of Restrictions',
  name: 'Valid Until Addition of Restrictions'
  fieldofstudy: 'Valid Until Addition of Restrictions',
  section: 'Valid Until Addition of Restrictions',
  restrictions:
   { 'Must be assigned one of the following Student Attributes':
      [ 'Non-Res. In-State',
        'Non-Res. Out-of-State',
        'DE Student Non-Res Out-of-St',
        'Resident In-State',
        'Res. Out-of-State' ],
     'Must be enrolled in one of the following Levels': [ 'Graduate' ] },
  times: [],
  professors: [ 'Jo Blo' ] }
</code>```

Non-Functional:

```<code>{
    "uniquenumber": "Valid Until Addition of Restrictions",
    "name": "Valid Until Addition of Restrictions",
    "fieldofstudy": "Valid Until Addition of Restrictions",
    "section": 'Valid Until Addition of Restrictions',
    "restrictions": {
        "May not be enrolled in one of the following Programs": ["MA [LA] Non-thesis option", "MS [AG] Non-thesis option", "MS [AR] Non-thesis option", "MS [BA] Non-thesis option", "MS [COFD] Non-thesis option", "MS [ED] Non-thesis option", "MS [EN] Non-thesis option", "MS [GE] Non-thesis option", "MS [LA] Non-thesis option", "MS [SC] Non-thesis option", "MS [VM] Non-thesis option", "MS NTO (Special Programs)", "MUP [AR] Non-thesis option"],
        "Must be enrolled in one of the following Levels": ["Graduate"],
        "May not be enrolled in one of the following Degrees": ["Master of Agribusiness", "Master of Agriculture", "Master of Architecture", "Master of Business Admin.", "Master of Computer Science", "Master of Education", "Master of Engineering", "Master of Land Econ & Real Est", "Master of Geoscience", "Master of Landscape Arch.", "Master of Public Administratn", "Master of Public Health", "Master of Public Svc & Admin"],
        "May not be enrolled in one of the following Colleges": ["English Language Institute"],
        "Must be assigned one of the following Student Attributes": ["Non-Res. In-State", "Non-Res. Out-of-State", "DE Student Non-Res Out-of-St", "Resident In-State", "Res. Out-of-State"],
        "Must be enrolled in one of the following Classifications": ["G7-Graduate, Master's Level", "G8-Graduate, Doctoral Level", "G9-Graduate, Mas/Doc Admitted"]
    },
    "times": [],
    "professors": []
}
</code>```

Up until the creation of the restrictions object, the scraper was functioning as expected, so I believe the error can be narrowed down to there.  However, it is unclear to me where any key is "too large" to be indexed.  If my guess is correct, why is Mongo counting it as a key and how can I remedy the situation?

EDIT: The response to db.Section.getIndexes(); is shown below:

```<code>[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "database.Section"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "uniquenumber" : 1
                },
                "name" : "uniquenumber_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "fieldofstudy" : 1
                },
                "name" : "fieldofstudy_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "course" : 1
                },
                "name" : "course_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "section" : 1
                },
                "name" : "section_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "professors" : 1
                },
                "name" : "professors_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "times" : 1
                },
                "name" : "times_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "restrictions" : 1
                },
                "name" : "restrictions_1",
                "ns" : "database.Section",
                "background" : true
        }
]
</code>```

答:
You've got an index on restrictions which, based on your data, is completely useless and would be very large as that's a sub-document.

You likely want to drop that index from the collection:

```<code>db.Section.dropIndex({restrictions: 1});
</code>```

Body:
I have been attempting to save a MongoDB document, and am getting a strange error concerning the key being too large to index.  I have provided an example of a functional document below, as well as one that creates an error:

Functional:

{ uniquenumber: 'Valid Until Addition of Restrictions',
  name: 'Valid Until Addition of Restrictions'
  fieldofstudy: 'Valid Until Addition of Restrictions',
  section: 'Valid Until Addition of Restrictions',
  restrictions:
   { 'Must be assigned one of the following Student Attributes':
      [ 'Non-Res. In-State',
        'Non-Res. Out-of-State',
        'DE Student Non-Res Out-of-St',
        'Resident In-State',
        'Res. Out-of-State' ],
     'Must be enrolled in one of the following Levels': [ 'Graduate' ] },
  times: [],
  professors: [ 'Jo Blo' ] }

Non-Functional:

{
    "uniquenumber": "Valid Until Addition of Restrictions",
    "name": "Valid Until Addition of Restrictions",
    "fieldofstudy": "Valid Until Addition of Restrictions",
    "section": 'Valid Until Addition of Restrictions',
    "restrictions": {
        "May not be enrolled in one of the following Programs": ["MA [LA] Non-thesis option", "MS [AG] Non-thesis option", "MS [AR] Non-thesis option", "MS [BA] Non-thesis option", "MS [COFD] Non-thesis option", "MS [ED] Non-thesis option", "MS [EN] Non-thesis option", "MS [GE] Non-thesis option", "MS [LA] Non-thesis option", "MS [SC] Non-thesis option", "MS [VM] Non-thesis option", "MS NTO (Special Programs)", "MUP [AR] Non-thesis option"],
        "Must be enrolled in one of the following Levels": ["Graduate"],
        "May not be enrolled in one of the following Degrees": ["Master of Agribusiness", "Master of Agriculture", "Master of Architecture", "Master of Business Admin.", "Master of Computer Science", "Master of Education", "Master of Engineering", "Master of Land Econ & Real Est", "Master of Geoscience", "Master of Landscape Arch.", "Master of Public Administratn", "Master of Public Health", "Master of Public Svc & Admin"],
        "May not be enrolled in one of the following Colleges": ["English Language Institute"],
        "Must be assigned one of the following Student Attributes": ["Non-Res. In-State", "Non-Res. Out-of-State", "DE Student Non-Res Out-of-St", "Resident In-State", "Res. Out-of-State"],
        "Must be enrolled in one of the following Classifications": ["G7-Graduate, Master's Level", "G8-Graduate, Doctoral Level", "G9-Graduate, Mas/Doc Admitted"]
    },
    "times": [],
    "professors": []
}

Up until the creation of the restrictions object, the scraper was functioning as expected, so I believe the error can be narrowed down to there.  However, it is unclear to me where any key is "too large" to be indexed.  If my guess is correct, why is Mongo counting it as a key and how can I remedy the situation?

EDIT: The response to db.Section.getIndexes(); is shown below:

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "database.Section"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "uniquenumber" : 1
                },
                "name" : "uniquenumber_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "fieldofstudy" : 1
                },
                "name" : "fieldofstudy_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "course" : 1
                },
                "name" : "course_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "section" : 1
                },
                "name" : "section_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "professors" : 1
                },
                "name" : "professors_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "times" : 1
                },
                "name" : "times_1",
                "ns" : "database.Section",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "restrictions" : 1
                },
                "name" : "restrictions_1",
                "ns" : "database.Section",
                "background" : true
        }
]

Body:
You've got an index on restrictions which, based on your data, is completely useless and would be very large as that's a sub-document.

You likely want to drop that index from the collection:

db.Section.dropIndex({restrictions: 1});


问:
Javascript reference object by an identifier or reference it directly?
I am creating quite many objects in Javascript, which I need to be able to reference to retrieve later, for example through an array. Now I am wondering how to save the object reference in the array.

The objects will interract with an external library, which can function either with object IDs or the object itself. I know Javascript treats object variables like pointers and not object copies, so is it safe to reference the objects directly ?

At first I was thinking "if I save the IDs of the objects, that would keep memory usage low", but is this true ? How much memory does an object variable* consume versus an integer variable ?

*the pointer to the object, not the object data

Also, if saving the objects directly is the way to go, is it ok to use array.push() to add the new object to the array ? Is array.push() creating a copy or does it work like a variable ?

答:
Yes, you can reference the objects directly. If you really care about memory usage, I'd say the way of passing the ids will use more memory since you'll have to maintain another set of mappings.

Passing the objects directly will let the JavaScript engine to work directly with the object references. That's not affecting the memory usage, as long you don't to any cloning.


答:
I believe the relevant question is weather or not saving an integer and using that as an identifier later is more effective than saving a reference to the object.

I'd go with the reference in an array. the size of a reference vs a number is going to be negligible.

Title: Javascript reference object by an identifier or reference it directly?

Body:
I am creating quite many objects in Javascript, which I need to be able to reference to retrieve later, for example through an array. Now I am wondering how to save the object reference in the array.

The objects will interract with an external library, which can function either with object IDs or the object itself. I know Javascript treats object variables like pointers and not object copies, so is it safe to reference the objects directly ?

At first I was thinking "if I save the IDs of the objects, that would keep memory usage low", but is this true ? How much memory does an object variable* consume versus an integer variable ?

*the pointer to the object, not the object data

Also, if saving the objects directly is the way to go, is it ok to use array.push() to add the new object to the array ? Is array.push() creating a copy or does it work like a variable ?


问:
jQuery keyup event does not set event.shiftKey
I am trying to listen to the shift key being pressed and released again using jQuery.

See JSFiddle here

```<code>$(document).bind('keydown', function (event) {
    if (event.shiftKey) {
        document.body.innerHTML += 'shift down<br>';
    }
});
$(document).bind('keyup', function (event) {
    if (event.shiftKey) {
        document.body.innerHTML += 'shift up<br>';
    }
});
</code>```

The keyup/keydown events seem to be called properly in general. However, if shift is the only button being pressed then event.shiftKey is only set for the keyDOWN event, not for the keyUP event. You can see that in the JSFiddle the "key up" message is never printed in this case. However, if I press shift + something else (e.g. Ctrl) everything works like it should.

Is this a bug in jQuery? Any workarounds?

答:
e.shiftKey has a bug, I tried it. Does not work (My guess maybe on older instances)
Whereas e.which === 16 works perfectly fine.</p>

```<code>          self.on("keyup", ""+id, function(e) {
                if (e.which === 16) {
                    console.log(e.which);
                    // Your Code :)
                }
          }
</code>```

Body:
I am trying to listen to the shift key being pressed and released again using jQuery.

See JSFiddle here

$(document).bind('keydown', function (event) {
    if (event.shiftKey) {
        document.body.innerHTML += 'shift down
';
    }
});
$(document).bind('keyup', function (event) {
    if (event.shiftKey) {
        document.body.innerHTML += 'shift up
';
    }
});

The keyup/keydown events seem to be called properly in general. However, if shift is the only button being pressed then event.shiftKey is only set for the keyDOWN event, not for the keyUP event. You can see that in the JSFiddle the "key up" message is never printed in this case. However, if I press shift + something else (e.g. Ctrl) everything works like it should.

Is this a bug in jQuery? Any workarounds?

Body:
e.shiftKey has a bug, I tried it. Does not work (My guess maybe on older instances)
Whereas e.which === 16 works perfectly fine.

          self.on("keyup", ""+id, function(e) {
                if (e.which === 16) {
                    console.log(e.which);
                    // Your Code :)
                }
          }


问:
PyInstaller - OSError: [Errno 2] No such file or directory
I run into "OSError: [Errno 2] No such file or directory" while running pyinstaller. Could someone point me what needs to be installed or done to solve it?

Below is the error message.

```<code>root@mylinkit:/usr# pyinstaller t123.py
2999 INFO: PyInstaller: 3.2.1
3002 INFO: Python: 2.7.12
3013 INFO: Platform: Linux-3.18.44-mips-with-glibc2.0
3026 INFO: wrote /usr/t123.spec
3069 INFO: UPX is not available.
3089 INFO: Extending PYTHONPATH with paths
['/usr', '/usr']
3092 INFO: checking Analysis
3258 INFO: checking PYZ
3346 INFO: checking PKG
3356 INFO: Bootloader /usr/lib/python2.7/site-packages/PyInstaller/bootloader/Linux-32bit/run
3358 INFO: checking EXE
3360 INFO: Building EXE because out00-EXE.toc is non existent
3362 INFO: Building EXE from out00-EXE.toc
3575 INFO: Appending archive to ELF section in EXE /usr/build/t123/t123
Traceback (most recent call last):
  File "/usr/bin/pyinstaller", line 9, in <module>
load_entry_point('PyInstaller==3.2.1', 'console_scripts', 'pyinstaller')()
  File "/usr/lib/python2.7/site-packages/PyInstaller/__main__.py", line 90, in run
run_build(pyi_config, spec_file, **vars(args))
  File "/usr/lib/python2.7/site-packages/PyInstaller/__main__.py", line 46, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 788, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 734, in build
exec(text, spec_namespace)
  File "<string>", line 26, in <module>
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/api.py", line 411, in __init__
self.__postinit__()
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/datastruct.py", line 161, in __postinit__
self.assemble()
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/api.py", line 563, in assemble
self.name)
  File "/usr/lib/python2.7/site-packages/PyInstaller/compat.py", line 486, in exec_command_all
stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
root@mylinkit:/usr#
</code>```

答:
I've done some investigation and I believe binutils may be the missing dependency.

```<code>apt-get install binutils
</code>```

Body:
I run into "OSError: [Errno 2] No such file or directory" while running pyinstaller. Could someone point me what needs to be installed or done to solve it?

Below is the error message.

root@mylinkit:/usr# pyinstaller t123.py
2999 INFO: PyInstaller: 3.2.1
3002 INFO: Python: 2.7.12
3013 INFO: Platform: Linux-3.18.44-mips-with-glibc2.0
3026 INFO: wrote /usr/t123.spec
3069 INFO: UPX is not available.
3089 INFO: Extending PYTHONPATH with paths
['/usr', '/usr']
3092 INFO: checking Analysis
3258 INFO: checking PYZ
3346 INFO: checking PKG
3356 INFO: Bootloader /usr/lib/python2.7/site-packages/PyInstaller/bootloader/Linux-32bit/run
3358 INFO: checking EXE
3360 INFO: Building EXE because out00-EXE.toc is non existent
3362 INFO: Building EXE from out00-EXE.toc
3575 INFO: Appending archive to ELF section in EXE /usr/build/t123/t123
Traceback (most recent call last):
  File "/usr/bin/pyinstaller", line 9, in <module>
load_entry_point('PyInstaller==3.2.1', 'console_scripts', 'pyinstaller')()
  File "/usr/lib/python2.7/site-packages/PyInstaller/__main__.py", line 90, in run
run_build(pyi_config, spec_file, **vars(args))
  File "/usr/lib/python2.7/site-packages/PyInstaller/__main__.py", line 46, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 788, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/build_main.py", line 734, in build
exec(text, spec_namespace)
  File "<string>", line 26, in <module>
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/api.py", line 411, in __init__
self.__postinit__()
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/datastruct.py", line 161, in __postinit__
self.assemble()
  File "/usr/lib/python2.7/site-packages/PyInstaller/building/api.py", line 563, in assemble
self.name)
  File "/usr/lib/python2.7/site-packages/PyInstaller/compat.py", line 486, in exec_command_all
stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
root@mylinkit:/usr#

Body:
I've done some investigation and I believe binutils may be the missing dependency.

apt-get install binutils


问:
Adding league s3 filesystem breaks auto loading
After adding the Leauge S3 filesystem adaptor I receive the following auto loading error on my EBS system.

composer.json

```<code>  "require": {
    "php": ">=5.5.0",
    "slim/slim": "2.3.2",
    "slim/extras": "dev-develop",
    "twig/twig":  "1.*",
    "directus/migrations": "dev-master",
    "directus/permissions": "0.9.*@dev",
    "directus/database": "~0.1.3",
    "league/flysystem": "^1.0",
    "league/flysystem-aws-s3-v3": "^1.0",
    "swiftmailer/swiftmailer": "^5.4"   },
</code>```

Error:

Failed opening required
  '/var/app/current/vendor/composer/../guzzlehttp/psr7/src/functions_include.php'
  (include_path='/var/app/current/vendor/phpunit/php-token-stream:/var/app/current/vendor/phpunit/phpunit-mock-objects:/var/app/current/vendor/phpunit/php-code-coverage:/var/app/current/vendor/phpunit/phpunit:/var/app/current/vendor/symfony/yaml:.:/usr/share/pear7:/usr/share/php7')
  in /var/app/current/vendor/composer/autoload_real.php on line 70

答:
try updating composer with

>composer self-update

You can also clear the cache of composer launching the command:

>composer clear-cache

Hope this help

Body:
After adding the Leauge S3 filesystem adaptor I receive the following auto loading error on my EBS system.

composer.json

  "require": {
    "php": ">=5.5.0",
    "slim/slim": "2.3.2",
    "slim/extras": "dev-develop",
    "twig/twig":  "1.*",
    "directus/migrations": "dev-master",
    "directus/permissions": "0.9.*@dev",
    "directus/database": "~0.1.3",
    "league/flysystem": "^1.0",
    "league/flysystem-aws-s3-v3": "^1.0",
    "swiftmailer/swiftmailer": "^5.4"   },

Error:

Failed opening required
  '/var/app/current/vendor/composer/../guzzlehttp/psr7/src/functions_include.php'
  (include_path='/var/app/current/vendor/phpunit/php-token-stream:/var/app/current/vendor/phpunit/phpunit-mock-objects:/var/app/current/vendor/phpunit/php-code-coverage:/var/app/current/vendor/phpunit/phpunit:/var/app/current/vendor/symfony/yaml:.:/usr/share/pear7:/usr/share/php7')
  in /var/app/current/vendor/composer/autoload_real.php on line 70