问:
416 Error when creating url from a Blob
I'm using the Web Audio API to record a stream of audio source nodes. My code looks like this:

```<code>var context,
    bufferLoader,
    destination,
    mediaRecorder,
    source,
    bufferList,
    chunks = [],
    sound_paths = [],
    audioRecordings = [];

//fill in sound paths
sound_paths = ['sound.mp3', 'sound2.mp3'];

bufferLoader = new BufferLoader(
    context,
    sound_paths,
    callback
);

//fill bufferList with bufferdata
bufferLoader.load();

destination = context.CreateMediaStreamDestination();
mediaRecorder = new MediaRecorder(destination);

mediaRecorder.ondataavailable = function(e){
    chunks.push(e.data);
}

mediaRecorder.onstop = function (e) {
    var blob = new Blob(chunks, {'type': 'audio/ogg; codecs=opus'});
    var audio = document.createElement('audio');
    audio.src = URL.createObjectURL(blob);
    audioRecordings.push(audio);

    chunks = [];
};

function startRecording(){
    mediaRecorder.start();
    source = Recorder.context.createBufferSource();
    source.buffer = bufferList[0];
    source.connect(Recorder.destination);
}

function stopRecording(){
    mediaRecorder.stop();
}

//call startRecording(), then source.start(0) on user input
//call stopRecording(), then source.stop(0) on user input
</code>```

I am using a the BufferLoader as defined here: http://middleearmedia.com/web-audio-api-bufferloader/

This works for the most part, but sometimes I get a 416 (Requested Range Not Satisfiable) when creating a Blob and creating a URL from it. This seems to happen more often when the web page begins to lag. I'm guessing this is because the Blob is undefined when creating the URL, or something like that. Is there a safer way to handle the onstop event for the media recorder? Maybe it would be better to use srcObjet and a MediaStream instead of a Blob?

答:
For my website http://gtube.de (just an example no commercial) i am using recorder.js=>https://github.com/mattdiamond/Recorderjs. It works very good. Perhaps you should give that a try to record the context.

If you load the mp3.s in buffers with the web audio api and play them just at the same time it will devinitely work. => https://www.html5rocks.com/en/tutorials/webaudio/intro/
But thats already the way you do it => The code is missing in your example above so i had to read the article => Perhaps next time you try to make a shorter example.

Sorry i don't know enough about mediaStream API => I suppose it's broken ;-)
If something in web-audio doesn't work just try another way. It is still not very stable => Especially the Mozilla people are  supporting it badly.

Title: 416 Error when creating url from a Blob

Body:
I'm using the Web Audio API to record a stream of audio source nodes. My code looks like this:

var context,
    bufferLoader,
    destination,
    mediaRecorder,
    source,
    bufferList,
    chunks = [],
    sound_paths = [],
    audioRecordings = [];

//fill in sound paths
sound_paths = ['sound.mp3', 'sound2.mp3'];

bufferLoader = new BufferLoader(
    context,
    sound_paths,
    callback
);

//fill bufferList with bufferdata
bufferLoader.load();

destination = context.CreateMediaStreamDestination();
mediaRecorder = new MediaRecorder(destination);

mediaRecorder.ondataavailable = function(e){
    chunks.push(e.data);
}

mediaRecorder.onstop = function (e) {
    var blob = new Blob(chunks, {'type': 'audio/ogg; codecs=opus'});
    var audio = document.createElement('audio');
    audio.src = URL.createObjectURL(blob);
    audioRecordings.push(audio);

    chunks = [];
};

function startRecording(){
    mediaRecorder.start();
    source = Recorder.context.createBufferSource();
    source.buffer = bufferList[0];
    source.connect(Recorder.destination);
}

function stopRecording(){
    mediaRecorder.stop();
}

//call startRecording(), then source.start(0) on user input
//call stopRecording(), then source.stop(0) on user input

I am using a the BufferLoader as defined here: http://middleearmedia.com/web-audio-api-bufferloader/

This works for the most part, but sometimes I get a 416 (Requested Range Not Satisfiable) when creating a Blob and creating a URL from it. This seems to happen more often when the web page begins to lag. I'm guessing this is because the Blob is undefined when creating the URL, or something like that. Is there a safer way to handle the onstop event for the media recorder? Maybe it would be better to use srcObjet and a MediaStream instead of a Blob?


来源: stackexchange

问:
Listening to "esc" key event on div component in Vue.js
I wish to listen to an 'esc' key event in order to call a method in a Vue component.
The docs shows this example:

```<code><input v-on:keyup.enter="submit">
</code>```

but i'm using a

, and need to catch the event from outside.
However, I wish NOT to overload global handlers or anything like that.

Any suggestions?

答:
You can't. Key events are dispatched from the body tag and Vue can't be mounted to the  tag.

]

You'll have to set up your own event listener.

(image source & more info at When VueJS Can't Help You)

ContentLicense: CC BY-SA 3.0

Body:
I wish to listen to an 'esc' key event in order to call a method in a Vue component.
The docs shows this example:

<input v-on:keyup.enter="submit">

but i'm using a

, and need to catch the event from outside.
However, I wish NOT to overload global handlers or anything like that.

Any suggestions?

Body:
You can't. Key events are dispatched from the body tag and Vue can't be mounted to the <body> tag.

]

You'll have to set up your own event listener.

(image source & more info at When VueJS Can't Help You)


问:
How can I get the returned value from the child_process.exec in javascript?
I tried the following code, it shows the res is undefined.
How can I return the stdout?</p>

```<code>function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
}
</code>```

答:
In this case resulting value of the child_process will be in stdout. Why it hasn't worked for you? Also here

```<code>if(err) {
    console.log('shell error:'+stderr);
}
</code>```

why are you checking for err and logging stderr?

Body:
I tried the following code, it shows the res is undefined.
How can I return the stdout?

function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
}

Body:
In this case resulting value of the child_process will be in stdout. Why it hasn't worked for you? Also here

if(err) {
    console.log('shell error:'+stderr);
}

why are you checking for err and logging stderr?


问:
How can I print each value in a list without shortening the list in python?
What I am trying to do is this:

```<code>Str = "yes"
lst = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]
</code>```

I want to be able to print out each item in the list that has a character in Str. So for example I want it to return this:

```<code>["y1", "y2", "y3", "e1", "e2", "e3", "s1", "s2", "s3"]
</code>```

Since that is the order of Str. I have this so far:

```<code>newlst = []
while lst != []:
if Str[0] in text[0]:
    newlst += text[0]
    lst = lst[1:]
    Str = Str[1:]
else:
   lst = lst[1:]
</code>```

My problem is that it only gives me:

```<code>["y1", "y2", "y3"]
</code>```

It's because the list is now []. Is there any way to do this without shortening the list? So keeping it the same but just extracting the values in list that contain Str[n]?

答:
Using list comrehension, I compared with the first item

```<code>[x for item in Str for x in list if x[0] in item]
</code>```

Output :

```<code>['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']
</code>```

Body:
What I am trying to do is this:

Str = "yes"
lst = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]

I want to be able to print out each item in the list that has a character in Str. So for example I want it to return this:

["y1", "y2", "y3", "e1", "e2", "e3", "s1", "s2", "s3"]

Since that is the order of Str. I have this so far:

newlst = []
while lst != []:
if Str[0] in text[0]:
    newlst += text[0]
    lst = lst[1:]
    Str = Str[1:]
else:
   lst = lst[1:]

My problem is that it only gives me:

["y1", "y2", "y3"]

It's because the list is now []. Is there any way to do this without shortening the list? So keeping it the same but just extracting the values in list that contain Str[n]?

Body:
Using list comrehension, I compared with the first item

[x for item in Str for x in list if x[0] in item]

Output :

['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']


问:
Get the identity id's from a batch insert into redshift using python psycopg2 execute_values
I am currently inserting records in batch to a Redshift (Postgres) db.  I am using the psycopg2.extras.execute_values method as from what I have read, this is the fastest way to do it using the below code constructing a list of tuples which contain the data to insert

```<code>    dataList = []
    dataList.append(tuple(data.values()))

    insert_query = "insert into " + tableName + " ( " + insert + ") VALUES %s"

    try:
        psycopg2.extras.execute_values(cur, insert_query, dataList, template=None, page_size=100)
        con.commit()
</code>```

This works fine, however I need to get back the id's from the identity column on the DB.  I have searched to see if this is possible with this method but cannot find a firm answer on whether this is possible with the the execute_values method?

If not, what is the best way to achieve this batch insert and also retrieve the id's?

答:
Use returning and a page_size bigger then the batch size:

```<code>insert_query = "insert into t (c) values %s returning *"
execute_values(cursor, insert_query, data, template=None, page_size=99999)
rows = cursor.fetchall()
</code>```

If the page_size is smaller than the batch size then the cursor content is undefined, probably the last batch.

Body:
I am currently inserting records in batch to a Redshift (Postgres) db.  I am using the psycopg2.extras.execute_values method as from what I have read, this is the fastest way to do it using the below code constructing a list of tuples which contain the data to insert

    dataList = []
    dataList.append(tuple(data.values()))

    insert_query = "insert into " + tableName + " ( " + insert + ") VALUES %s"

    try:
        psycopg2.extras.execute_values(cur, insert_query, dataList, template=None, page_size=100)
        con.commit()

This works fine, however I need to get back the id's from the identity column on the DB.  I have searched to see if this is possible with this method but cannot find a firm answer on whether this is possible with the the execute_values method?

If not, what is the best way to achieve this batch insert and also retrieve the id's?

Body:
Use returning and a page_size bigger then the batch size:

insert_query = "insert into t (c) values %s returning *"
execute_values(cursor, insert_query, data, template=None, page_size=99999)
rows = cursor.fetchall()

If the page_size is smaller than the batch size then the cursor content is undefined, probably the last batch.


问:
Finding the type of an object in C++
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.

What is the best way to find out which type the object passed to my function is?

答:
If you can access boost library, maybe type_id_with_cvr() function is what you need, which can provide data type without removing const, volatile, & and && modifiers. Here is an simple example in C++11:

```<code>#include <iostream>
#include <boost/type_index.hpp>

int a;
int& ff()
{
    return a;
}

int main() {
    ff() = 10;
    using boost::typeindex::type_id_with_cvr;
    std::cout << type_id_with_cvr<int&>().pretty_name() << std::endl;
    std::cout << type_id_with_cvr<decltype(ff())>().pretty_name() << std::endl;
    std::cout << typeid(ff()).name() << std::endl;
}
</code>```

Hope this is useful.

OwnerDisplayName: lemnisca

ContentLicense: CC BY-SA 2.5

Title: Finding the type of an object in C++

Body:
If you can access boost library, maybe type_id_with_cvr() function is what you need, which can provide data type without removing const, volatile, & and && modifiers. Here is an simple example in C++11:

#include <iostream>
#include <boost/type_index.hpp>

int a;
int& ff()
{
    return a;
}

int main() {
    ff() = 10;
    using boost::typeindex::type_id_with_cvr;
    std::cout << type_id_with_cvr<int&>().pretty_name() << std::endl;
    std::cout << type_id_with_cvr<decltype(ff())>().pretty_name() << std::endl;
    std::cout << typeid(ff()).name() << std::endl;
}

Hope this is useful.


问:
File written to createWriteStream gets corrupted when listening to 'data' event on createReadStream in NodeJS
I have an Electron application and I have written a service to copy file using Node's fs module. File copy works fine when not listening to data event of fs.createReadStream, but when I add readStream.on('data', ... event, output file gets corrupted(Output file is always less in size than original file). This is my function code to copy files:

```<code>copyFile(sourcePath: string, targetPath: string): Observable<FileCopyResponseModel> {
        const copyResponse = new Subject<FileCopyResponseModel>();
        const fileSize = this.node.fs.statSync(sourcePath).size;
        const readStream = this.node.fs.createReadStream(sourcePath);
        let bytesCopied = 0;

        readStream.once("error", (err) => {
            const response = new FileCopyResponseModel();
            response.is_error = true;
            response.error = err;
            copyResponse.next(response);
        });

        readStream.on('data', (buffer) => {
            bytesCopied+= buffer.length

            const response = new FileCopyResponseModel();
            response.is_error = false;
            response.is_done = false;
            response.size = fileSize;
            response.size_copied = bytesCopied;
            copyResponse.next(response);
        });

        this.node.mkdirp(this.node.path.dirname(targetPath), (err) => {
            if (err) {
                const response = new FileCopyResponseModel();
                response.is_error = true;
                response.error = err;
                copyResponse.next(response);
            } else {
                const writeStream = this.node.fs.createWriteStream(targetPath);
                writeStream.once("error", (err) => {
                    const response = new FileCopyResponseModel();
                    response.is_error = true;
                    response.error = err;
                    copyResponse.next(response);
                });

                writeStream.once("close", (ex) => {
                    const response = new FileCopyResponseModel();
                    response.is_error = false;
                    response.is_done = true;
                    response.size = fileSize;
                    copyResponse.next(response);
                });

                readStream.pipe(writeStream);
            }
        });

        return copyResponse;
    }
</code>```

File gets copied correctly if I just comment out this section of code:

```<code>readStream.on('data', (buffer) => {
            bytesCopied+= buffer.length

            const response = new FileCopyResponseModel();
            response.is_error = false;
            response.is_done = false;
            response.size = fileSize;
            response.size_copied = bytesCopied;
            copyResponse.next(response);
        });
</code>```

Any idea what is wrong here?

On a Side Note copy progress is being reported correctly when listening to data event.

答:
I think that you are trying to consume the readable stream twice. Once in the on('data', handler and once in readStream.pipe(writeStream);. The on('data', will consume the readable stream before you can pipe it to the write stream.

You could try replacing the line:

```<code>readStream.pipe(writeStream);
</code>```

with

```<code>readStream.on('data', (buffer) => {
     bytesCopied+= buffer.length

     const response = new FileCopyResponseModel();
     response.is_error = false;
     response.is_done = false;
     response.size = fileSize;
     response.size_copied = bytesCopied;
     copyResponse.next(response);
     // new bit
     writeStream.write(buffer);
 });
</code>```

and removing the on('data, from handler from above.

You can also end the writeStream when the read stream ends.

```<code>readStream.on('end', function() {
    console.log('end');
    writeStream.end();
});
</code>```

Body:
I have an Electron application and I have written a service to copy file using Node's fs module. File copy works fine when not listening to data event of fs.createReadStream, but when I add readStream.on('data', ... event, output file gets corrupted(Output file is always less in size than original file). This is my function code to copy files:

copyFile(sourcePath: string, targetPath: string): Observable<FileCopyResponseModel> {
        const copyResponse = new Subject<FileCopyResponseModel>();
        const fileSize = this.node.fs.statSync(sourcePath).size;
        const readStream = this.node.fs.createReadStream(sourcePath);
        let bytesCopied = 0;

        readStream.once("error", (err) => {
            const response = new FileCopyResponseModel();
            response.is_error = true;
            response.error = err;
            copyResponse.next(response);
        });

        readStream.on('data', (buffer) => {
            bytesCopied+= buffer.length

            const response = new FileCopyResponseModel();
            response.is_error = false;
            response.is_done = false;
            response.size = fileSize;
            response.size_copied = bytesCopied;
            copyResponse.next(response);
        });

        this.node.mkdirp(this.node.path.dirname(targetPath), (err) => {
            if (err) {
                const response = new FileCopyResponseModel();
                response.is_error = true;
                response.error = err;
                copyResponse.next(response);
            } else {
                const writeStream = this.node.fs.createWriteStream(targetPath);
                writeStream.once("error", (err) => {
                    const response = new FileCopyResponseModel();
                    response.is_error = true;
                    response.error = err;
                    copyResponse.next(response);
                });

                writeStream.once("close", (ex) => {
                    const response = new FileCopyResponseModel();
                    response.is_error = false;
                    response.is_done = true;
                    response.size = fileSize;
                    copyResponse.next(response);
                });

                readStream.pipe(writeStream);
            }
        });

        return copyResponse;
    }

File gets copied correctly if I just comment out this section of code:

readStream.on('data', (buffer) => {
            bytesCopied+= buffer.length

            const response = new FileCopyResponseModel();
            response.is_error = false;
            response.is_done = false;
            response.size = fileSize;
            response.size_copied = bytesCopied;
            copyResponse.next(response);
        });

Any idea what is wrong here?

On a Side Note copy progress is being reported correctly when listening to data event.

Body:
I think that you are trying to consume the readable stream twice. Once in the on('data', handler and once in readStream.pipe(writeStream);. The on('data', will consume the readable stream before you can pipe it to the write stream.

You could try replacing the line:

readStream.pipe(writeStream);

with

readStream.on('data', (buffer) => {
     bytesCopied+= buffer.length

     const response = new FileCopyResponseModel();
     response.is_error = false;
     response.is_done = false;
     response.size = fileSize;
     response.size_copied = bytesCopied;
     copyResponse.next(response);
     // new bit
     writeStream.write(buffer);
 });

and removing the on('data, from handler from above.

You can also end the writeStream when the read stream ends.

readStream.on('end', function() {
    console.log('end');
    writeStream.end();
});


问:
How to add node labels to Bounded Force Layout (D3 v4)?
Latest code attempt:

```<code> var node = svg.selectAll("circle")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("r", radius - .75)
      .style("fill", function(d) { return fill(d.group); })
      .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
      .call(force.drag);

  var label = svg.selectAll("text")
    .data(graph.nodes)
    .enter()
    .append("text")
    .text(function(d){return d.id; });
    .style("text-anchor", "middle")
    .attr("font-family", "sans-serif")
    .attr("font-size", "11px")
    .attr("fill", "red");
 })

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .on("tick", tick)
      .start();

  function tick() {
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); });

    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    label.attr("x", function(d){ return d.x; })
          .attr("y", function (d) {return d.y });
</code>```

Hi Everyone,

I am a newbie to D3 and have spent almost two days on this problem so far to no avail!

I am trying to add node labels to a version of https://bl.ocks.org/mbostock/1129492

I've copy/pasted snippets of code from every forum response I can find and it either breaks my diagram (empty screen on execution) or has no effect (lots of pretty colored circles but no labels).  I have been able to add labels to another force diagram successfully but that one was not bounded, and bounding is a key feature I'd like to have.  At this stage I have not made any changes to the graph.json file Bostock put up.  I am simply trying to get it to display the node text labels.

Can someone please tell me what code I need to write to get labels to show, and where and how to to insert it?  I'm determined to not give up on this one!

Here's my code:

<!DOCTYPE html>
<meta charset="utf-8">

```

答:
I have modified the example from Mike Bostock to include labels for each node by doing the following:

The label for each node is in graph.nodes so first we create a
selection labels and perform a typical d3 data-join to add text
elements and set the label-text.

The positioning of the labels occurs in the tick() function. On
each step of the animation, we set the x and y attribute of the
text element according to the x and y value of the graph.node
element.

Please note that this example uses d3 v3 so there will be some changes to the syntax - primarily the names used for scale etc. More details can be found here.

I have not attempted to position the text to avoid overlapping. This is reasonably involved and discussed elsewhere like this other SO post.

var width = 960,
    height = 500,
    radius = 6;

var fill = d3.scale.category20();

var force = d3.layout.force()
    .gravity(.05)
    .charge(-240)
    .linkDistance(50)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("https://gist.githubusercontent.com/mbostock/1129492/raw/9513c3fe193673a09e161d49d00a587fd806bdf5/graph.json", function(error, graph) {
  if (error) throw error;

  var link = svg.selectAll("line")
      .data(graph.links)
    .enter().append("line");

  var node = svg.selectAll("circle")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("r", radius - .75)
      .style("fill", function(d) { return fill(d.group); })
      .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
      .call(force.drag);

  var labels = svg.selectAll("text")
      .data(graph.nodes)
    .enter().append('text')
      .text(function (d){return d.name});

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .on("tick", tick)
      .start();

  function tick() {
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); });

    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    labels.attr('x', function(d) { return d.x; })
          .attr('y', function(d) { return d.y; });
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>circle {
  stroke-width: 1.5px;
}
line {
  stroke: #999;
}</code>```

```

Body:
Latest code attempt:

 var node = svg.selectAll("circle")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("r", radius - .75)
      .style("fill", function(d) { return fill(d.group); })
      .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
      .call(force.drag);

  var label = svg.selectAll("text")
    .data(graph.nodes)
    .enter()
    .append("text")
    .text(function(d){return d.id; });
    .style("text-anchor", "middle")
    .attr("font-family", "sans-serif")
    .attr("font-size", "11px")
    .attr("fill", "red");
 })

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .on("tick", tick)
      .start();

  function tick() {
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); });

    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    label.attr("x", function(d){ return d.x; })
          .attr("y", function (d) {return d.y });

Hi Everyone,

I am a newbie to D3 and have spent almost two days on this problem so far to no avail!

I am trying to add node labels to a version of https://bl.ocks.org/mbostock/1129492

I've copy/pasted snippets of code from every forum response I can find and it either breaks my diagram (empty screen on execution) or has no effect (lots of pretty colored circles but no labels).  I have been able to add labels to another force diagram successfully but that one was not bounded, and bounding is a key feature I'd like to have.  At this stage I have not made any changes to the graph.json file Bostock put up.  I am simply trying to get it to display the node text labels.

Can someone please tell me what code I need to write to get labels to show, and where and how to to insert it?  I'm determined to not give up on this one!

Here's my code:

<!DOCTYPE html>
<meta charset="utf-8">

Body:
I have modified the example from Mike Bostock to include labels for each node by doing the following:

The label for each node is in graph.nodes so first we create a
selection labels and perform a typical d3 data-join to add text
elements and set the label-text.

The positioning of the labels occurs in the tick() function. On
each step of the animation, we set the x and y attribute of the
text element according to the x and y value of the graph.node
element.

Please note that this example uses d3 v3 so there will be some changes to the syntax - primarily the names used for scale etc. More details can be found here.

I have not attempted to position the text to avoid overlapping. This is reasonably involved and discussed elsewhere like this other SO post.

var width = 960,
    height = 500,
    radius = 6;

var fill = d3.scale.category20();

var force = d3.layout.force()
    .gravity(.05)
    .charge(-240)
    .linkDistance(50)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("https://gist.githubusercontent.com/mbostock/1129492/raw/9513c3fe193673a09e161d49d00a587fd806bdf5/graph.json", function(error, graph) {
  if (error) throw error;

  var link = svg.selectAll("line")
      .data(graph.links)
    .enter().append("line");

  var node = svg.selectAll("circle")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("r", radius - .75)
      .style("fill", function(d) { return fill(d.group); })
      .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
      .call(force.drag);

  var labels = svg.selectAll("text")
      .data(graph.nodes)
    .enter().append('text')
      .text(function (d){return d.name});

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .on("tick", tick)
      .start();

  function tick() {
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); });

    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    labels.attr('x', function(d) { return d.x; })
          .attr('y', function(d) { return d.y; });
  }
});

circle {
  stroke-width: 1.5px;
}
line {
  stroke: #999;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


问:
window.location.href.split('/').pop() returning special characters instead of actual value
I have the following url:

```<code>gr-dev.indegene.com/el-gr/ο-πόνος/τι-είναι-ο-πόνος;
</code>```

The problem is when i do:

```<code>window.location.href.split('/').pop()
</code>```

I get a bunch of special characters , such as the below:

```<code>"%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;"
</code>```

I just want to get τι-είναι-ο-πόνος instead of the above , how do i do that ?

答:
Use the below code.

```<code>window.decodeURI(window.location.href.split('/').pop());
</code>```

Please refer to decodeURI

 var decodedVal = window.decodeURI("%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;");

 console.log(decodedVal);```

Body:
I have the following url:

gr-dev.indegene.com/el-gr/ο-πόνος/τι-είναι-ο-πόνος;

The problem is when i do:

window.location.href.split('/').pop()

I get a bunch of special characters , such as the below:

"%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;"

I just want to get τι-είναι-ο-πόνος instead of the above , how do i do that ?

Body:
Use the below code.

window.decodeURI(window.location.href.split('/').pop());

Please refer to decodeURI

 var decodedVal = window.decodeURI("%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;");

 console.log(decodedVal);


问:
How to show country wise price InApp Purchase V3?
In my android app, I am showing the price of purchase products on my custom buttons. I want to show those prices according to the country for eg. if the app opens at Indian price should be in INR, if it opens at US price should be in USD etc.

I tried

```<code>private void getSkuDetails(Inventory inventory) {

        for (int i = 0; i < myData.INAPP_SKUS.length; i++) {

            SkuDetails skuDetails = inventory.getSkuDetails(myData.INAPP_SKUS[i]);

            if (skuDetails != null) {
                System.out.println(">>>> Price::::" + skuDetails.getPrice());
                System.out.println(">>>> Type::::" + skuDetails.toString());
            } else {
                System.out.println(">>>>> It is null.....");
            }
        }
    }
</code>```

but always skuDetails comes null for every SKU.

I have also published my app in play store and test this. but still, I am getting null skuDetail.

So, How to display these In-App products price according to the country?

答:
first,make sure you can make a purchase in your app.
second,you can try to clear your google play sotre cache.

the getSkuDetails API will return the correct price and currency depends on user's ip or credit card country.
if you don't config wrong,you won't get the null result.

Body:
In my android app, I am showing the price of purchase products on my custom buttons. I want to show those prices according to the country for eg. if the app opens at Indian price should be in INR, if it opens at US price should be in USD etc.

I tried

private void getSkuDetails(Inventory inventory) {

        for (int i = 0; i < myData.INAPP_SKUS.length; i++) {

            SkuDetails skuDetails = inventory.getSkuDetails(myData.INAPP_SKUS[i]);

            if (skuDetails != null) {
                System.out.println(">>>> Price::::" + skuDetails.getPrice());
                System.out.println(">>>> Type::::" + skuDetails.toString());
            } else {
                System.out.println(">>>>> It is null.....");
            }
        }
    }

but always skuDetails comes null for every SKU.

I have also published my app in play store and test this. but still, I am getting null skuDetail.

So, How to display these In-App products price according to the country?


问:
Pandas : Replace values multiple times until the end
I have a pandas df like this:

```<code>import pandas as pd
df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})
</code>```

It is cumulative data from sales.
There is a bug in the data : Some observations are wrong.
(No value can be greater than the previous one : i.e., 8500 and 8666 are not correct)
I want to replace these values with the previous one.

I tried this

```<code>df['above'] = df.sales.shift(1)
df.loc[df.above < df.sales, 'sales'] = df.above
</code>```

But this code works only one time, how to extend this code to replace all values until the end of the series (with the previous one) ?

The desired result should looks like :

答:
How about this?

```<code>df.loc[df['sales'] > 200] = 10
</code>```

ref: https://stackoverflow.com/a/38467449/4772042

'200' is the proper value I caught. Change it to the desired value.

Body:
I have a pandas df like this:

import pandas as pd
df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]})

It is cumulative data from sales.
There is a bug in the data : Some observations are wrong.
(No value can be greater than the previous one : i.e., 8500 and 8666 are not correct)
I want to replace these values with the previous one.

I tried this

df['above'] = df.sales.shift(1)
df.loc[df.above < df.sales, 'sales'] = df.above

But this code works only one time, how to extend this code to replace all values until the end of the series (with the previous one) ?

The desired result should looks like :

Body:
How about this?

df.loc[df['sales'] > 200] = 10

ref: https://stackoverflow.com/a/38467449/4772042

'200' is the proper value I caught. Change it to the desired value.


问:
Unable to center content of a div
I'm creating a table with divs. I'm able to create it, but there is this instance where in there is a row where I need to do a merge and center.

Here is my code.

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
    <div class="divTableRow">
      <div class="divTableCell"> 6</div>
    </div>
  </div>
</div></code>```

Here I want 6 to be in center. How can I achieve this?

basically like below table

```<code><table border="1px solid black">
  <tr>
    <td>$2</td>
    <td>1</td>
  </tr>
  <tr>
    <td colspan="2" align="center">6</td>
  </tr>
</table>
</code>```

答:
Try this</p>

```<code>.divTableRow{
width:100%;
display:flex;
justify-content:center;
}
</code>```

Title: Unable to center content of a div

Body:
I'm creating a table with divs. I'm able to create it, but there is this instance where in there is a row where I need to do a merge and center.

Here is my code.

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}

$2

1

 6

Here I want 6 to be in center. How can I achieve this?

basically like below table

    $2
    1

    6

Body:
Try this

.divTableRow{
width:100%;
display:flex;
justify-content:center;
}


问:
How to declare style in propTypes?
With the forbid-prop-types rule enabled, eslint forbids me from using style: React.PropTypes.object, and using shape is suggested.

But is it really necessary to define all the available properties there for this purpose like this?

```<code>DEMO.propTypes = {
    style: React.PropTypes.shape({
        color: React.PropTypes.string,
        fontSize: React.PropTypes.number,
        ...
    })
};
</code>```

Too much definition code!

答:
React Native now contains ViewPropTypes, which will replace View.propTypes.style. Example of usage:

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

MyComponent.propTypes = {
  style: ViewPropTypes.style
};
</code>```

Title: How to declare style in propTypes?

Body:
With the forbid-prop-types rule enabled, eslint forbids me from using style: React.PropTypes.object, and using shape is suggested.

But is it really necessary to define all the available properties there for this purpose like this?

DEMO.propTypes = {
    style: React.PropTypes.shape({
        color: React.PropTypes.string,
        fontSize: React.PropTypes.number,
        ...
    })
};

Too much definition code!

Body:
React Native now contains ViewPropTypes, which will replace View.propTypes.style. Example of usage:

import { ViewPropTypes } from 'react-native';

MyComponent.propTypes = {
  style: ViewPropTypes.style
};


问:
How to configure Openlayers for a flat 1:1 pixel coordinate system?
I'm trying to build a map for the game Guild Wars 2, but having trouble getting openlayers to handle the coordinate system correctly and render the map completely.

Here's a fiddle of what I have: https://jsfiddle.net/ndqb8rqx/

The Guild Wars world is square and 49152 pixels on both axes. The origin ([0, 0]) of the coordinates should be the north-west. The south-east should be [49152, 49152]. The developer of the game makes the tiles for the map available as a service: https://wiki.guildwars2.com/wiki/API:Tile_service

I created a Projection based on Zoomify to try to handle this:

```<code>var gw2Projection = new ol.proj.Projection({
  code: 'ZOOMIFY',
  units: 'pixels',
  extent: [0, -49152, 49152, 0]
})
</code>```

And I also added the game tiles as a Tilelayer from an XYZ source, like this:

```<code>new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
    projection: gw2Projection
  }),
}),
</code>```

The first problem is that openlayers doesn't render the complete map. The map actually extends further south and east than the fiddle shows. The bottom right edge which is actually shown in the fiddle is really [32768, 32768], but the map extends out to [49152, 49152]. It seems that openlayers simply shrinks the coordinate system to the area of a single tile when zoomed completely out. Instead I would like the coordinates to match 1:1 with the pixels.

The other problem is that currently the y-coordinate increase in the northern direction. I would like to invert the y-axis, such that the y-coordinates increase in the southern direction.

答:
The key to making this work is a custom tile grid definition, i.e. with the correct extent and maxZoom:

```<code>var tilegrid = new ol.tilegrid.createXYZ({
  extent: gw2Projection.getExtent(),
  maxZoom: 7
});
</code>```

Then configure the XYZ source with that tilegrid:

```<code>source: new ol.source.XYZ({
  url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
  projection: gw2Projection,
  tileGrid: tilegrid
})
</code>```

Also configure the view with the resolutions of that tilegrid:

```<code>view: new ol.View({
  center: ol.extent.getCenter(gw2Projection.getExtent()),
  extent: gw2Projection.getExtent(),
  zoom: 1,
  resolutions: tilegrid.getResolutions()
}
</code>```

I have created an updated fiddle that makes your map work: https://jsfiddle.net/kay99yor/.

Body:
I'm trying to build a map for the game Guild Wars 2, but having trouble getting openlayers to handle the coordinate system correctly and render the map completely.

Here's a fiddle of what I have: https://jsfiddle.net/ndqb8rqx/

The Guild Wars world is square and 49152 pixels on both axes. The origin ([0, 0]) of the coordinates should be the north-west. The south-east should be [49152, 49152]. The developer of the game makes the tiles for the map available as a service: https://wiki.guildwars2.com/wiki/API:Tile_service

I created a Projection based on Zoomify to try to handle this:

var gw2Projection = new ol.proj.Projection({
  code: 'ZOOMIFY',
  units: 'pixels',
  extent: [0, -49152, 49152, 0]
})

And I also added the game tiles as a Tilelayer from an XYZ source, like this:

new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
    projection: gw2Projection
  }),
}),

The first problem is that openlayers doesn't render the complete map. The map actually extends further south and east than the fiddle shows. The bottom right edge which is actually shown in the fiddle is really [32768, 32768], but the map extends out to [49152, 49152]. It seems that openlayers simply shrinks the coordinate system to the area of a single tile when zoomed completely out. Instead I would like the coordinates to match 1:1 with the pixels.

The other problem is that currently the y-coordinate increase in the northern direction. I would like to invert the y-axis, such that the y-coordinates increase in the southern direction.

Body:
The key to making this work is a custom tile grid definition, i.e. with the correct extent and maxZoom:

var tilegrid = new ol.tilegrid.createXYZ({
  extent: gw2Projection.getExtent(),
  maxZoom: 7
});

Then configure the XYZ source with that tilegrid:

source: new ol.source.XYZ({
  url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
  projection: gw2Projection,
  tileGrid: tilegrid
})

Also configure the view with the resolutions of that tilegrid:

view: new ol.View({
  center: ol.extent.getCenter(gw2Projection.getExtent()),
  extent: gw2Projection.getExtent(),
  zoom: 1,
  resolutions: tilegrid.getResolutions()
}

I have created an updated fiddle that makes your map work: https://jsfiddle.net/kay99yor/.


问:
Solve issue with nested keys in JSON
I am trying to adapt some python code from an awesome guide for dark web scanning/graph creation.

I have thousands of json files created with Onionscan, and I have this code that should wrap everything in a gephi graph. Unfortunately, this code is old, as the Json files are now formatted differently and this code does not work anymore:

code (partial):

```<code>import glob
import json
import networkx
import shodan

file_list = glob.glob("C:\\test\\*.json")
graph = networkx.DiGraph()

for json_file in file_list:
    with open(json_file,"rb") as fd:
        scan_result = json.load(fd)
        edges = []
        if scan_result('linkedOnions') is not None:
            edges.extend(scan_result['linkedOnions'])
</code>```

In fact, at this point I get "KeyError", because linkedOnions is one-level nested like this:

```<code>"identifierReport": {
 "privateKeyDetected": false,
  "foundApacheModStatus": false,
  "serverVersion": "",
  "relatedOnionServices": null,
  "relatedOnionDomains": null,
  "linkedOnions": [many urls here]
</code>```

could you please help me fix the code above?

I would be VERY grateful :)

Lorenzo

答:
this is the correct way to read nested JSON.

```<code>if scan_result['identifierReport']['linkedOnions'] is not None:
            edges.extend(scan_result'identifierReport']['linkedOnions'])
</code>```

Try this it will work for you if your JSON file is correct format

```<code>try:
   scan_result = json.load(fd)
   edges = []
   if scan_result('linkedOnions') is not None:
      edges.extend(scan_result['linkedOnions'])
except Exception,e:
     #print your message or log
     print e
</code>```

Title: Solve issue with nested keys in JSON

Body:
I am trying to adapt some python code from an awesome guide for dark web scanning/graph creation.

I have thousands of json files created with Onionscan, and I have this code that should wrap everything in a gephi graph. Unfortunately, this code is old, as the Json files are now formatted differently and this code does not work anymore:

code (partial):

import glob
import json
import networkx
import shodan

file_list = glob.glob("C:\\test\\*.json")
graph = networkx.DiGraph()

for json_file in file_list:
    with open(json_file,"rb") as fd:
        scan_result = json.load(fd)
        edges = []
        if scan_result('linkedOnions') is not None:
            edges.extend(scan_result['linkedOnions'])

In fact, at this point I get "KeyError", because linkedOnions is one-level nested like this:

"identifierReport": {
 "privateKeyDetected": false,
  "foundApacheModStatus": false,
  "serverVersion": "",
  "relatedOnionServices": null,
  "relatedOnionDomains": null,
  "linkedOnions": [many urls here]

could you please help me fix the code above?

I would be VERY grateful :)

Lorenzo

Body:
this is the correct way to read nested JSON.

if scan_result['identifierReport']['linkedOnions'] is not None:
            edges.extend(scan_result'identifierReport']['linkedOnions'])

Try this it will work for you if your JSON file is correct format

try:
   scan_result = json.load(fd)
   edges = []
   if scan_result('linkedOnions') is not None:
      edges.extend(scan_result['linkedOnions'])
except Exception,e:
     #print your message or log
     print e


问:
Wrap H1-H6 Tags with Typo3 ParseFunc depending on the class set in RTE
I want to add inline-svgs to my h1 to h6 Tags depending on the class set in the RTE.

Example:
RTE:

```<code><h1 class="icon--clock">Header</h1>
</code>```

Output:

```<code><h1 class="icon--clock"><svg>...</svg>Header</h1>
</code>```

I've done something similar with links before, using the parseFunc Config. A method like this: https://wiki.typo3.org/External_links

Is there any way to access and split the tag and class like the link parameters through TypoScript?

I also tried using a userFunc

```<code>lib.parseFunc.userFunc = ...\MyClass->MyUserFunc
</code>```

but in Params I only get the tag content, not the tag or the classes that have been set themselves.

I'm using Typo8 with the ckeditor, but I don't think that makes a difference.

Can I even do this?
How do I do this?

I know that I can alternatively add different header layouts and use the tt_content header field, because it's easier to manipulate the template there. But I'd love to know if there is a way to this in the RTE.

答:
I think you could do it in typoscript, but that would be very complicated as you need to analyze the attributes of the Hn-tags.

A simpler method which came to mind would be: use CSS and ::before. So you can use a selector to the class to insert the matching SVG.

This also can be done with javascript but as CSS can do it it would be more efficient to use CSS.

Body:
I want to add inline-svgs to my h1 to h6 Tags depending on the class set in the RTE.

Example:
RTE:

Header

Output:

<svg>...</svg>Header

I've done something similar with links before, using the parseFunc Config. A method like this: https://wiki.typo3.org/External_links

Is there any way to access and split the tag and class like the link parameters through TypoScript?

I also tried using a userFunc

lib.parseFunc.userFunc = ...\MyClass->MyUserFunc

but in Params I only get the tag content, not the tag or the classes that have been set themselves.

I'm using Typo8 with the ckeditor, but I don't think that makes a difference.

Can I even do this?
How do I do this?

I know that I can alternatively add different header layouts and use the tt_content header field, because it's easier to manipulate the template there. But I'd love to know if there is a way to this in the RTE.


问:
php and sql. Can't echo the query
I'm running into a problem while doing Homework

```<code> <form class="" action="" method="post">
 <div class="form-group">
 <input type="text" name="datebegin" value="">
    <button type="submit" name="submit" value="submit" class="btn btn-warning">Reprot</button>
 <table class="table table-striped" class="problem1">
    <?php
    Display();
    ?>
   </table>
</code>```

This's form function.php

```<code><?php
function Display(){
global $conn;
global $datebegin;
if(isset($_POST['submit'])){
$datebegin = $_POST['datebegin'];
print($datebegin);
}
$query="SELECT Guest_name FROM form WHERE datediff($datebegin,datein) = '0'";
<tr>
<th>Guest name</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row['Guest_name'] . "</td>/tr>";
}
?>
</code>```

From my database

```<code>  Guest_name   |  datein
  David        |  2017-12-04
</code>```

when i input the value '2017-12-04'
the print($datebegin) display 2017-12-04
but echo Guest_name won't display David
Thanks you for your time.

答:
```<code><?php

function Display(){
global $conn;
global $datebegin;
if(isset($_POST['submit'])){
    $datebegin = $_POST['datebegin'];
    print($datebegin);
}
$query="SELECT Guest_name FROM form WHERE datediff($datebegin,$datein) = '0'";
?>
<tr>
<th>Guest name</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
    echo "<tr><td>" .$row['Guest_name']. "</td></tr>";
}
?>
</code>```

Try this, you did not close your php tag before you used html. I hope this solves the error for you and also fixed some more mistakes in your code. But for sure this is not the full code as i can't see where your query is executed and where your $datein variable is coming from inside your datediff function.  Also datediff is used in SELECT and expects 2 string parameters so probably your query is also wrong.

Title: php and sql. Can't echo the query

Body:
I'm running into a problem while doing Homework

 <form class="" action="" method="post">

 <input type="text" name="datebegin" value="">
    <button type="submit" name="submit" value="submit" class="btn btn-warning">Reprot</button>

    <?php
    Display();
    ?>

This's form function.php

<?php
function Display(){
global $conn;
global $datebegin;
if(isset($_POST['submit'])){
$datebegin = $_POST['datebegin'];
print($datebegin);
}
$query="SELECT Guest_name FROM form WHERE datediff($datebegin,datein) = '0'";

Guest name

<?php
while($row = mysqli_fetch_array($result)) {
echo "
" . $row['Guest_name'] . "	/tr>";
}
?>

From my database

  Guest_name   |  datein
  David        |  2017-12-04

when i input the value '2017-12-04'
the print($datebegin) display 2017-12-04
but echo Guest_name won't display David
Thanks you for your time.

Body:
<?php

function Display(){
global $conn;
global $datebegin;
if(isset($_POST['submit'])){
    $datebegin = $_POST['datebegin'];
    print($datebegin);
}
$query="SELECT Guest_name FROM form WHERE datediff($datebegin,$datein) = '0'";
?>
<tr>
<th>Guest name</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
    echo "<tr><td>" .$row['Guest_name']. "</td></tr>";
}
?>

Try this, you did not close your php tag before you used html. I hope this solves the error for you and also fixed some more mistakes in your code. But for sure this is not the full code as i can't see where your query is executed and where your $datein variable is coming from inside your datediff function.  Also datediff is used in SELECT and expects 2 string parameters so probably your query is also wrong.


问:
Does Azure ML have dplyr package of R preinstalled?
Does Azure ML have the dplyr package installed? If not how to install dplyr package in Azure Ml studio. Kindly help.  </p>

答:
Both packages should be preinstalled, and simply loading the packages with library("package-name") should do it.

Link: https://msdn.microsoft.com/en-us/library/mt741980.aspx

When you load a package, do you get an error?


问:
Postgresql: How to group items based on their percentage to the grandtotal
```<code>    store_id   product_name   quantity
       1          apple          10
       1          orange         12
       1          grapes          9
       1          mango          17
       2          chicken        112
       2          beef           90
       2          pork           89
       2          lamb           115
</code>```

I want to group them from top and bottom 50% based on the percentage of their grandtotal grouped by their store_id, and label the bottom product as 'others'
something that looks like this:

```<code>     store_id    product_name    percent
        1           mango         35.42%
        1           orange        25.00%
        1           OTHER         20.83%
        1           OTHER         18.75%
        2           lamb          28.33%
        2           chicken       27.59%
        2           OTHER         22.17%
        2           OTHER         21.92%
</code>```

Is this possible? I really had a hard time google-ing this that's why I came here. Thanks!

答:
assuming tablename as gt, then:</p>

```<code>t=# with a as (select *,round( quantity * 100.0 / sum(quantity) over(partition by store_id), 2) r from gt)
,b as (select *, sum(r) over (partition by store_id order by r desc) from a)
select store_id, case when coalesce(lag(sum) over (partition by store_id) < 50 ,true) then product_name else 'OTHER' end product_name, r||'%' percent from b;
 store_id | product_name | percent
----------+--------------+---------
        1 | mango        | 35.42%
        1 | orange       | 25.00%
        1 | OTHER        | 20.83%
        1 | OTHER        | 18.75%
        2 | lamb         | 28.33%
        2 | chicken      | 27.59%
        2 | OTHER        | 22.17%
        2 | OTHER        | 21.92%
(8 rows)
</code>```

Body:
    store_id   product_name   quantity
       1          apple          10
       1          orange         12
       1          grapes          9
       1          mango          17
       2          chicken        112
       2          beef           90
       2          pork           89
       2          lamb           115

I want to group them from top and bottom 50% based on the percentage of their grandtotal grouped by their store_id, and label the bottom product as 'others'
something that looks like this:

     store_id    product_name    percent
        1           mango         35.42%
        1           orange        25.00%
        1           OTHER         20.83%
        1           OTHER         18.75%
        2           lamb          28.33%
        2           chicken       27.59%
        2           OTHER         22.17%
        2           OTHER         21.92%

Is this possible? I really had a hard time google-ing this that's why I came here. Thanks!

Body:
assuming tablename as gt, then:

t=# with a as (select *,round( quantity * 100.0 / sum(quantity) over(partition by store_id), 2) r from gt)
,b as (select *, sum(r) over (partition by store_id order by r desc) from a)
select store_id, case when coalesce(lag(sum) over (partition by store_id) < 50 ,true) then product_name else 'OTHER' end product_name, r||'%' percent from b;
 store_id | product_name | percent
----------+--------------+---------
        1 | mango        | 35.42%
        1 | orange       | 25.00%
        1 | OTHER        | 20.83%
        1 | OTHER        | 18.75%
        2 | lamb         | 28.33%
        2 | chicken      | 27.59%
        2 | OTHER        | 22.17%
        2 | OTHER        | 21.92%
(8 rows)


问:
How to change backGround color in Xamarin forms NavigationPage
I'm trying to change the background color of navigationBar in navigationPage I'm using this code:

```<code>using System;
using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
namespace P
{
public class App : Application
{
    public App ()
    {
 MainPage = new NavigationPage(new LoginPage());
    }
    protected override void OnStart ()
    {
    }
    protected override void OnSleep ()
    {
    }
    protected override void OnResume ()
    {
        // Handle when your app resumes
    }
   }
  }
</code>```

how can I do it?

答:
If you want to change the NavigationBar BackgroundColor on each page with a different color. You can do the following on the Codebehinds of each page/view.

```<code>using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace NewApp.Cross.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewView : ContentPage
    {
        public NewView()
        {
            InitializeComponent();
            Title = "PageTitle"

            NavigationPage.SetHasBackButton(this, false);

            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            ((NavigationPage)Application.Current.MainPage).BarTextColor = Color.OrangeRed;
        }
    }
}
</code>```

It works on Android and iOS.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to change the background color of navigationBar in navigationPage I'm using this code:

using System;
using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
namespace P
{
public class App : Application
{
    public App ()
    {
 MainPage = new NavigationPage(new LoginPage());
    }
    protected override void OnStart ()
    {
    }
    protected override void OnSleep ()
    {
    }
    protected override void OnResume ()
    {
        // Handle when your app resumes
    }
   }
  }

how can I do it?

Body:
If you want to change the NavigationBar BackgroundColor on each page with a different color. You can do the following on the Codebehinds of each page/view.

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace NewApp.Cross.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewView : ContentPage
    {
        public NewView()
        {
            InitializeComponent();
            Title = "PageTitle"

            NavigationPage.SetHasBackButton(this, false);

            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            ((NavigationPage)Application.Current.MainPage).BarTextColor = Color.OrangeRed;
        }
    }
}

It works on Android and iOS.


问:
How do I exclude a specific row in Laravel?
I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

```<code>$finalNews = News::find(DB::table('news')->max('id'));
</code>```

But than I have another variable which return all the rows from News table with the following code

```<code>$news = News::orderBy('id','desc')->get();
</code>```

I want to exclude the news row which is equal to $finalNews
at the end of controller I return view with following data

```<code>return view('news', ['news' => $news, 'finalNews' => $finalNews]);
</code>```

How can I exclude the last news? I am using Laravel and MySQL.

答:
First, get all news

```<code>$news = News::orderBy('id','desc')->get();
</code>```

Then, pop the last item (the lastest news) out of $news

```<code>$latest_news = $news->pop();
</code>```

https://laravel.com/docs/5.5/collections#method-pop

There is no need to use 2 queries in this case

Body:
I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

$finalNews = News::find(DB::table('news')->max('id'));

But than I have another variable which return all the rows from News table with the following code

$news = News::orderBy('id','desc')->get();

I want to exclude the news row which is equal to $finalNews
at the end of controller I return view with following data

return view('news', ['news' => $news, 'finalNews' => $finalNews]);

How can I exclude the last news? I am using Laravel and MySQL.

Body:
First, get all news

$news = News::orderBy('id','desc')->get();

Then, pop the last item (the lastest news) out of $news

$latest_news = $news->pop();

https://laravel.com/docs/5.5/collections#method-pop

There is no need to use 2 queries in this case


问:
Java - Search and Delete an object from Arraylist
so I have class Customer and class Bank , a bank class has methods of adding Customer to an arraylist of Customers , and also must have a method to search a Customer in an arraylist and delete it (Remove from arraylist) , How can I do it?

Bank class -

```<code>private ArrayList<Customer> customers = new ArrayList<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.add(customer);
    System.out.println("new customer " + customer.getName() + " added");
}

public void deleteAccount(String name){

}
</code>```

Customer class -

```<code>private String name;
private double balance;

public Customer(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer " +
            "name :'" + name + '\'' +
            '}';
}
</code>```

Main -

```<code>public static void deleteAccount(){
    System.out.println("Enter the name you want to delete");
    String name = scanner.nextLine();
    scanner.nextLine();
    bank.deleteAccount(name);
}
</code>```

As you can see, the main class has method which takes input type String from user and then calles Bank class's method of deleteAccount with that input , but I don't know how to proceed with the deleteAccount method, how to make it work ?

I need something that firstly checks if the user input is in the Arraylist, and then remove it from there if there is.

I do realize that input is String and Arraylist is Customer instances , but Customer only takes String name in constractor, so can I make it work this way?

答:
Iterate over the list and check if the supplied name is equal to the name retrieved from customer in the list , if yes then delete it.</p>

```<code>public void deleteAccount(String name){

      Iterator<Customer> itr=  customers.iterator();
      while(itr.hasNext()){

          String cuName = itr.next().getName();
          if(cuName.equalsIgnoreCase(name)){
              //delete it from list
              //break out of loop
              itr.remove();
              break;
          }
      }

    }
</code>```

Body:
so I have class Customer and class Bank , a bank class has methods of adding Customer to an arraylist of Customers , and also must have a method to search a Customer in an arraylist and delete it (Remove from arraylist) , How can I do it?

Bank class -

private ArrayList<Customer> customers = new ArrayList<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.add(customer);
    System.out.println("new customer " + customer.getName() + " added");
}

public void deleteAccount(String name){

}

Customer class -

private String name;
private double balance;

public Customer(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer " +
            "name :'" + name + '\'' +
            '}';
}

Main -

public static void deleteAccount(){
    System.out.println("Enter the name you want to delete");
    String name = scanner.nextLine();
    scanner.nextLine();
    bank.deleteAccount(name);
}

As you can see, the main class has method which takes input type String from user and then calles Bank class's method of deleteAccount with that input , but I don't know how to proceed with the deleteAccount method, how to make it work ?

I need something that firstly checks if the user input is in the Arraylist, and then remove it from there if there is.

I do realize that input is String and Arraylist is Customer instances , but Customer only takes String name in constractor, so can I make it work this way?

Body:
Iterate over the list and check if the supplied name is equal to the name retrieved from customer in the list , if yes then delete it.

public void deleteAccount(String name){

      Iterator<Customer> itr=  customers.iterator();
      while(itr.hasNext()){

          String cuName = itr.next().getName();
          if(cuName.equalsIgnoreCase(name)){
              //delete it from list
              //break out of loop
              itr.remove();
              break;
          }
      }

    }


问:
Delphi SQL return with multidimensional array
i created a type

```<code>type
  TStringArray = array of array of string;

function TDataModule4.GetList(TableName: String): TStringArray;
var
  i : Integer;
begin
  i:= 0;
  with TFDQuery.Create(Nil) do
  begin
    Connection := ADConnectionMySQL;
    SQL.Add(Format('Select * from %s', [TableName]));
    Open;
    First;
    while not Eof do
    begin

    end;
    Free;
  end;
end;
</code>```

I know get data using FieldByName, but i want to return all data in multidimensional array. How can i do this?

Here is how i want  to return :

array[0]["column1"] = "value1"

array[0]["column2"] = "value2"

array[1]["column1"] = "value3"

array[1]["column2"] = "value4"

array[2]["column1"] = "value5"

array[2]["column2"] = "value6"

答:
I did not use Delphi for a while and I never used TFD- Query, but as far as I remember this was no Problem. I wanted to write it to a comment, but sourcecode is better readable in an answer (untested).
I introduced Q for the Name of your Query for better understanding and A for the array to be filled with data.

```<code>//var
A:TStringArray;
actLine, actCol:integer;

setlength(A,0);
actLine := 0;

while not Q.eof() do begin

  setlength(A,actLine + 1);
  setlength(A[actLine],FieldCount());

  for actCol := 0 to Q.FieldCount()-1 do
    A[actLine][actCol] := Q.Fields[actCol].AsString;

  inc(actLine);
  Q.Next;
end;
</code>```

I hope, this helps you.

of course: array of array produces a 2 dimensional array with columns and lines numbered. Only the Content is string. A structure you describe you should implement yourself.

Body:
i created a type

type
  TStringArray = array of array of string;

function TDataModule4.GetList(TableName: String): TStringArray;
var
  i : Integer;
begin
  i:= 0;
  with TFDQuery.Create(Nil) do
  begin
    Connection := ADConnectionMySQL;
    SQL.Add(Format('Select * from %s', [TableName]));
    Open;
    First;
    while not Eof do
    begin

    end;
    Free;
  end;
end;

I know get data using FieldByName, but i want to return all data in multidimensional array. How can i do this?

Here is how i want  to return :

array[0]["column1"] = "value1"

array[0]["column2"] = "value2"

array[1]["column1"] = "value3"

array[1]["column2"] = "value4"

array[2]["column1"] = "value5"

array[2]["column2"] = "value6"

Body:
I did not use Delphi for a while and I never used TFD- Query, but as far as I remember this was no Problem. I wanted to write it to a comment, but sourcecode is better readable in an answer (untested).
I introduced Q for the Name of your Query for better understanding and A for the array to be filled with data.

//var
A:TStringArray;
actLine, actCol:integer;

setlength(A,0);
actLine := 0;

while not Q.eof() do begin

  setlength(A,actLine + 1);
  setlength(A[actLine],FieldCount());

  for actCol := 0 to Q.FieldCount()-1 do
    A[actLine][actCol] := Q.Fields[actCol].AsString;

  inc(actLine);
  Q.Next;
end;

I hope, this helps you.

of course: array of array produces a 2 dimensional array with columns and lines numbered. Only the Content is string. A structure you describe you should implement yourself.


问:
Using ISSET with checkboxes
I am working on a wordpress search form to refine the current search and what Im trying to do is have the search results page with the search from and it's values set based on the query.

So far I've been successful in doing so with single select drop downs and single checkboxes like so --

```<code><!-- SINGLE SELECT -->
    <select name="baths" class="form-control">
    <?php if (isset($_GET['baths'])) {
        $bths = $_GET['baths']; ?>
    <option value="<?php echo $bths; ?>"><?php echo $bths; ?></option>
    <?php } else { ?>
    <option value="Any">Any</option>
    <?php } ?>
    <option value="Any">Any</option>
    <option value="1">1+</option>
    <option value="2">2+</option>
    <option value="3">3+</option>
    <option value="4">4+</option>
    <option value="5">5+</option>
    <option value="6">6+</option>
    <option value="7">7+</option>
    <option value="8">8+</option>
    <option value="9">9+</option>
    <option value="10">10+</option>
    </select>

<!-- SINGLE CHECKBOX -->
<input type="checkbox" name="dogs" class="styled" value ="yes" <?php if (isset($_GET['dogs'])) { ?>checked<?php } ?>>
</code>```

That works, but for the multiple values it doesn't. This is my function to generate a set of checkboxes to select amenities -

```<code><?php
$amenity_array = array();
$id            = get_query_var('site');
if (!empty($id)) {
  $property_amenities = get_post_meta($id, 'imic_property_amenities', true);
  global $imic_options;
  foreach ($property_amenities as $properties_amenities_temp) {
    if ($properties_amenities_temp != 'Not Selected') {
      array_push($amenity_array, $properties_amenities_temp);
    }
  }
}
global $imic_options;
if (isset($imic_options['properties_amenities']) && count($imic_options['properties_amenities']) > 1) {
  foreach ($imic_options['properties_amenities'] as $properties_amenities) {
    $am_name = strtolower(str_replace(' ', '', $properties_amenities));
    $check   = '';
    if (in_array($properties_amenities, $amenity_array)) {
      $check = 'checked="checked"';
    }

<!-- HERE I TRY TO FIND THE SELECTED CHECKBOXES AND CHECK THEM OFF -->
    if (isset($_GET['p_am'])) {
      $ams = $_GET['p_am'];

      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    } else {
      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    }
<!-- END ISSET -->

  }
} else {
  _e('There is no Properties Amenities', 'framework');
}
?>
</code>```

For the multi select drop down I am using bootstrap multiselect, so on my template the  code looks like this --

```<code><select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
 $terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
 $count = count($terms);
 if ( $count > 0  ){
   echo "<option value='Any'>All</option>";
   foreach ( $terms as $term ) {
     echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
   }
 }
?>
</select>
</code>```

On the page it renders out as ---

```<code><select name="property_type[]" id="pt-multi" class="form-control multi-select2 iOSselect" multiple="multiple" style="display: none;">
  <option value="Any">All</option>
  <option value="co-op">Co-Op</option>
  <option value="condo">Condo</option>
</select>

<div class="btn-group" style="width: 100%;">
  <button type="button" class="multiselect dropdown-toggle btn btn-default form-control multi-select2" data-toggle="dropdown" title="Property Type" style="width: 100%; overflow: hidden; text-overflow: ellipsis;">
  <span class="multiselect-selected-text">Property Type</span>
  <b class="caret"></b></button>
  <ul class="multiselect-container dropdown-menu pull-right">
    <li class="multiselect-item multiselect-all">
      <a tabindex="0" class="multiselect-all">
        <label class="checkbox"><input type="checkbox" value="multiselect-all">  Select all</label>
      </a>
    </li>
    <li>
      <a tabindex="0"><label class="checkbox">
        <input type="checkbox" value="Any"> All</label>
      </a>
    </li>
    <li>
      <a tabindex="0"><label class="checkbox"><input type="checkbox" value="co-op"> Co-Op</label>
      </a>
    </li>
    <li>
      <a tabindex="0"><label class="checkbox"><input type="checkbox" value="condo"> Condo</label>
      </a>
    </li>
  </ul>
</div>
</code>```

Any ideas?

UPDATE

Using my code from above my amenities checkbox renders out on the page like so ---

```<code><div>
  <label>amenities</label>
  <div class="checkbox">
    <input type="checkbox" name="p_am" class="styled" value="Doorman (Full Time)">
    <label for="doorman(fulltime)">Doorman (Full Time)</label>
  </div>

  <div class="checkbox">
    <input type="checkbox" name="p_am" class="styled" value="Doorman (Part Time)"><label for="doorman(parttime)">Doorman (Part Time)</label>
  </div>

  <div class="checkbox">
    <input type="checkbox" name="p_am" class="styled" value="Laundry (In-Unit)"><label for="laundry(in-unit)">Laundry (In-Unit)</label>
  </div>

  <div class="checkbox">
    <input type="checkbox" name="p_am" class="styled" value="Fitness Center"><label for="fitnesscenter">Fitness Center</label>
  </div>
</div>
</code>```

This works with my search function allowing users to check off which amenities to include in the query string --

```<code>p_am=Doorman+%28Full+Time%29&p_am=Indoor+Pool
</code>```

My search function is extensive but as far the relevant parts to the amenities -

```<code>$amenities = isset($_GET['p_am'])?$_GET['p_am']:'';
$amenities = ($amenities == __('Any', 'framework')) ? '' : $amenities;

// .....

if (!empty($amenities)) {
  array_push($meta_query,array(
    'key' => 'imic_property_amenities',
    'value' => $amenities,
    'compare'=>'LIKE'
  ));
}
</code>```

UPDATE

In regards to setting the dropdown options for the bootstrap multiselect, I'm trying to set the options using the following code -

```<code><?php

$taxonomyName = "city-type";

$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );

echo "<select name='property_nhb[]' class='form-control multi-select' id='p-nhb' multiple>";

foreach ( $parent_terms as $pterm ) {
 // echo "<option data-val='" . $pterm->slug . "' value='Any' " . $selected . ">Any</option>";
    //Get the Child terms
    $terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {

if(isset($_GET['property_nhb[]'])) {
$pnhb = $_GET['property_nhb'];

$selected = 'selected';

}

        echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' " . $selected . " >" . $term->name . "</option>";
    }
}
echo "</select>";
?>
</code>```

My current search function code

答:
This seems a little backwards for creating a search form - it seems more like you're generating a form for each individual result? Annotated code and comments below. I've tried to keep to your coding style in my answer.

```<code>$amenity_array = array();
$id            = get_query_var('site');
// this first section gets the selected meta properties for the queried property (if available)
// [skipping for brevity ]
global $imic_options;
if (isset($imic_options['properties_amenities']) && count($imic_options['properties_amenities']) > 1) {
  // this loops over all of the globally defined properties
  foreach ($imic_options['properties_amenities'] as $properties_amenities) {
    // gets the name of the property
    $am_name = strtolower(str_replace(' ', '', $properties_amenities));
    // and sets up to check the box if the property has the defined amenity
    // if this is for a search form, why check boxes based on a result?
    $check   = '';
    if (in_array($properties_amenities, $amenity_array)) {
      // note: this only really needs to be 'checked'
      $check = 'checked="checked"';
    }
</code>```

Here's where things go a little cross-purposes, though.

```<code>    if (isset($_GET['p_am'])) {
      $ams = $_GET['p_am'];

      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    } else {
      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    }
</code>```

This says that all checkboxes have the same name ("p_am") instead of using the loop name for the amenity ($am_name) or some form combination if you want all amenities in the same search input array (e.g. "p_am[$am_name]").

Each checkbox would also change the value of $check if supplied to the $_GET array.

```<code>      $ams = $_GET['p_am'];
      if (isset($ams[$am_name])) {
        $check = 'checked';
      }
</code>```

Each checkbox would have name="p_am['.$am_name.']" as the name.

```<code>      echo '<div class="checkbox"><input type="checkbox" name="p_am[' . $am_name . ']" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
</code>```

If you want each of the amenities to have unique names (looking at the original checkbox which isn't called p_am at all) and not be in an array in PHP, then you would just use the loop name for the amenity ($am_name), like so:

```<code>      if (isset($_GET[$am_name])) {
        $check = 'checked';
      }
</code>```

Each checkbox would have name="'.$am_name.'" as the name.

UPDATE: after the OP was updated, it looks like every checkbox needs to have the same name, but not be keyed values. For this situation, your checkboxes should be called p_am[] (on both search page an original page), and you need to use something like in_array() instead of isset() to check the result, like so:

```<code>      if (in_array($properties_amenities, $_GET['p_am'])) {
        $check = 'checked';
      }
</code>```

Additional note - you're also using $am_name for the label, without actually setting the id attribute on the checkbox to match to, as well as not stripping out non-id characters (like parentheses), so the label association won't work.

```<code>      echo '<div class="checkbox"><input type="checkbox" name="' . $am_name . '" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
</code>```

For the bootstrap select, you're just missing a check for which options are selected:

```<code><select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0  ){
  echo "<option value='Any'>All</option>";
  foreach ( $terms as $term ) {
    // if the option is 'checked', you need to add the 'selected' atttibute here
    echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
  }
}
?>
</select>
</code>```

So the inside of the loop would look something like this instead:

```<code>    // for efficiency's sake should live outside the loop as a one-off, but here for illustrative purposes
    $types = $_GET['property_type'];
    $selected = isset($types[$term->slug]) ? 'selected' : '';
    echo "<option value='" . $term->slug . "'" . $selected . ">" . $term->name . "</option>";
</code>```

If you're using an older version of bootstrap select, you may need to have the selected string be 'selected="selected" or data-selected="true", depending on the version you're using. For a current version, the above string should be fine.

If the <select> isn't meant to be an array of options either (i.e. not multiple), then the [] should be removed from the name, and would operate similarly to the checkbox code:

```<code><select name="property_type" id="pt-multi" class="form-control multi-select2">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0  ){
  echo "<option value='Any'>All</option>";
  foreach ( $terms as $term ) {
    $type = $_GET['property_type'];
    $selected = isset($type) && $type == $term-slug ? 'selected' : '';
    echo "<option value='" . $term->slug . "'" . $selected . ">" . $term->name . "</option>";
  }
}
?>
</select>
</code>```

The original HTML for the <select> doesn't actually 'work' as such either - all it's doing is adding a duplicate <option> to the top of the options list, and because nothing is selected, the form will treat the duplicate created at the top as 'selected' for the <select>.

UPDATE 2: the reason that the search function is breaking with an array of checkbox inputs is because you are using the LIKE comparison for your meta query. From the documentation on WordPress Meta Query:

It can be an array only when compare is 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN'.

The documentation also shows examples of how to join these together. Since you haven't supplied how you're actually making the search query this is guessing a little, but it looks like for an array of checkboxes your code should be something similar to:

```<code>    if (isset($_GET['p_am'])) {
      $ams = $_GET['p_am'];

      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    } else {
      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    }
</code>```0

As with the examples in the documentation, you'll need to make sure there's a relation => 'OR' or relation => 'AND' to define how you want your search to operate.

Title: Using ISSET with checkboxes

Body:
I am working on a wordpress search form to refine the current search and what Im trying to do is have the search results page with the search from and it's values set based on the query.

So far I've been successful in doing so with single select drop downs and single checkboxes like so --

    <select name="baths" class="form-control">
    <?php if (isset($_GET['baths'])) {
        $bths = $_GET['baths']; ?>
    <option value="<?php echo $bths; ?>"><?php echo $bths; ?></option>
    <?php } else { ?>
    <option value="Any">Any</option>
    <?php } ?>
    <option value="Any">Any</option>
    <option value="1">1+</option>
    <option value="2">2+</option>
    <option value="3">3+</option>
    <option value="4">4+</option>
    <option value="5">5+</option>
    <option value="6">6+</option>
    <option value="7">7+</option>
    <option value="8">8+</option>
    <option value="9">9+</option>
    <option value="10">10+</option>
    </select>

<input type="checkbox" name="dogs" class="styled" value ="yes" <?php if (isset($_GET['dogs'])) { ?>checked<?php } ?>>

That works, but for the multiple values it doesn't. This is my function to generate a set of checkboxes to select amenities -

<?php
$amenity_array = array();
$id            = get_query_var('site');
if (!empty($id)) {
  $property_amenities = get_post_meta($id, 'imic_property_amenities', true);
  global $imic_options;
  foreach ($property_amenities as $properties_amenities_temp) {
    if ($properties_amenities_temp != 'Not Selected') {
      array_push($amenity_array, $properties_amenities_temp);
    }
  }
}
global $imic_options;
if (isset($imic_options['properties_amenities']) && count($imic_options['properties_amenities']) > 1) {
  foreach ($imic_options['properties_amenities'] as $properties_amenities) {
    $am_name = strtolower(str_replace(' ', '', $properties_amenities));
    $check   = '';
    if (in_array($properties_amenities, $amenity_array)) {
      $check = 'checked="checked"';
    }

    if (isset($_GET['p_am'])) {
      $ams = $_GET['p_am'];

      echo '
<input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '">' . $properties_amenities . '
';
    } else {
      echo '
<input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '">' . $properties_amenities . '
';
    }

  }
} else {
  _e('There is no Properties Amenities', 'framework');
}
?>

For the multi select drop down I am using bootstrap multiselect, so on my template the  code looks like this --

<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
 $terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
 $count = count($terms);
 if ( $count > 0  ){
   echo "<option value='Any'>All</option>";
   foreach ( $terms as $term ) {
     echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
   }
 }
?>
</select>

On the page it renders out as ---

<select name="property_type[]" id="pt-multi" class="form-control multi-select2 iOSselect" multiple="multiple" style="display: none;">
  <option value="Any">All</option>
  <option value="co-op">Co-Op</option>
  <option value="condo">Condo</option>
</select>

  <button type="button" class="multiselect dropdown-toggle btn btn-default form-control multi-select2" data-toggle="dropdown" title="Property Type" style="width: 100%; overflow: hidden; text-overflow: ellipsis;">
  Property Type
  </button>

        <input type="checkbox" value="multiselect-all">  Select all

        <input type="checkbox" value="Any"> All

      <input type="checkbox" value="co-op"> Co-Op

      <input type="checkbox" value="condo"> Condo

Any ideas?

UPDATE

Using my code from above my amenities checkbox renders out on the page like so ---

  amenities

    <input type="checkbox" name="p_am" class="styled" value="Doorman (Full Time)">
    Doorman (Full Time)

    <input type="checkbox" name="p_am" class="styled" value="Doorman (Part Time)">Doorman (Part Time)

    <input type="checkbox" name="p_am" class="styled" value="Laundry (In-Unit)">Laundry (In-Unit)

    <input type="checkbox" name="p_am" class="styled" value="Fitness Center">Fitness Center

This works with my search function allowing users to check off which amenities to include in the query string --

p_am=Doorman+%28Full+Time%29&p_am=Indoor+Pool

My search function is extensive but as far the relevant parts to the amenities -

$amenities = isset($_GET['p_am'])?$_GET['p_am']:'';
$amenities = ($amenities == __('Any', 'framework')) ? '' : $amenities;

// .....

if (!empty($amenities)) {
  array_push($meta_query,array(
    'key' => 'imic_property_amenities',
    'value' => $amenities,
    'compare'=>'LIKE'
  ));
}

UPDATE

In regards to setting the dropdown options for the bootstrap multiselect, I'm trying to set the options using the following code -

<?php

$taxonomyName = "city-type";

$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );

echo "<select name='property_nhb[]' class='form-control multi-select' id='p-nhb' multiple>";

foreach ( $parent_terms as $pterm ) {
 // echo "<option data-val='" . $pterm->slug . "' value='Any' " . $selected . ">Any</option>";
    //Get the Child terms
    $terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {

if(isset($_GET['property_nhb[]'])) {
$pnhb = $_GET['property_nhb'];

$selected = 'selected';

}

        echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' " . $selected . " >" . $term->name . "</option>";
    }
}
echo "</select>";
?>

My current search function code

Body:
This seems a little backwards for creating a search form - it seems more like you're generating a form for each individual result? Annotated code and comments below. I've tried to keep to your coding style in my answer.

$amenity_array = array();
$id            = get_query_var('site');
// this first section gets the selected meta properties for the queried property (if available)
// [skipping for brevity ]
global $imic_options;
if (isset($imic_options['properties_amenities']) && count($imic_options['properties_amenities']) > 1) {
  // this loops over all of the globally defined properties
  foreach ($imic_options['properties_amenities'] as $properties_amenities) {
    // gets the name of the property
    $am_name = strtolower(str_replace(' ', '', $properties_amenities));
    // and sets up to check the box if the property has the defined amenity
    // if this is for a search form, why check boxes based on a result?
    $check   = '';
    if (in_array($properties_amenities, $amenity_array)) {
      // note: this only really needs to be 'checked'
      $check = 'checked="checked"';
    }

Here's where things go a little cross-purposes, though.

    if (isset($_GET['p_am'])) {
      $ams = $_GET['p_am'];

      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    } else {
      echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
    }

This says that all checkboxes have the same name ("p_am") instead of using the loop name for the amenity ($am_name) or some form combination if you want all amenities in the same search input array (e.g. "p_am[$am_name]").

Each checkbox would also change the value of $check if supplied to the $_GET array.

      $ams = $_GET['p_am'];
      if (isset($ams[$am_name])) {
        $check = 'checked';
      }

Each checkbox would have name="p_am['.$am_name.']" as the name.

      echo '<div class="checkbox"><input type="checkbox" name="p_am[' . $am_name . ']" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';

If you want each of the amenities to have unique names (looking at the original checkbox which isn't called p_am at all) and not be in an array in PHP, then you would just use the loop name for the amenity ($am_name), like so:

      if (isset($_GET[$am_name])) {
        $check = 'checked';
      }

Each checkbox would have name="'.$am_name.'" as the name.

UPDATE: after the OP was updated, it looks like every checkbox needs to have the same name, but not be keyed values. For this situation, your checkboxes should be called p_am[] (on both search page an original page), and you need to use something like in_array() instead of isset() to check the result, like so:

      if (in_array($properties_amenities, $_GET['p_am'])) {
        $check = 'checked';
      }

Additional note - you're also using $am_name for the label, without actually setting the id attribute on the checkbox to match to, as well as not stripping out non-id characters (like parentheses), so the label association won't work.

      echo '<div class="checkbox"><input type="checkbox" name="' . $am_name . '" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';

For the bootstrap select, you're just missing a check for which options are selected:

<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0  ){
  echo "<option value='Any'>All</option>";
  foreach ( $terms as $term ) {
    // if the option is 'checked', you need to add the 'selected' atttibute here
    echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
  }
}
?>
</select>

So the inside of the loop would look something like this instead:

    // for efficiency's sake should live outside the loop as a one-off, but here for illustrative purposes
    $types = $_GET['property_type'];
    $selected = isset($types[$term->slug]) ? 'selected' : '';
    echo "<option value='" . $term->slug . "'" . $selected . ">" . $term->name . "</option>";

If you're using an older version of bootstrap select, you may need to have the selected string be 'selected="selected" or data-selected="true", depending on the version you're using. For a current version, the above string should be fine.

If the <select> isn't meant to be an array of options either (i.e. not multiple), then the [] should be removed from the name, and would operate similarly to the checkbox code:

<select name="property_type" id="pt-multi" class="form-control multi-select2">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0  ){
  echo "<option value='Any'>All</option>";
  foreach ( $terms as $term ) {
    $type = $_GET['property_type'];
    $selected = isset($type) && $type == $term-slug ? 'selected' : '';
    echo "<option value='" . $term->slug . "'" . $selected . ">" . $term->name . "</option>";
  }
}
?>
</select>

The original HTML for the <select> doesn't actually 'work' as such either - all it's doing is adding a duplicate <option> to the top of the options list, and because nothing is selected, the form will treat the duplicate created at the top as 'selected' for the <select>.

UPDATE 2: the reason that the search function is breaking with an array of checkbox inputs is because you are using the LIKE comparison for your meta query. From the documentation on WordPress Meta Query:

It can be an array only when compare is 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN'.

The documentation also shows examples of how to join these together. Since you haven't supplied how you're actually making the search query this is guessing a little, but it looks like for an array of checkboxes your code should be something similar to:

if (!empty($amenities)) {
  foreach ($amenities as $amenity) {
    array_push($meta_query, array(
      'key' => 'imic_property_amenities',
      'value' => $amenity,
      'compare' => 'LIKE'
    ));
  }
}

As with the examples in the documentation, you'll need to make sure there's a relation => 'OR' or relation => 'AND' to define how you want your search to operate.


问:
Get info from JSON data and store into CSV file
I am able to get Name,Info and Points( all the data present inside this is coming in as whole data).
Here is the sample input data:

```<code>data : [[{'Info':'http:\/\/www.epa.gov\/enviro\/geo_data.html', 'Name':'US RCRA Generators (CESQG, SQG, LQG)', 'Color':[
240, 180, 120 ], 'Points':[
{
'Direction':'1.64069406001901', 'Description':'SRID=4326;POINT(-111.74632     33.29791)', 'Fields':[
{
'Value':'COSTCO #644', 'Key':'Primary Name' }, {
'Value':'2887 S MARKET ST', 'Key':'Address' }, {
'Value':'GILBERT', 'Key':'City' }, {
'Value':'MARICOPA', 'Key':'County' }, {
'Value':'ONE-HOUR PHOTOFINISHING., OTHER GASOLINE STATIONS.', 'Key':'NAICS     Descriptions' } ], 'Longitude':'-111.74632', 'Latitude':'33.29791',     'Type':'ST_Point' } ]]]
</code>```

Here is what I tried:

```<code>info_list = []
name_list = []
points_list = []
lat_list = []
long_list = []
for ff in finalJson:
    for gg in ff:
        info = gg['Info']
        name = gg['Name']
        points = gg['Points']
        info_list.append(info)
        name_list.append(name)
        points_list.append(points)
</code>```

But need to get the key value data in the csv(quoted things as column name and values as rows with their respective) :  'Name','Info','Points'['Latitude'],'Points'['Longitude'],'Points'['Fields'[all the key,values of this inside block]]

Any help would be appreciated.

答:
Why not use json_normalize?

It does a pretty good job of flattening the object into a pandas dataframe:

```<code>from pandas.io.json import json_normalize
df = json_normalize(json_data['data'])
print(df.head())
</code>```

Then clean/restructure the dataframe, at last export it to CSV using to_csv.

```<code>df.to_csv('/path/output.csv', encoding='utf-8')
</code>```

Edit: Splitting 'Points' column into multiple columns.

```<code>df2 = df.groupby('Info').Points.apply(lambda x: pd.DataFrame(x.values[0])).reset_index()
final_df = pd.concat([df, df2])
print(final_df)
</code>```

Body:
I am able to get Name,Info and Points( all the data present inside this is coming in as whole data).
Here is the sample input data:

data : [[{'Info':'http:\/\/www.epa.gov\/enviro\/geo_data.html', 'Name':'US RCRA Generators (CESQG, SQG, LQG)', 'Color':[
240, 180, 120 ], 'Points':[
{
'Direction':'1.64069406001901', 'Description':'SRID=4326;POINT(-111.74632     33.29791)', 'Fields':[
{
'Value':'COSTCO #644', 'Key':'Primary Name' }, {
'Value':'2887 S MARKET ST', 'Key':'Address' }, {
'Value':'GILBERT', 'Key':'City' }, {
'Value':'MARICOPA', 'Key':'County' }, {
'Value':'ONE-HOUR PHOTOFINISHING., OTHER GASOLINE STATIONS.', 'Key':'NAICS     Descriptions' } ], 'Longitude':'-111.74632', 'Latitude':'33.29791',     'Type':'ST_Point' } ]]]

Here is what I tried:

info_list = []
name_list = []
points_list = []
lat_list = []
long_list = []
for ff in finalJson:
    for gg in ff:
        info = gg['Info']
        name = gg['Name']
        points = gg['Points']
        info_list.append(info)
        name_list.append(name)
        points_list.append(points)

But need to get the key value data in the csv(quoted things as column name and values as rows with their respective) :  'Name','Info','Points'['Latitude'],'Points'['Longitude'],'Points'['Fields'[all the key,values of this inside block]]

Any help would be appreciated.

Body:
Why not use json_normalize?

It does a pretty good job of flattening the object into a pandas dataframe:

from pandas.io.json import json_normalize
df = json_normalize(json_data['data'])
print(df.head())

Then clean/restructure the dataframe, at last export it to CSV using to_csv.

df.to_csv('/path/output.csv', encoding='utf-8')

Edit: Splitting 'Points' column into multiple columns.

df2 = df.groupby('Info').Points.apply(lambda x: pd.DataFrame(x.values[0])).reset_index()
final_df = pd.concat([df, df2])
print(final_df)