问:
Frequency count for Comma delimited categories within a column
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

```<code>Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
</code>```

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

答:
A solution using tidyverse. dt_final is the final output.

```<code>library(tidyverse)

# Separate the comma
dt2 <- dt %>% separate_rows(Make)

# Calculate the frequency
dt3 <- dt2 %>% count(Zip, Make)

# Prepare the Frequency column
dt4 <- dt3 %>%
  mutate(n = paste0("(", n, ")")) %>%
  unite(Frequency, Make, n, sep = " ") %>%
  group_by(Zip) %>%
  summarise(Frequency = paste0(Frequency, collapse = ", "))

# Prepare the Top 3 Make column
dt5 <- dt3 %>%
  group_by(Zip) %>%
  mutate(Rank = dense_rank(n)) %>%
  filter(Rank <= 3) %>%
  arrange(Zip, Rank, Make) %>%
  select(Zip, Make) %>%
  summarise(`Top 3 Make (per frequency)` = paste0(Make, collapse = ", "))

# Join the results
dt_final <- reduce(list(dt, dt4, dt5), left_join, by = "Zip")

dt_final
#     Zip                                                                       Make
# 1 12325                                Toyota, Honda, Toyota, Mitsubishi, Mercedes
# 2 85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
# 3 56098  Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
#                                                         Frequency
# 1             Honda (1), Mercedes (1), Mitsubishi (1), Toyota (2)
# 2                    Honda (2), Nissan (4), Toyota (4), Volvo (1)
# 3 Acura (1), Chevrolet (3), Honda (2), Mitsubishi (1), Toyota (2)
#                    Top 3 Make (per frequency)
# 1         Honda, Mercedes, Mitsubishi, Toyota
# 2                Volvo, Honda, Nissan, Toyota
# 3 Acura, Mitsubishi, Honda, Toyota, Chevrolet
</code>```

DATA

```<code>dt <- read.table(text = "Zip                   Make
12325 'Toyota, Honda, Toyota, Mitsubishi, Mercedes'
                 85271 'Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan'
                 56098 'Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda'",
                 header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

Body:
A solution using tidyverse. dt_final is the final output.

library(tidyverse)

# Separate the comma
dt2 <- dt %>% separate_rows(Make)

# Calculate the frequency
dt3 <- dt2 %>% count(Zip, Make)

# Prepare the Frequency column
dt4 <- dt3 %>%
  mutate(n = paste0("(", n, ")")) %>%
  unite(Frequency, Make, n, sep = " ") %>%
  group_by(Zip) %>%
  summarise(Frequency = paste0(Frequency, collapse = ", "))

# Prepare the Top 3 Make column
dt5 <- dt3 %>%
  group_by(Zip) %>%
  mutate(Rank = dense_rank(n)) %>%
  filter(Rank <= 3) %>%
  arrange(Zip, Rank, Make) %>%
  select(Zip, Make) %>%
  summarise(`Top 3 Make (per frequency)` = paste0(Make, collapse = ", "))

# Join the results
dt_final <- reduce(list(dt, dt4, dt5), left_join, by = "Zip")

dt_final
#     Zip                                                                       Make
# 1 12325                                Toyota, Honda, Toyota, Mitsubishi, Mercedes
# 2 85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
# 3 56098  Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
#                                                         Frequency
# 1             Honda (1), Mercedes (1), Mitsubishi (1), Toyota (2)
# 2                    Honda (2), Nissan (4), Toyota (4), Volvo (1)
# 3 Acura (1), Chevrolet (3), Honda (2), Mitsubishi (1), Toyota (2)
#                    Top 3 Make (per frequency)
# 1         Honda, Mercedes, Mitsubishi, Toyota
# 2                Volvo, Honda, Nissan, Toyota
# 3 Acura, Mitsubishi, Honda, Toyota, Chevrolet

DATA

dt <- read.table(text = "Zip                   Make
12325 'Toyota, Honda, Toyota, Mitsubishi, Mercedes'
                 85271 'Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan'
                 56098 'Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda'",
                 header = TRUE, stringsAsFactors = FALSE)


来源: stackexchange

问:
How to pass array as variable outside the wp_query loop in php
Is there a way to pass an array as a variable out of the wp_query loop? I want to collect post meta from the four posts — next week and the following three weeks. To keep the code clean, I thought it'd be easiest to capture the variable and use the data later in the form.

```<code>// Capture next week's week number
$nextweek = date("W", strtotime( "+1 week"));

// Query all custom post types
$menu_args = array(
    'post_type'=>'single_menu',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC'
    );

    $menu = new WP_Query( $menu_args ); if ( $menu->have_posts() ) : while ( $menu->have_posts() ) : $menu->the_post();

    // Get custom fields
    $menuids = array( get_post_field( 'week', $post->id ) );
    $titles = array( get_post( $post->id )->post_title );
    $choosefrom = array( get_post_field( 'menu_listing', $post->id ) );
    $selection = array( get_post_field( $checkout_menu, $post->id ) );

    // Create new array with custom fields
    $result = array();
    foreach ( $menuids as $id => $menuid ) {
        $result[$menuid] = array(
            'title'  => $titles[$id],
            'offering'  => $choosefrom[$id],
            'menu' => $selection[$id],
            'delivery'    => 0,
        );
    }

    // Return the arrays for specified weeks
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {
        print_r( $result );
    }
    }

    endwhile;
    endif;
</code>```

print_r() returns the correct results, my $results array for the next four weeks. However, when I create a variable and call it outside the loop, like below, I only get the last/fourth $result in the array:

```<code>    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload = $result;
    }
  }

endwhile;
endif;

print_r( $payload );
</code>```

Same thing happens when I create a new array like so:

```<code>    $payload = array();
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload[] = $result;
    }
  }

endwhile;
endif;

print_r( $payload );
</code>```

If I concatenate the variable like $payload .= $result;, I get ArrayArrayArrayArray returned.

I know I can echo the form inside loop, but would rather take the array as a data variable if at all possible. Am I missing something easy?

答: Sometimes we can't see straight ... $payload = array(); needed to be placed outside of the wp_query, before $menu_args.

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to pass an array as a variable out of the wp_query loop? I want to collect post meta from the four posts — next week and the following three weeks. To keep the code clean, I thought it'd be easiest to capture the variable and use the data later in the form.

// Capture next week's week number
$nextweek = date("W", strtotime( "+1 week"));

// Query all custom post types
$menu_args = array(
    'post_type'=>'single_menu',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC'
    );

    $menu = new WP_Query( $menu_args ); if ( $menu->have_posts() ) : while ( $menu->have_posts() ) : $menu->the_post();

    // Get custom fields
    $menuids = array( get_post_field( 'week', $post->id ) );
    $titles = array( get_post( $post->id )->post_title );
    $choosefrom = array( get_post_field( 'menu_listing', $post->id ) );
    $selection = array( get_post_field( $checkout_menu, $post->id ) );

    // Create new array with custom fields
    $result = array();
    foreach ( $menuids as $id => $menuid ) {
        $result[$menuid] = array(
            'title'  => $titles[$id],
            'offering'  => $choosefrom[$id],
            'menu' => $selection[$id],
            'delivery'    => 0,
        );
    }

    // Return the arrays for specified weeks
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {
        print_r( $result );
    }
    }

    endwhile;
    endif;

print_r() returns the correct results, my $results array for the next four weeks. However, when I create a variable and call it outside the loop, like below, I only get the last/fourth $result in the array:

    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload = $result;
    }
  }

endwhile;
endif;

print_r( $payload );

Same thing happens when I create a new array like so:

    $payload = array();
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload[] = $result;
    }
  }

endwhile;
endif;

print_r( $payload );

If I concatenate the variable like $payload .= $result;, I get ArrayArrayArrayArray returned.

I know I can echo the form inside loop, but would rather take the array as a data variable if at all possible. Am I missing something easy?


问:
Make an API call inside of another API call?
I basically need to combine data from two different API calls. Here is what I have right now:

```<code>    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('<tr><td>'+api[i].thing+'</td></tr>');
            }
        }
    });
</code>```

The above works.

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('
+api[i].thing+'
');

答:
```<code>const getDataFromApi = (endpoint) => {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            type: "GET",
            dataType: 'json',
            headers: {'X-API-Key': 'xxxxxx'},
            success: (data) => {
                return resolve(data);
            }
        });
    });
};

Promise.all([
    return getDataFromApi('https://website.com/api.json');
]).then((data) => {
    return Promise.all([
        data,
        getDataFromApi('https://website.com/api2.json')
    ]);
    // here your business logic (for loop in your code)
}).then((data) => { // with bluebird it's easier use spread
    const dataApi1 = data[0];
    const dataApi2 = data[1];
})
.catch((err) => {
    console.error(err);
});
</code>```

Body:
I basically need to combine data from two different API calls. Here is what I have right now:

    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('
'+api[i].thing+'
');
            }
        }
    });

The above works.

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('
+api[i].thing+'
');


问:
Shifting Extended ASCII codes
When assigning Extended ASCII codes to an unsigned char, I noticed that the values are shifted upwards when they are written to a file.

I condensed my code into this simple program to briefly present my question:

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

int main()
{
    unsigned char testascii[3];

    testascii[0] = 122;
    testascii[1] = 150;
    testascii[2] = 175;

    printf("%d\n", testascii[0]);
    printf("%d\n", testascii[1]);
    printf("%d\n", testascii[2]);

    return 0;
}
</code>```

If I run this simple program, I get this terminal output:

```<code>122
150
175
</code>```

This is correct.

If I now add the following to the above program:

```<code>FILE *f;
f = fopen("/mystuff/testascii", "wb");
if (f == NULL)
{
  printf("Error opening file\n");
  exit(1);
}
fwrite(testascii, 1, 3, f);
fclose(f);
</code>```

It runs correctly but if I now go to the O/S and run:

```<code>od -c testascii
</code>```

I get this output:

```<code>0000000   z 226 257
0000003
</code>```

As you can see the Standard ASCII code (below 128) is correctly shown; however the Extended ASCII codes (above 127) are changed. I expect them to be 150 and 175 but they are 226 and 257.

If I remove the binary flag from the file open command, the result is still the same.

As a final check, instead of the binary print (fwrite), I changed the code again and looped through the array and did a fprintf of each item like this:

```<code>fprintf (fp, "%d", appendtxt[i]);
</code>```

Here's the OD display for that:

```<code>0000000   1   2   2   1   5   0   1   7   5
0000011
</code>```

This all tells me that the binary print (fwrite) isn't doing what I expected. It's my understanding the fwrite command writes the binary data to the file. In that case why does it successful write a value less than 128 but it fails with values equal to or greater than 128?

Environment:
  Code::Blocks 16.01
  Centos 7.1

Note: I did find this similar question: fwrite with non ASCII characters but it didn't seem to help with my situation. I could be wrong. Please let me know if I missed something in that post?

答: You are printing in octal (that's what od does by default), 226 octal is 150 decimal.</p>

Title: Shifting Extended ASCII codes

Body:
When assigning Extended ASCII codes to an unsigned char, I noticed that the values are shifted upwards when they are written to a file.

I condensed my code into this simple program to briefly present my question:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned char testascii[3];

    testascii[0] = 122;
    testascii[1] = 150;
    testascii[2] = 175;

    printf("%d\n", testascii[0]);
    printf("%d\n", testascii[1]);
    printf("%d\n", testascii[2]);

    return 0;
}

If I run this simple program, I get this terminal output:

122
150
175

This is correct.

If I now add the following to the above program:

FILE *f;
f = fopen("/mystuff/testascii", "wb");
if (f == NULL)
{
  printf("Error opening file\n");
  exit(1);
}
fwrite(testascii, 1, 3, f);
fclose(f);

It runs correctly but if I now go to the O/S and run:

od -c testascii

I get this output:

0000000   z 226 257
0000003

As you can see the Standard ASCII code (below 128) is correctly shown; however the Extended ASCII codes (above 127) are changed. I expect them to be 150 and 175 but they are 226 and 257.

If I remove the binary flag from the file open command, the result is still the same.

As a final check, instead of the binary print (fwrite), I changed the code again and looped through the array and did a fprintf of each item like this:

fprintf (fp, "%d", appendtxt[i]);

Here's the OD display for that:

0000000   1   2   2   1   5   0   1   7   5
0000011

This all tells me that the binary print (fwrite) isn't doing what I expected. It's my understanding the fwrite command writes the binary data to the file. In that case why does it successful write a value less than 128 but it fails with values equal to or greater than 128?

Environment:
  Code::Blocks 16.01
  Centos 7.1

Note: I did find this similar question: fwrite with non ASCII characters but it didn't seem to help with my situation. I could be wrong. Please let me know if I missed something in that post?


问:
Simple script running on server and app communicating with it
new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the request and how can the page/application receive the data back(like download link,or info like JSON).

A simple information would suffice,i don't need a thorough explanation,mostly names like protocols,etc.. maybe some sample code for Hello World.

I should add that my website runs with Wordpress and i am not looking to change that yet.I want to create a web app within wordpress,with the app written in Python.

答: I would suggest using something like AWS Lambda. Lambda is an AWS product that will allow you to host your function online and you can just call it with HTTP requests and GET a response. More at aws.amazon.com/lambda</p>


问:
JOIN clause wne using raw SQL in javalite JDBC
Is it possible to use a JOIN clause when using a raw SQL ? If so, how should I map the result as there are at least 2 models involved ? </p>

答:
you can use any clause your database provides. When running a non-standard query, use method Model.findBySQL(...).

However, before using, read its documentation:

http://javalite.github.io/activejdbc/snapshot/org/javalite/activejdbc/Model.html#findBySQL-java.lang.String-java.lang.Object...-

Specifically, this:

Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate themselves properly. Returned columns that are not part of this model will be ignored, but can be used for clauses like above.

In other words, whatever query you execute, the columns it returns should match that of this model. Technically speaking, your query can span multiple tables, views, even execute custom functions, but the resultset needs to have the columns that match this model. Why is that? Because your model is 'O' in the ORM. In other words, it represents a single record from a table as an object.

If your results are a mix of more than one model, or a partial model, or anything in between, do not use a model API. Use Base:

```<code>List<Map> results = Base.findAll("complex custom query");
</code>```

http://javalite.github.io/activejdbc/snapshot/org/javalite/activejdbc/Base.html#findAll-java.lang.String-

Look at variations of find(...) and findAll(...) methods

Body:
you can use any clause your database provides. When running a non-standard query, use method Model.findBySQL(...).

However, before using, read its documentation:

http://javalite.github.io/activejdbc/snapshot/org/javalite/activejdbc/Model.html#findBySQL-java.lang.String-java.lang.Object...-

Specifically, this:

Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate themselves properly. Returned columns that are not part of this model will be ignored, but can be used for clauses like above.

In other words, whatever query you execute, the columns it returns should match that of this model. Technically speaking, your query can span multiple tables, views, even execute custom functions, but the resultset needs to have the columns that match this model. Why is that? Because your model is 'O' in the ORM. In other words, it represents a single record from a table as an object.

If your results are a mix of more than one model, or a partial model, or anything in between, do not use a model API. Use Base:

List<Map> results = Base.findAll("complex custom query");

http://javalite.github.io/activejdbc/snapshot/org/javalite/activejdbc/Base.html#findAll-java.lang.String-

Look at variations of find(...) and findAll(...) methods


问:
Simple Flask app using spaCy NLP hangs intermittently

I'm working on a simple Flask app that will eventually turn into a simple REST API for doing named entity recognition using spaCy on a given text string. I have a simple prototype as follows:

```<code>from flask import Flask, render_template, request, json
import spacy
from spacy import displacy

def to_json(doc):
        return [
                {
                'start': ent.start_char,
                'end': ent.end_char,
                'type': ent.label_,
                'text': str(ent),
                } for ent in doc.ents
                ]

nlp = spacy.load('en')

app = Flask(__name__)

@app.route('/')
def index():
        return render_template('index.html')

@app.route('/demo', methods=['GET', 'POST'])
def demo():
        q = request.values.get('text')
        doc = nlp(q)

        if request.values.get('type') == 'html':
                return displacy.render(doc, style='ent', page=True)
        else:
                return app.response_class(
                                response=json.dumps(to_json(doc), indent=4),
                                status=200,
                                mimetype='text/string'
                                )

if __name__ == '__main__':
     app.run(host='0.0.0.0')
</code>```

The Flask app is served using an Apache webserver on Ubuntu. I submit text to the app using a simple web form and it returns results as either HTML or JSON text.

The problem I am having is that the app hangs intermittently...I can't figure out a pattern of what causes it to hang. Nothing shows up in the Apache error log, and the request that hangs does not appear in the Apache access log. If I kill the server while the browser is spinning, the browser reports that the server provided an empty response. If I restart the server, the error log reports that 1 or 2 child processes don't exit after a SIGTERM, and a SIGKILL has to be sent.

One possible clue is that the error log reports the following when the server starts up:

```<code>[Wed Dec 06 20:19:33.753041 2017] [wsgi:warn] [pid 1822:tid 140029812619136] mod_wsgi: Compiled for Python/2.7.11.
[Wed Dec 06 20:19:33.753055 2017] [wsgi:warn] [pid 1822:tid 140029812619136] mod_wsgi: Runtime using Python/2.7.12.
</code>```

Another possible clue is that the "index" route (/) never seems to hang. But the "/demo" route can hang for both branches of the request.values.get('type') == 'html' if statement.

EDIT:
I've taken Apache and mod_wsgi out of the loop, and am now running the app using the standalone Flask server. The app still hangs occasionally...when it does, I can press control-c and it consistently returns the following as the most recent code:

```<code>Exception happened during processing of request from ('xxx.xxx.xxx.xxx', 55608)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 290, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 318, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
    self.handle()
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 232, in handle
    rv = BaseHTTPRequestHandler.handle(self)
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
    self.handle_one_request()
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 263, in handle_one_request
    self.raw_requestline = self.rfile.readline()
  File "/usr/lib/python2.7/socket.py", line 451, in readline
    data = self._sock.recv(self._rbufsize)
KeyboardInterrupt
----------------------------------------
</code>```

After pressing control-c, Flask gets "released" and then returns the result I expect. The server continues on as normal and will accept more requests until it hangs again. Sometimes a hung request will come back on its own if I wait long enough.

This seems more and more like it's a problem with Flask (or how I'm using it). If anyone can provide advice on how to track down the problem, I would appreciate it!

答:
Try forcing the user of the main Python interpreter context as explained in:

http://modwsgi.readthedocs.io/en/develop/user-guides/application-issues.html#python-simplified-gil-state-api

Some third party C extension modules in Python don't work properly in sub interpreters and can hang or crash the process.

Body:
I'm working on a simple Flask app that will eventually turn into a simple REST API for doing named entity recognition using spaCy on a given text string. I have a simple prototype as follows:

from flask import Flask, render_template, request, json
import spacy
from spacy import displacy

def to_json(doc):
        return [
                {
                'start': ent.start_char,
                'end': ent.end_char,
                'type': ent.label_,
                'text': str(ent),
                } for ent in doc.ents
                ]

nlp = spacy.load('en')

app = Flask(__name__)

@app.route('/')
def index():
        return render_template('index.html')

@app.route('/demo', methods=['GET', 'POST'])
def demo():
        q = request.values.get('text')
        doc = nlp(q)

        if request.values.get('type') == 'html':
                return displacy.render(doc, style='ent', page=True)
        else:
                return app.response_class(
                                response=json.dumps(to_json(doc), indent=4),
                                status=200,
                                mimetype='text/string'
                                )

if __name__ == '__main__':
     app.run(host='0.0.0.0')

The Flask app is served using an Apache webserver on Ubuntu. I submit text to the app using a simple web form and it returns results as either HTML or JSON text.

The problem I am having is that the app hangs intermittently...I can't figure out a pattern of what causes it to hang. Nothing shows up in the Apache error log, and the request that hangs does not appear in the Apache access log. If I kill the server while the browser is spinning, the browser reports that the server provided an empty response. If I restart the server, the error log reports that 1 or 2 child processes don't exit after a SIGTERM, and a SIGKILL has to be sent.

One possible clue is that the error log reports the following when the server starts up:

[Wed Dec 06 20:19:33.753041 2017] [wsgi:warn] [pid 1822:tid 140029812619136] mod_wsgi: Compiled for Python/2.7.11.
[Wed Dec 06 20:19:33.753055 2017] [wsgi:warn] [pid 1822:tid 140029812619136] mod_wsgi: Runtime using Python/2.7.12.

Another possible clue is that the "index" route (/) never seems to hang. But the "/demo" route can hang for both branches of the request.values.get('type') == 'html' if statement.

EDIT:
I've taken Apache and mod_wsgi out of the loop, and am now running the app using the standalone Flask server. The app still hangs occasionally...when it does, I can press control-c and it consistently returns the following as the most recent code:

Exception happened during processing of request from ('xxx.xxx.xxx.xxx', 55608)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 290, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 318, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
    self.handle()
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 232, in handle
    rv = BaseHTTPRequestHandler.handle(self)
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
    self.handle_one_request()
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 263, in handle_one_request
    self.raw_requestline = self.rfile.readline()
  File "/usr/lib/python2.7/socket.py", line 451, in readline
    data = self._sock.recv(self._rbufsize)
KeyboardInterrupt
----------------------------------------

After pressing control-c, Flask gets "released" and then returns the result I expect. The server continues on as normal and will accept more requests until it hangs again. Sometimes a hung request will come back on its own if I wait long enough.

This seems more and more like it's a problem with Flask (or how I'm using it). If anyone can provide advice on how to track down the problem, I would appreciate it!


问:
Get detected face bitmap
I'm experimenting with the following Google sample: https://github.com/googlesamples/android-vision/tree/master/visionSamples/FaceTracker

The sample is using the Play Service new Face detection APIs, and draws a square on detected faces on the camera video stream.

I'm trying to figure out if it is possible to save the frames that has detected faces in them, from following the code it seems that the face detector's processor is a good place to perform the 'saving' but it only supplies the detection meta data and not the actual frame.

Your guidance will be appreciated.

答:
You can get it in the following way:</p>

```<code>    Bitmap source = ((BitmapDrawable) yourImageView.getDrawable()).getBitmap();
    // detect faces
    Bitmap faceBitmap = createBitmap(source,
                                     face.getPosition().x,
                                     face.getPosition().y,
                                     face.getWidth(),
                                     face.getHeight());
</code>```

Title: Get detected face bitmap

Body:
You can get it in the following way:

    Bitmap source = ((BitmapDrawable) yourImageView.getDrawable()).getBitmap();
    // detect faces
    Bitmap faceBitmap = createBitmap(source,
                                     face.getPosition().x,
                                     face.getPosition().y,
                                     face.getWidth(),
                                     face.getHeight());


问:
Attach image in Native SMS/MMS Application on iPhone
i want to send an image through native application in iphone.

I have searched a lot on web but cant find anything.

is it possible with iOS?

Please do help...

答:
If you mean you want to do this programatically - I don't think you can. Your best bet'd be to save the image to the camera roll and tell the user to attach it. Maybe someone more experienced knows a better way of doing things. </p>

<p>If you just want to do it as a normal user opening the messages app, you can. Just click the little blue camera on the left hand side of the text field. </p>

ContentLicense: CC BY-SA 2.5

Body:
If you mean you want to do this programatically - I don't think you can. Your best bet'd be to save the image to the camera roll and tell the user to attach it. Maybe someone more experienced knows a better way of doing things.

If you just want to do it as a normal user opening the messages app, you can. Just click the little blue camera on the left hand side of the text field.


问:
Can't set headers after they are sent error happens with socket.io
I am writing a very simple nodejs socket.io app. Somehow this returns "can't set headers after they are sent" error. but I can't see the point where the header is set again. I've only called server.listen once and I believe socket.listen works independently so it shouldn't conflict.

I am aware that can't set headers error had been posted a multiple times. I've read them briefly and I also understand how does response.writeHead works under normal circumstances(I've experimented with some node.js apps with response.writeHead, they worked fine most cases) it seems I am missing something from here. is it due to socket.io?

```<code>const fs = require("fs");

const server = require("http").createServer();
const io = require("socket.io").listen(server);

server.listen(52273,function(){
  console.log("server up");
});

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

io.sockets.on("connection",function(socket){

  var roomName = null;
  socket.on("join", function(data){
    roomName = data;
    socket.join(data);
    console.log("client joined" + data);
  });

  socket.on("message",function(data){
    io.sockets.in(roomName).emit("message","test");
  });
});
</code>```

答:
What version of Node you using?

We had the same problem when we were using 0.9.x. I downgraded Node to 0.8.4 and the problem seems to have gone away.

My best guess is something in Node has changed that Socket.io doesnt agree with.

Body:
I am writing a very simple nodejs socket.io app. Somehow this returns "can't set headers after they are sent" error. but I can't see the point where the header is set again. I've only called server.listen once and I believe socket.listen works independently so it shouldn't conflict.

I am aware that can't set headers error had been posted a multiple times. I've read them briefly and I also understand how does response.writeHead works under normal circumstances(I've experimented with some node.js apps with response.writeHead, they worked fine most cases) it seems I am missing something from here. is it due to socket.io?

const fs = require("fs");

const server = require("http").createServer();
const io = require("socket.io").listen(server);

server.listen(52273,function(){
  console.log("server up");
});

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

io.sockets.on("connection",function(socket){

  var roomName = null;
  socket.on("join", function(data){
    roomName = data;
    socket.join(data);
    console.log("client joined" + data);
  });

  socket.on("message",function(data){
    io.sockets.in(roomName).emit("message","test");
  });
});


问:
WordPress Contact Form 7 CF7 Shortcode not working
Facing this issue i.e. Contact Form 7 shortcode will not work, just show the raw shortcode when in Post Draft mode, trying to find any way to make it work.

Strange that it works on all other page and areas but not on this new page I am working on. I have tried to find any reason but no success so far.

Update: It was due to page being in Draft Mode , turned out that CF7 does not execute the CF7 Shortcode if page is not published and you are previewing it in Draft mode.

答:
Problem was that database messed up the html code.
Which has been right after retrieved from DB and passed to the method.

Not sure if it is your problem, but according my searching plenty of websites nobody mentioned this between 2011-2017 !!!! OMG

```<code>echo do_shortcode(htmlspecialchars_decode($memberModel->getContactShortcode())
</code>```

For me, this finally works

Body:
Problem was that database messed up the html code.
Which has been right after retrieved from DB and passed to the method.

Not sure if it is your problem, but according my searching plenty of websites nobody mentioned this between 2011-2017 !!!! OMG

echo do_shortcode(htmlspecialchars_decode($memberModel->getContactShortcode())

For me, this finally works


问:
JPA @ManyToOne @JoinFormula throwing ClassCastException
I'm trying to model a many-to-one bi-directional association using JPA. The join uses a formula. I've tried it a couple of ways, as shown below. Once with just JoinFormula and another with JoinColumnsOrFormulas.

```<code>public class JobOperation
{
  private Operation                 operation;

  @ManyToOne
  //  @JoinFormula("CASE WHEN attribute7 IS NULL OR TO_NUMBER(attribute7) = 0 THEN standard_operation_id ELSE TO_NUMBER(attribute7) END")
  @JoinColumnsOrFormulas(
  {
    @JoinColumnOrFormula(formula = @JoinFormula(//
        value = "(CASE WHEN this_.attribute7 IS NULL OR TO_NUMBER(this_.attribute7) = 0 THEN this_.standard_operation_id ELSE TO_NUMBER(this_.attribute7) END)", //
        referencedColumnName = "standard_operation_id"))
  })
  @Fetch(FetchMode.SELECT)
  @NotFound(action = NotFoundAction.IGNORE)
  public Operation getOperation()
  {
    return this.operation;
  }
}
</code>```

I originally was using Hibernate 4.3.9 and then tried with Hibernate 5.1.0. Both throw the same exception:

```<code>15:55:21,408 DEBUG [org.hibernate.cfg.annotations.TableBinder] Retrieving property com.icumed.ifactory3.dto.wip.JobOperation.operation
15:55:21,409 DEBUG [org.hibernate.jpa.HibernatePersistenceProvider] Unable to build entity manager factory
java.lang.ClassCastException: org.hibernate.mapping.Formula cannot be cast to org.hibernate.mapping.Column
    at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:584)
</code>```

Nothing in Hibernate's TableBinder class refers to a formula. Does Hibernate just not support this or am I using the wrong annotations, or is there something else going on?

答:
The root cause of the problem seems to be on the other side of the association. I originally had this

```<code>public class Operation extends AbstractOperation
{
  @OneToMany(mappedBy="operation")
  public Set<JobOperation> getJobOperations()
  {
    return this.jobOperations;
  }
}
</code>```

and when I changed it to the following, it worked.

```<code>public class Operation extends AbstractOperation
{
  @OneToMany
  @JoinColumn(name="STANDARD_OPERATION_ID")
  public Set<JobOperation> getJobOperations()
  {
    return this.jobOperations;
  }
}
</code>```

Body:
I'm trying to model a many-to-one bi-directional association using JPA. The join uses a formula. I've tried it a couple of ways, as shown below. Once with just JoinFormula and another with JoinColumnsOrFormulas.

public class JobOperation
{
  private Operation                 operation;

  @ManyToOne
  //  @JoinFormula("CASE WHEN attribute7 IS NULL OR TO_NUMBER(attribute7) = 0 THEN standard_operation_id ELSE TO_NUMBER(attribute7) END")
  @JoinColumnsOrFormulas(
  {
    @JoinColumnOrFormula(formula = @JoinFormula(//
        value = "(CASE WHEN this_.attribute7 IS NULL OR TO_NUMBER(this_.attribute7) = 0 THEN this_.standard_operation_id ELSE TO_NUMBER(this_.attribute7) END)", //
        referencedColumnName = "standard_operation_id"))
  })
  @Fetch(FetchMode.SELECT)
  @NotFound(action = NotFoundAction.IGNORE)
  public Operation getOperation()
  {
    return this.operation;
  }
}

I originally was using Hibernate 4.3.9 and then tried with Hibernate 5.1.0. Both throw the same exception:

15:55:21,408 DEBUG [org.hibernate.cfg.annotations.TableBinder] Retrieving property com.icumed.ifactory3.dto.wip.JobOperation.operation
15:55:21,409 DEBUG [org.hibernate.jpa.HibernatePersistenceProvider] Unable to build entity manager factory
java.lang.ClassCastException: org.hibernate.mapping.Formula cannot be cast to org.hibernate.mapping.Column
    at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:584)

Nothing in Hibernate's TableBinder class refers to a formula. Does Hibernate just not support this or am I using the wrong annotations, or is there something else going on?

Body:
The root cause of the problem seems to be on the other side of the association. I originally had this

public class Operation extends AbstractOperation
{
  @OneToMany(mappedBy="operation")
  public Set<JobOperation> getJobOperations()
  {
    return this.jobOperations;
  }
}

and when I changed it to the following, it worked.

public class Operation extends AbstractOperation
{
  @OneToMany
  @JoinColumn(name="STANDARD_OPERATION_ID")
  public Set<JobOperation> getJobOperations()
  {
    return this.jobOperations;
  }
}


问:
Stuck in a while loop in python
I'm very new to python so bear with me. I have this code below which I've inserted a while loop to make sure every time a name is given it checks to verify that name is in the csv and then if it isn't it gives and error and asks for a new name. My problem is that I can't seem to get out of the loop. Even with a new name that I know for a fact is in the csv it still sticks in the loop. My question is how can I get this code to run through a loop and verify the name is in there? any help would be great. I am even open to changing the entire code if there's a better way to write this.

Here's what I got:

```<code>import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

```<code>Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system
</code>```

Here's what the output should look like when the code runs.

```<code>Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours
</code>```

and the csv looks like this:

```<code>First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4
</code>```

答:
assuming the file can have multiple lines related to the given full name, try something like:</p>

```<code>import csv

full_name = input('Enter your full name: ').lower()
run=1
while run:
    with open('Report1.csv') as csvfile:
        hour_summation = {}
        read_csv = csv.reader(csvfile, delimiter=',')
        for row in read_csv:
            if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))

    if hour_summation:
        print('This is {} full hours report:'.format(full_name))
        for k, v in hour_summation.items():
            print(k + ': ' + str(v) + ' hours')
        run=0
    else:
        print('Name is not in system')
        full_name = input('Enter your full name: ').lower() # following your code,
                                                            # request for a new full name comes only in case no results for the 1st one
</code>```

Title: Stuck in a while loop in python

Body:
I'm very new to python so bear with me. I have this code below which I've inserted a while loop to make sure every time a name is given it checks to verify that name is in the csv and then if it isn't it gives and error and asks for a new name. My problem is that I can't seem to get out of the loop. Even with a new name that I know for a fact is in the csv it still sticks in the loop. My question is how can I get this code to run through a loop and verify the name is in there? any help would be great. I am even open to changing the entire code if there's a better way to write this.

Here's what I got:

import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system

Here's what the output should look like when the code runs.

Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours

and the csv looks like this:

First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4

Body:
assuming the file can have multiple lines related to the given full name, try something like:

import csv

full_name = input('Enter your full name: ').lower()
run=1
while run:
    with open('Report1.csv') as csvfile:
        hour_summation = {}
        read_csv = csv.reader(csvfile, delimiter=',')
        for row in read_csv:
            if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))

    if hour_summation:
        print('This is {} full hours report:'.format(full_name))
        for k, v in hour_summation.items():
            print(k + ': ' + str(v) + ' hours')
        run=0
    else:
        print('Name is not in system')
        full_name = input('Enter your full name: ').lower() # following your code,
                                                            # request for a new full name comes only in case no results for the 1st one


问:
VSCode Extension API - on scroll
Is there a way to detected when scrolling in the VSCode extension API. The only available functions I see are:

onDidChangeActiveTextEditor: Event<TextEditor>

onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>

onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>

onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>

onDidChangeVisibleTextEditors: Event<TextEditor[]>

onDidChangeWindowState: Event<WindowState>

onDidCloseTerminal: Event<Terminal>
```

I can file this as a feature request. But is there any way to circumvent this behavior?

答:
VS Code now has an api for this: window.onDidChangeTextEditorVisibleRanges

This event is fired with an TextEditorVisibleRangesChangeEvent object:

export interface TextEditorVisibleRangesChangeEvent {
    /**
     * The text editor for which the visible ranges have changed.
     */
    textEditor: TextEditor;

    /**
     * The new value for the text editor's visible ranges.
     */
    visibleRanges: Range[];
}
```

VS Code's markdown preview uses this event to synchronize the scrolling of the editor with the markdown  preview.

ContentLicense: CC BY-SA 4.0

Title: VSCode Extension API - on scroll

Body:
Is there a way to detected when scrolling in the VSCode extension API. The only available functions I see are:

onDidChangeActiveTextEditor: Event<TextEditor>

onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>

onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>

onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>

onDidChangeVisibleTextEditors: Event<TextEditor[]>

onDidChangeWindowState: Event<WindowState>

onDidCloseTerminal: Event<Terminal>

I can file this as a feature request. But is there any way to circumvent this behavior?

Body:
VS Code now has an api for this: window.onDidChangeTextEditorVisibleRanges

This event is fired with an TextEditorVisibleRangesChangeEvent object:

export interface TextEditorVisibleRangesChangeEvent {
    /**
     * The text editor for which the visible ranges have changed.
     */
    textEditor: TextEditor;

    /**
     * The new value for the text editor's visible ranges.
     */
    visibleRanges: Range[];
}

VS Code's markdown preview uses this event to synchronize the scrolling of the editor with the markdown  preview.


问:
Dynamically invoke a method given a Type variable
My Goal:
I have a system where I would like others to be able to add a C# script that contains a specific method that I can lookup and execute from within another class at runtime.

My Approach:
I created an interface with a method so I can loop through any class that implements the interface using reflection and list them then have the method name be the same between all those classes.

I have class that has an enum of all the classes found during the lookup and the user can select between them at runtime.

I now need to be able to get the method of the selected class type and invoke it's method, the problem is I know the name of the method for certain but the type of the class is stored as a variable.

The Code:

//Pseudo code from memory:

```<code>            //Possible solution 1:
            Type selectedType = typeSelectedByEnum;
            MethodInfo genericMethod = selectedType.GetMethod("TheInterfaceMethod").MakeGenericMethod(selectedType);
            genericMethod.Invoke(selectedType, new object[0]);

            //Possible solution 2: (however I would much prefer to use something avaliable prior to .NET 4.6)
            Type selectedType = typeSelectedByEnum;
            dynamic changedObj = Convert.ChangeType(selectedType, selectedType);//-Something here needs to implement IConvertable, how would I set this up?
            changedObj.TheInterfaceMethod();

            //Possible solution 3:

            //Your solution??!
</code>```

Any help appreciated, at this point I have tried many things and am open to just about any possible runtime alternative. I can provide more code if necessary.

答:
Since you are using an interface to mark classes that have your method "TheInterfaceMethod", then the method must not be static. That means that you need an instance of the object in which to invoke the method on. The Activator class provides an easy way to create instances of objects, but it does require a default constructor with visibility (most likely a public constructor in your case).

I also noticed on potential issue with your example which is that you were calling "MakeGenericMethod". This is only necessary if the function has some generic type parameter that you need to define to have a meaningful function. Such as this interface:

```<code>    interface IInterfaceWithGenericMethod
    {
        void TheInterfaceMethod<T>();
    }
</code>```

Here's an example using your variables:

```<code>        Type selectedType = typeSelectedByEnum;
        MethodInfo method = selectedType.GetMethod("TheInterfaceMethod");
        object obj = Activator.CreateInstance(selectedType);
        method.Invoke(obj, null);
</code>```

Interestingly, once you have an instance of the object, you don't need reflection to invoke the method anymore. You can simply cast it to your interface. Let's assume your interface is called IAwesomeInterface:

```<code>        Type selectedType = typeSelectedByEnum;
        object obj = Activator.CreateInstance(selectedType);
        IAwesomeInterface converted = obj as IAwesomeInterface;
        converted.TheInterfaceMethod();
</code>```

Body:
My Goal:
I have a system where I would like others to be able to add a C# script that contains a specific method that I can lookup and execute from within another class at runtime.

My Approach:
I created an interface with a method so I can loop through any class that implements the interface using reflection and list them then have the method name be the same between all those classes.

I have class that has an enum of all the classes found during the lookup and the user can select between them at runtime.

I now need to be able to get the method of the selected class type and invoke it's method, the problem is I know the name of the method for certain but the type of the class is stored as a variable.

The Code:

//Pseudo code from memory:

            //Possible solution 1:
            Type selectedType = typeSelectedByEnum;
            MethodInfo genericMethod = selectedType.GetMethod("TheInterfaceMethod").MakeGenericMethod(selectedType);
            genericMethod.Invoke(selectedType, new object[0]);

            //Possible solution 2: (however I would much prefer to use something avaliable prior to .NET 4.6)
            Type selectedType = typeSelectedByEnum;
            dynamic changedObj = Convert.ChangeType(selectedType, selectedType);//-Something here needs to implement IConvertable, how would I set this up?
            changedObj.TheInterfaceMethod();

            //Possible solution 3:

            //Your solution??!

Any help appreciated, at this point I have tried many things and am open to just about any possible runtime alternative. I can provide more code if necessary.

Body:
Since you are using an interface to mark classes that have your method "TheInterfaceMethod", then the method must not be static. That means that you need an instance of the object in which to invoke the method on. The Activator class provides an easy way to create instances of objects, but it does require a default constructor with visibility (most likely a public constructor in your case).

I also noticed on potential issue with your example which is that you were calling "MakeGenericMethod". This is only necessary if the function has some generic type parameter that you need to define to have a meaningful function. Such as this interface:

    interface IInterfaceWithGenericMethod
    {
        void TheInterfaceMethod<T>();
    }

Here's an example using your variables:

        Type selectedType = typeSelectedByEnum;
        MethodInfo method = selectedType.GetMethod("TheInterfaceMethod");
        object obj = Activator.CreateInstance(selectedType);
        method.Invoke(obj, null);

Interestingly, once you have an instance of the object, you don't need reflection to invoke the method anymore. You can simply cast it to your interface. Let's assume your interface is called IAwesomeInterface:

        Type selectedType = typeSelectedByEnum;
        object obj = Activator.CreateInstance(selectedType);
        IAwesomeInterface converted = obj as IAwesomeInterface;
        converted.TheInterfaceMethod();


问:
warning: branch has multiple values and pull also fails
I used to have an old branch 201.  I removed it both locally and on the remote.

I now have a local branch called 201-me.  I tried to rename it locally and did, but then renamed it back to 201-me again.

But now I can't set it upstream to 201-me, I get:

```<code>company/app/app-api  201-me ✔                                                                                2h5m  ⍉
▶ git branch --set-upstream-to=origin/201-me
warning: branch.201-me.remote has multiple values
warning: branch.201-me.merge has multiple values
Branch 201-me set up to track remote branch 201-me from origin.

company/app/app-api  201-me ✔                                                                                2h6m
▶ git pull
Your configuration specifies to merge with the ref 'refs/heads/201'
from the remote, but no such ref was fetched.

▶ git branch -vv
* 201-me ef4632c [origin/201: ahead 10, behind 1]

company/app/app-api  201-me ✔                                                                                2h13m
▶ git pull
remote: Counting objects: 10, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 10 (delta 8), reused 10 (delta 8), pack-reused 0
Unpacking objects: 100% (10/10), done.
Your configuration specifies to merge with the ref 'refs/heads/201'
from the remote, but no such ref was fetched.
</code>```

答:
Yup, I had 2 entries in ./git/config:

```<code>[branch "201-me"]
    remote = origin
    merge = refs/heads/201

[branch "201-me"]
    remote = origin
    merge = refs/heads/201
</code>```

so deleted one of them and then fixed it:

```<code>[branch "201-me"]
    remote = origin
    merge = refs/heads/201-me
</code>```

Body:
I used to have an old branch 201.  I removed it both locally and on the remote.

I now have a local branch called 201-me.  I tried to rename it locally and did, but then renamed it back to 201-me again.

But now I can't set it upstream to 201-me, I get:

company/app/app-api  201-me ✔                                                                                2h5m  ⍉
▶ git branch --set-upstream-to=origin/201-me
warning: branch.201-me.remote has multiple values
warning: branch.201-me.merge has multiple values
Branch 201-me set up to track remote branch 201-me from origin.

company/app/app-api  201-me ✔                                                                                2h6m
▶ git pull
Your configuration specifies to merge with the ref 'refs/heads/201'
from the remote, but no such ref was fetched.

▶ git branch -vv
* 201-me ef4632c [origin/201: ahead 10, behind 1]

company/app/app-api  201-me ✔                                                                                2h13m
▶ git pull
remote: Counting objects: 10, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 10 (delta 8), reused 10 (delta 8), pack-reused 0
Unpacking objects: 100% (10/10), done.
Your configuration specifies to merge with the ref 'refs/heads/201'
from the remote, but no such ref was fetched.

Body:
Yup, I had 2 entries in ./git/config:

[branch "201-me"]
    remote = origin
    merge = refs/heads/201

[branch "201-me"]
    remote = origin
    merge = refs/heads/201

so deleted one of them and then fixed it:

[branch "201-me"]
    remote = origin
    merge = refs/heads/201-me


问:
What is the purpose of adding to INSTALLED_APPS in Django?
Most documentation simply tells you to add the name of each of your apps to the INSTALLED_APPS array in your Django project's settings. What is the benefit/purpose of this? What different functionality will I get if I create 2 apps, but only include the name of one in my INSTALLED_APPS array?</p>

答:
Django uses INSTALLED_APPS as a list of all of the places to look for models, management commands, tests, and other utilities.

If you made two apps (say myapp and myuninstalledapp), but only one was listed in INSTALLED_APPS, you'd notice the following behavior:

The models contained in myuninstalledapp/models.py would never trigger migration changes (or generate initial migrations). You wouldn't be able to interact with them on the database level either because their tables will have never been created.

Static files listed within myapp/static/ would be discovered as part of collectstatic or the test server's staticfiles serving, but myuninstalledapp/static files wouldn't be.

Tests within myapp/tests.py would run but myuninstalledapp/tests.py wouldn't.

Management commands listed in myuninstalledapp/management/commands/ wouldn't be discovered.

So really, you're welcome to have folders within your Django project that aren't installed apps (you can even create them with python manage.py startapp) but just know that certain auto-discovery Django utilities won't work for that application.


问:
How to upload large file to azure using typescript
I was looking for a way to upload large big files to azure data lake store using typescript but end up with no answer, have any one done this? Thanks in advance.

------------EDITED----------------
I found a way to give REST API calls to send data to azure data lake, this is the link i'm following https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-data-operations-rest-api.

It is successful through PostMan, but now the big hurdle i am facing is the way to make these requests in typescript. Have anyone did this?

答:
I am not aware of samples for Typescript. However, if you are trying to upload large files using the REST API, you will need to handle errors, retries, etc in your code. Instead of the REST API, can you use the SDKs that we provide?  https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-get-started-java-sdk - This is link to Java SDK. We also have Python SDK and .NET SDK. These SDKs handle a lot of the heavylifting for you that needs to be done when using the REST APIs.

Thanks,
Sachin Sheth
Program Manager, Azure Data Lake.


问:
Change AppIcon at build time in Xcode 9
I use a script to generate app icon at build time (just add "dev" title for debug mode). That's pretty easy using ImageMagick and Ghostscript (a lot of examples in google). Everything was ok before I started to use new Xcode 9. Now, I can see updated icons on MyAppName.app file but simulator/device shows AppIcon from assets.
Any suggestions? Thx</p>

答:
Support Xcode 9

check full example here
https://github.com/dimohamdy/IconOverlaying

Full Script

```<code>#!/bin/sh
export PATH=/opt/local/bin/:/opt/local/sbin:$PATH:/usr/local/bin:

convertPath=`which convert`
gsPath=`which gs`

if [[ ! -f ${convertPath} || -z ${convertPath} ]]; then
  convertValidation=true;
else
  convertValidation=false;
fi

if [[ ! -f ${gsPath} || -z ${gsPath} ]]; then
  gsValidation=true;
else
  gsValidation=false;
fi

if [[ "$convertValidation" = true || "$gsValidation" = true ]]; then
  echo "WARNING: Skipping Icon versioning, you need to install ImageMagick and ghostscript (fonts) first, you can use brew to simplify process:"

  if [[ "$convertValidation" = true ]]; then
    echo "brew install imagemagick"
  fi
  if [[ "$gsValidation" = true ]]; then
    echo "brew install ghostscript"
  fi
exit 0;
fi

version=`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${SRCROOT}/${PROJECT_NAME}/${INFOPLIST_PATH}"`
build_num=`/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${SRCROOT}/${PROJECT_NAME}/${INFOPLIST_PATH}"`

# Check if we are under a Git or Hg repo
if [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1; then
    commit=`git rev-parse --short HEAD`
    branch=`git rev-parse --abbrev-ref HEAD`
else
    commit=`hg identify -i`
    branch=`hg identify -b`
fi;

#SRCROOT=..
#CONFIGURATION_BUILD_DIR=.
#UNLOCALIZED_RESOURCES_FOLDER_PATH=.

#commit="3783bab"
#branch="master"
#version="3.4"
#build_num="9999"

shopt -s extglob
build_num="${build_num##*( )}"
shopt -u extglob
caption="${version} ($build_num)\n${branch}\n${commit}"
echo $caption

function abspath() { pushd . > /dev/null; if [ -d "$1" ]; then cd "$1"; dirs -l +0; else cd "`dirname \"$1\"`"; cur_dir=`dirs -l +0`; if [ "$cur_dir" == "/" ]; then echo "$cur_dir`basename \"$1\"`"; else echo "$cur_dir/`basename \"$1\"`"; fi; fi; popd > /dev/null; }

function processIcon() {
    base_path=$1

     echo base_path

    #this is the change
    target_path=$base_path

    width=`identify -format %w ${base_path}`
    height=`identify -format %h ${base_path}`

    band_height=$((($height * 47) / 100))
    band_position=$(($height - $band_height))
    text_position=$(($band_position - 3))
    point_size=$(((13 * $width) / 100))

    echo "Image dimensions ($width x $height) - band height $band_height @ $band_position - point size $point_size"

    #
    # blur band and text
    #
    convert ${base_path} -blur 10x8 /tmp/blurred.png
    convert /tmp/blurred.png -gamma 0 -fill white -draw "rectangle 0,$band_position,$width,$height" /tmp/mask.png
    convert -size ${width}x${band_height} xc:none -fill 'rgba(0,0,0,0.2)' -draw "rectangle 0,0,$width,$band_height" /tmp/labels-base.png
    convert -background none -size ${width}x${band_height} -pointsize $point_size -fill white -gravity center -gravity South caption:"$caption" /tmp/labels.png

    convert ${base_path} /tmp/blurred.png /tmp/mask.png -composite /tmp/temp.png

    rm /tmp/blurred.png
    rm /tmp/mask.png

    #
    # compose final image
    #
    filename=New${base_file}
    convert /tmp/temp.png /tmp/labels-base.png -geometry +0+$band_position -composite /tmp/labels.png -geometry +0+$text_position -geometry +${w}-${h} -composite "${target_path}"

    # clean up
    rm /tmp/temp.png
    rm /tmp/labels-base.png
    rm /tmp/labels.png

    echo "Overlayed ${target_path}"
}

    if [ $CONFIGURATION = "Release" ]; then
       cp  $SRCROOT/$PROJECT_NAME/Assets.xcassets/AppIcon.appiconset/icons/*.png "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/"
      echo "Exit"
      exit 0
    fi

if [ -d "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/icons/" ]
then
    echo "Directory exists."
    # get original icon to copy to assets
       cp  $SRCROOT/$PROJECT_NAME/Assets.xcassets/AppIcon.appiconset/icons/*.png "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/"
else
    # copy orgin to AppIcon
    rsync -rv  --include '*.png' --exclude '*' "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/" "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/icons/"
fi

for entry in "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset"/*.png
do
  processIcon "$entry"
done
</code>```

Title: Change AppIcon at build time in Xcode 9

Body:
Support Xcode 9

check full example here
https://github.com/dimohamdy/IconOverlaying

Full Script

#!/bin/sh
export PATH=/opt/local/bin/:/opt/local/sbin:$PATH:/usr/local/bin:

convertPath=`which convert`
gsPath=`which gs`

if [[ ! -f ${convertPath} || -z ${convertPath} ]]; then
  convertValidation=true;
else
  convertValidation=false;
fi

if [[ ! -f ${gsPath} || -z ${gsPath} ]]; then
  gsValidation=true;
else
  gsValidation=false;
fi

if [[ "$convertValidation" = true || "$gsValidation" = true ]]; then
  echo "WARNING: Skipping Icon versioning, you need to install ImageMagick and ghostscript (fonts) first, you can use brew to simplify process:"

  if [[ "$convertValidation" = true ]]; then
    echo "brew install imagemagick"
  fi
  if [[ "$gsValidation" = true ]]; then
    echo "brew install ghostscript"
  fi
exit 0;
fi

version=`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${SRCROOT}/${PROJECT_NAME}/${INFOPLIST_PATH}"`
build_num=`/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${SRCROOT}/${PROJECT_NAME}/${INFOPLIST_PATH}"`

# Check if we are under a Git or Hg repo
if [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1; then
    commit=`git rev-parse --short HEAD`
    branch=`git rev-parse --abbrev-ref HEAD`
else
    commit=`hg identify -i`
    branch=`hg identify -b`
fi;

#SRCROOT=..
#CONFIGURATION_BUILD_DIR=.
#UNLOCALIZED_RESOURCES_FOLDER_PATH=.

#commit="3783bab"
#branch="master"
#version="3.4"
#build_num="9999"

shopt -s extglob
build_num="${build_num##*( )}"
shopt -u extglob
caption="${version} ($build_num)\n${branch}\n${commit}"
echo $caption

function abspath() { pushd . > /dev/null; if [ -d "$1" ]; then cd "$1"; dirs -l +0; else cd "`dirname \"$1\"`"; cur_dir=`dirs -l +0`; if [ "$cur_dir" == "/" ]; then echo "$cur_dir`basename \"$1\"`"; else echo "$cur_dir/`basename \"$1\"`"; fi; fi; popd > /dev/null; }

function processIcon() {
    base_path=$1

     echo base_path

    #this is the change
    target_path=$base_path

    width=`identify -format %w ${base_path}`
    height=`identify -format %h ${base_path}`

    band_height=$((($height * 47) / 100))
    band_position=$(($height - $band_height))
    text_position=$(($band_position - 3))
    point_size=$(((13 * $width) / 100))

    echo "Image dimensions ($width x $height) - band height $band_height @ $band_position - point size $point_size"

    #
    # blur band and text
    #
    convert ${base_path} -blur 10x8 /tmp/blurred.png
    convert /tmp/blurred.png -gamma 0 -fill white -draw "rectangle 0,$band_position,$width,$height" /tmp/mask.png
    convert -size ${width}x${band_height} xc:none -fill 'rgba(0,0,0,0.2)' -draw "rectangle 0,0,$width,$band_height" /tmp/labels-base.png
    convert -background none -size ${width}x${band_height} -pointsize $point_size -fill white -gravity center -gravity South caption:"$caption" /tmp/labels.png

    convert ${base_path} /tmp/blurred.png /tmp/mask.png -composite /tmp/temp.png

    rm /tmp/blurred.png
    rm /tmp/mask.png

    #
    # compose final image
    #
    filename=New${base_file}
    convert /tmp/temp.png /tmp/labels-base.png -geometry +0+$band_position -composite /tmp/labels.png -geometry +0+$text_position -geometry +${w}-${h} -composite "${target_path}"

    # clean up
    rm /tmp/temp.png
    rm /tmp/labels-base.png
    rm /tmp/labels.png

    echo "Overlayed ${target_path}"
}

    if [ $CONFIGURATION = "Release" ]; then
       cp  $SRCROOT/$PROJECT_NAME/Assets.xcassets/AppIcon.appiconset/icons/*.png "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/"
      echo "Exit"
      exit 0
    fi

if [ -d "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/icons/" ]
then
    echo "Directory exists."
    # get original icon to copy to assets
       cp  $SRCROOT/$PROJECT_NAME/Assets.xcassets/AppIcon.appiconset/icons/*.png "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/"
else
    # copy orgin to AppIcon
    rsync -rv  --include '*.png' --exclude '*' "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/" "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset/icons/"
fi

for entry in "${SRCROOT}/${PROJECT_NAME}/Assets.xcassets/AppIcon.appiconset"/*.png
do
  processIcon "$entry"
done


问:
How to use cross_val_predict to predict probabilities for a new dataset?
I am using sklearn's cross_val_predict for training like so:

```<code>  myprobs_train = cross_val_predict(LogisticRegression(),X = x_old, y=y_old, method='predict_proba', cv=10)
</code>```

I am happy with the returned probabilities, and would like now to score up a brand-new dataset.  I tried:

```<code>  myprobs_test = cross_val_predict(LogisticRegression(), X =x_new, y= None, method='predict_proba',cv=10)
</code>```

but this did not work, it's complaining about y having zero shape.   Does it mean there's no way to apply the trained and cross-validated model from cross_val_predict on new data?  Or am I just using it wrong?

Thank you!

答:
You are looking at a wrong method. Cross validation methods do not return a trained model; they return values that evaluate the performance of a model (logistic regression in your case). Your goal is to fit some data and then generate prediction for new data. The relevant methods are fit and predict of the LogisticRegression class. Here is the basic structure: </p>

```<code>logreg = linear_model.LogisticRegression()
logreg.fit(x_old, y_old)
predictions = logreg.predict(x_new)
</code>```

Body:
I am using sklearn's cross_val_predict for training like so:

  myprobs_train = cross_val_predict(LogisticRegression(),X = x_old, y=y_old, method='predict_proba', cv=10)

I am happy with the returned probabilities, and would like now to score up a brand-new dataset.  I tried:

  myprobs_test = cross_val_predict(LogisticRegression(), X =x_new, y= None, method='predict_proba',cv=10)

but this did not work, it's complaining about y having zero shape.   Does it mean there's no way to apply the trained and cross-validated model from cross_val_predict on new data?  Or am I just using it wrong?

Thank you!

Body:
You are looking at a wrong method. Cross validation methods do not return a trained model; they return values that evaluate the performance of a model (logistic regression in your case). Your goal is to fit some data and then generate prediction for new data. The relevant methods are fit and predict of the LogisticRegression class. Here is the basic structure:

logreg = linear_model.LogisticRegression()
logreg.fit(x_old, y_old)
predictions = logreg.predict(x_new)


问:
Evaluate per class precision and recall in FastText
I am using Facebook Research FastText library for text classification following this tutorial. I have 2 labels for which i am performing the classification (2-class). The output of the prediction on test file shows the precision and recall for the same. How can i calculate per-class precision and recall for my test file?</p>

答:
I had to deal with this recently myself. This issue in Github describes the issue, and presents a solution.

In summary, you need to do this as a post processing step. The code linked to above does a comparison of your actual labels vs the predicted ones and computes a confusion matrix which accurately reflects the classifier's performance for binary classification. This code computes the confusion matrix and accuracy only. If you wanted to also add in the precision and recall you could similarly use the scikitlearn API such as sklearn.metrics.precision_recall_fscore_support


问:
Cloudformation : is it possible to export current aws configuration as template?
I just created Dynamodb table, Lambda function, S3 bucket, etc. I would like to know if there's a way to export this configuration as cloudformation template</p>

答: Yes you could use cloudformer to export your aws resources into cloudformation template. Please refer this for example and sample steps . http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-cloudformer.html</p>


问:
why json response has square brackets
For some reason I have to use JSON like this:

php code

```<code>$json = json_decode([{
"key":1812,
        "ticks":0,
        "events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
        "s1a":"011A00002066C0D9",
        "s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
        "s46":"014600283000CA8D","s10":"011000287182943B",
        "s9a":"019A0000000018000000000000000000DC69",
        "version" : "18.05"
}]);

// and use $json in loop to populate the table...
</code>```

that pair of square brackets does not let me do anything with it in php. My editor show an parse error. I solved this problem in js like this:

```<code>var data = json[0];
var i;
for(i=0; i<json.length; i++){
    var html = '';
    html += '<td>' + json[i]["key"] + '</td>'
    + '<td>' + json[i]["ticks"] + '</td>'
    + '<td>' + json[i]["events"] + '</td>'
    + '<td>' + json[i]["s1a"] + '</td>'
    + '<td>' + json[i]["s1c"] + '</td>'
    + '<td>' + json[i]["s46"] + '</td>'
    + '<td>' + json[i]["s9a"] + '</td>'
    + '<td>' + json[i]["version"] + '</td>';
}
    $(html).appendTo('#bundle');
//var jsonEncoded = JSON.parse(data);
console.log(json.length);*/
</code>```

But it seems bad to use it like this. How can I solve this in php?

答:
you can simply use json_decode for this in PHP, Like:

```<code><?php
$data = json_decode($json);
var_dump($data[0]->key);
var_dump($data[0]->events);
</code>```

And you can access them simply by using the index 0. Demo

Edit: The problem with your code is that your are not enclosing the json string in quotations. You should use it like this:

```<code>$json = json_decode('[{
"key":1812,
        "ticks":0,
        "events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
        "s1a":"011A00002066C0D9",
        "s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
        "s46":"014600283000CA8D","s10":"011000287182943B",
        "s9a":"019A0000000018000000000000000000DC69",
        "version" : "18.05"
}]');
</code>```

Title: why json response has square brackets

Body:
For some reason I have to use JSON like this:

php code

$json = json_decode([{
"key":1812,
        "ticks":0,
        "events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
        "s1a":"011A00002066C0D9",
        "s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
        "s46":"014600283000CA8D","s10":"011000287182943B",
        "s9a":"019A0000000018000000000000000000DC69",
        "version" : "18.05"
}]);

// and use $json in loop to populate the table...

that pair of square brackets does not let me do anything with it in php. My editor show an parse error. I solved this problem in js like this:

var data = json[0];
var i;
for(i=0; i<json.length; i++){
    var html = '';
    html += '' + json[i]["key"] + '	'
    + '' + json[i]["ticks"] + '	'
    + '' + json[i]["events"] + '	'
    + '' + json[i]["s1a"] + '	'
    + '' + json[i]["s1c"] + '	'
    + '' + json[i]["s46"] + '	'
    + '' + json[i]["s9a"] + '	'
    + '' + json[i]["version"] + '	';
}
    $(html).appendTo('#bundle');
//var jsonEncoded = JSON.parse(data);
console.log(json.length);*/

But it seems bad to use it like this. How can I solve this in php?

Body:
you can simply use json_decode for this in PHP, Like:

<?php
$data = json_decode($json);
var_dump($data[0]->key);
var_dump($data[0]->events);

And you can access them simply by using the index 0. Demo

Edit: The problem with your code is that your are not enclosing the json string in quotations. You should use it like this:

$json = json_decode('[{
"key":1812,
        "ticks":0,
        "events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
        "s1a":"011A00002066C0D9",
        "s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
        "s46":"014600283000CA8D","s10":"011000287182943B",
        "s9a":"019A0000000018000000000000000000DC69",
        "version" : "18.05"
}]');


问:
nginx redirect all domain to another port but keep one domain for admin apps
I try to setup a web server with Docker, so I will use the main domain of my server "server.domain.com" for admin use (server.domain.com/phpmyadmin, ect...) and I want to redirect all the other domain to an apache container who listen on port 81.

So I have this code on my default.conf:

```<code>server {
    listen 80;
    listen [::]:80 default_server;

    location / {
       proxy_pass  http://web/;
    }
}
</code>```

main.conf:

```<code>server {
    listen 80;
    listen [::]:80;

    server_name server.domain.com;

    location /phpmyadmin/ {
       proxy_pass http://phpmyadmin/;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
</code>```

(Updated conf)

And my nginx.conf:

```<code>user  nginx;
worker_processes  2;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;
    gzip_comp_level   5;
    gzip_http_version 1.0;
    gzip_min_length   0;
    gzip_types        *;
    gzip_vary         on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites/*;
}
</code>```

a part of ‘docker-compose.yml‘:

```<code>nginx:
    build: ./server/proxy
    ports:
        - "80:80"
    #volumes:
       #- nginx_conf:/etc/nginx/
    networks:
        - web_network
    depends_on:
        - web
        - phpmyadmin
        - panel
</code>```

At this moment I use "depends_on" for use the name of the container on my config but you talk only about network so I think "depends_on" is not obliged ?

But that gives me an error connection refused.
If I replace the 127.0.0.1 by server.domain.com the first vhost not working and redirect to nginx webRoot.

So I have no idea why ...

Thank you !

答:
As far as I understand this nginx container is listening on port 80 and all connection requests going to your machine will be passed to it. So it's a proxy container only. I have a project with similar implementation. Let's try to make it out.

I suggest that you have 2 conf files for clarity.

1) main.conf -  will serve your "server.domain.com"

```<code>server {
    listen 80;
    listen [::]:80;

    server_name server.domain.com;

    location /phpmyadmin {
       proxy_pass http://server.domain.com:82;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

That's all of the configuration you basically need here. Later if you need them, you'll pass headers.
</code>```

2) default.conf - will serve any other domain

```<code>server {
    listen 80;
    listen [::]:80 default_server;

    location / {
       proxy_pass  http://server.domain.com:81;
    }
}
</code>```

This configuration assumes that:

1) There is a container running apache and requests coming to your machine on port 81 will be passed to apache2 container's port 80 (or whatever it's listening to)

2) There is a container running phpmyadmin and requests coming to your machine on port 82 will be passed to phpmyadmin container's port 80 (or whatever...)

SOME IMPROVEMENTS YOU SHOULD CONSIDER:

1) If you start all those containers with docker-compose you'll be able to set up a virtual network for them. This would allow you to proxy pass requests straight to the container by name. In my project I do it like:

```<code>proxy_pass http://adminer;
</code>```

where adminer is defined as:

```<code>adminer:
    image: phpmyadmin/phpmyadmin
    volumes:
        - ./db_interface/conf/config.inc.php/:/etc/phpmyadmin/config.inc.php
    networks:
     - demo_webnet
     - prod_webnet
</code>```

If you have questions just ask, I'll explain.

2) You could place another nginx server together with your apache2 server in its container. They work nice in bundle. Nginx is better to server statics. Apache2 better suits PHP in your case. I can show you how to do that as well.

IN CASE YOU NEED IT

It looks like you're trying to do something similar to what I did for our company's needs. If you're interested I can give you access to my project. I've built up a whole server infrastructure with docker and it now perfectly deployed on our server. In short it works as follows:

nginx proxy container above all

a container with apache2-nginx-php5.6 for demo apps

a container with apache2-nginx-php7.0 for demo apps

a container with apache2-nginx-php5.6 for production apps

a container with apache2-nginx-php7.0 for production apps

a container with maria db for demo

a container with maria db for production

a container with phpmyadmin to access both db services

Any request comes to nginx proxy.

It matches some virtual host and gets proxied to one of the 4 containers that have apache2 and nginx inside.

Also there is a lot of cool stuff like cron configured to autoreload apache2 and nginx when it detects changes to files, supervising services, https support and so on..

I'm planning to further develop it as an open source project, whoever is interested should let me know.

Body:
I try to setup a web server with Docker, so I will use the main domain of my server "server.domain.com" for admin use (server.domain.com/phpmyadmin, ect...) and I want to redirect all the other domain to an apache container who listen on port 81.

So I have this code on my default.conf:

server {
    listen 80;
    listen [::]:80 default_server;

    location / {
       proxy_pass  http://web/;
    }
}

main.conf:

server {
    listen 80;
    listen [::]:80;

    server_name server.domain.com;

    location /phpmyadmin/ {
       proxy_pass http://phpmyadmin/;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

(Updated conf)

And my nginx.conf:

user  nginx;
worker_processes  2;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;
    gzip_comp_level   5;
    gzip_http_version 1.0;
    gzip_min_length   0;
    gzip_types        *;
    gzip_vary         on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites/*;
}

a part of ‘docker-compose.yml‘:

nginx:
    build: ./server/proxy
    ports:
        - "80:80"
    #volumes:
       #- nginx_conf:/etc/nginx/
    networks:
        - web_network
    depends_on:
        - web
        - phpmyadmin
        - panel

At this moment I use "depends_on" for use the name of the container on my config but you talk only about network so I think "depends_on" is not obliged ?

But that gives me an error connection refused.
If I replace the 127.0.0.1 by server.domain.com the first vhost not working and redirect to nginx webRoot.

So I have no idea why ...

Thank you !

Body:
As far as I understand this nginx container is listening on port 80 and all connection requests going to your machine will be passed to it. So it's a proxy container only. I have a project with similar implementation. Let's try to make it out.

I suggest that you have 2 conf files for clarity.

1) main.conf -  will serve your "server.domain.com"

server {
    listen 80;
    listen [::]:80;

    server_name server.domain.com;

    location /phpmyadmin {
       proxy_pass http://server.domain.com:82;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

That's all of the configuration you basically need here. Later if you need them, you'll pass headers.

2) default.conf - will serve any other domain

server {
    listen 80;
    listen [::]:80 default_server;

    location / {
       proxy_pass  http://server.domain.com:81;
    }
}

This configuration assumes that:

1) There is a container running apache and requests coming to your machine on port 81 will be passed to apache2 container's port 80 (or whatever it's listening to)

2) There is a container running phpmyadmin and requests coming to your machine on port 82 will be passed to phpmyadmin container's port 80 (or whatever...)

SOME IMPROVEMENTS YOU SHOULD CONSIDER:

1) If you start all those containers with docker-compose you'll be able to set up a virtual network for them. This would allow you to proxy pass requests straight to the container by name. In my project I do it like:

proxy_pass http://adminer;

where adminer is defined as:

adminer:
    image: phpmyadmin/phpmyadmin
    volumes:
        - ./db_interface/conf/config.inc.php/:/etc/phpmyadmin/config.inc.php
    networks:
     - demo_webnet
     - prod_webnet

If you have questions just ask, I'll explain.

2) You could place another nginx server together with your apache2 server in its container. They work nice in bundle. Nginx is better to server statics. Apache2 better suits PHP in your case. I can show you how to do that as well.

IN CASE YOU NEED IT

It looks like you're trying to do something similar to what I did for our company's needs. If you're interested I can give you access to my project. I've built up a whole server infrastructure with docker and it now perfectly deployed on our server. In short it works as follows:

nginx proxy container above all

a container with apache2-nginx-php5.6 for demo apps

a container with apache2-nginx-php7.0 for demo apps

a container with apache2-nginx-php5.6 for production apps

a container with apache2-nginx-php7.0 for production apps

a container with maria db for demo

a container with maria db for production

a container with phpmyadmin to access both db services

Any request comes to nginx proxy.

It matches some virtual host and gets proxied to one of the 4 containers that have apache2 and nginx inside.

Also there is a lot of cool stuff like cron configured to autoreload apache2 and nginx when it detects changes to files, supervising services, https support and so on..

I'm planning to further develop it as an open source project, whoever is interested should let me know.


问:
Error loading PHP modules
I'm running PHP 5.2.8 on Apache 2.2.11 on Windows XP SP 3. In php.ini,

```<code>extension_dir = "C:\Program Files\PHP\ext"
extension=php_mysql.dll
</code>```

In error.log:

```<code>PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\\Program Files\\PHP\\ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0
</code>```

php_mysql.dll is definately located in the extension_dir, and is the version that PHP 5.2.8 is bundled with. What's up?

答:
Try adding a trailing slash to your extension_dir path.

This is what I am using in my WAMP setup:

```<code>extension_dir = "D:\php\ext\"
; ...snip...
extension=php_gd2.dll
</code>```

Title: Error loading PHP modules

Body:
I'm running PHP 5.2.8 on Apache 2.2.11 on Windows XP SP 3. In php.ini,

extension_dir = "C:\Program Files\PHP\ext"
extension=php_mysql.dll

In error.log:

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\\Program Files\\PHP\\ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0

php_mysql.dll is definately located in the extension_dir, and is the version that PHP 5.2.8 is bundled with. What's up?

Body:
Try adding a trailing slash to your extension_dir path.

This is what I am using in my WAMP setup:

extension_dir = "D:\php\ext\"
; ...snip...
extension=php_gd2.dll

OwnerDisplayName: Ross


问:
How can I test my international IP detection script?
I want to test my international IP detection script on my web site.  How do I setup a proxy so that my web site thinks that I am coming from a foreign iP?  Specifically in this case I'm looking to test from Canada, Germany, UK and France.</p>

答:
Just use a web proxy from any of these countries and point it at your site/script.

Here is a list of many free web proxies - there is a breakdown by country. Canada, Germany, UK and France are all on the list.


问:
'No such file or directory' yet it exists?
I am relatively new to Stack Overflow and Python so please excuse me.
I ran into an issue with Jupyter trying to open my notebook.  Specifically, this error is:

```<code>Unreadable Notebook: /home/vagrant/Notebook 1.ipynb NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n {\\n "cell_type": "...',)
</code>```

I am trying to recover this file as it is pretty crucial!  I discovered there is hidden folder accessible by the terminal called .ipynb_checkpoints and after listing all contents in this folder I am presented with this.

```<code>-rw-rw-r-- 1 vagrant vagrant 656710 Dec  6 17:25 Notebook 1-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant  26332 Oct 19 21:47 Lab08-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant     72 Nov 17 16:35 Untitled-checkpoint.ipynb
</code>```

The top one Notebook 1-checkpoint.ipynb is the file I would like to recover.  Can anyone please help me with this?

When I try to do this:

```<code>cp Notebook 1-checkpoint.ipynb /home/vagrant/Desktop/
</code>```

I am presented with this:

```<code>cp: cannot stat ‘Notebook’: No such file or directory
cp: cannot stat ‘1-checkpoint.ipynb’: No such file or directory
</code>```

答: Your command should be cp 40126684_Notebook\ 1-checkpoint.ipynb /home/vagrant/Desktop/

Body:
I am relatively new to Stack Overflow and Python so please excuse me.
I ran into an issue with Jupyter trying to open my notebook.  Specifically, this error is:

Unreadable Notebook: /home/vagrant/Notebook 1.ipynb NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n {\\n "cell_type": "...',)

I am trying to recover this file as it is pretty crucial!  I discovered there is hidden folder accessible by the terminal called .ipynb_checkpoints and after listing all contents in this folder I am presented with this.

-rw-rw-r-- 1 vagrant vagrant 656710 Dec  6 17:25 Notebook 1-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant  26332 Oct 19 21:47 Lab08-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant     72 Nov 17 16:35 Untitled-checkpoint.ipynb

The top one Notebook 1-checkpoint.ipynb is the file I would like to recover.  Can anyone please help me with this?

When I try to do this:

cp Notebook 1-checkpoint.ipynb /home/vagrant/Desktop/

I am presented with this:

cp: cannot stat ‘Notebook’: No such file or directory
cp: cannot stat ‘1-checkpoint.ipynb’: No such file or directory


问:
using python commenting xml tags
for the below xml file , how can i comment(in xml) the heading tag including its children using python ? i am new to python , tried using lxml but only able to add a new comment, not able to comment existing tags. please do help , thanks in advance

```<code><note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
<body>Don't forget me this weekend!</body>
</note>
</code>```

i would want the output to be like

```<code><note>
<to>Tove</to>
<from>Jani</from>
<!--  <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>
</code>```

答:
Here's an example using the built-in ElementTree library and your xml sample as the input file:

```<code>from xml.etree import ElementTree as et

tree = et.parse('test.xml')
note = tree.getroot()

# Locate the heading and preserve the whitespace after the closing tag
heading = note.find('heading')
tail = heading.tail

# Generate the comment string with a space before and after it.
heading.tail = ' '
heading_comment = ' ' + et.tostring(heading,'unicode')

# Generate the comment node with the text of the commented out node and its original whitespace tail.
comment = et.Comment(heading_comment)
comment.tail = tail

# Locate the location in the child list of the heading node,
# remove it, and replace with the comment node.
index = note.getchildren().index(heading)
note.remove(heading)
note.insert(index,comment)

tree.write('out.xml')
</code>```

Output file:

```<code><note>
<to>Tove</to>
<from>Jani</from>
<!-- <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>
</code>```

Title: using python commenting xml tags

Body:
for the below xml file , how can i comment(in xml) the heading tag including its children using python ? i am new to python , tried using lxml but only able to add a new comment, not able to comment existing tags. please do help , thanks in advance

<note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
Don't forget me this weekend!
</note>

i would want the output to be like

<note>
<to>Tove</to>
<from>Jani</from>

Don't forget me this weekend!
</note>

Body:
Here's an example using the built-in ElementTree library and your xml sample as the input file:

from xml.etree import ElementTree as et

tree = et.parse('test.xml')
note = tree.getroot()

# Locate the heading and preserve the whitespace after the closing tag
heading = note.find('heading')
tail = heading.tail

# Generate the comment string with a space before and after it.
heading.tail = ' '
heading_comment = ' ' + et.tostring(heading,'unicode')

# Generate the comment node with the text of the commented out node and its original whitespace tail.
comment = et.Comment(heading_comment)
comment.tail = tail

# Locate the location in the child list of the heading node,
# remove it, and replace with the comment node.
index = note.getchildren().index(heading)
note.remove(heading)
note.insert(index,comment)

tree.write('out.xml')

Output file:

<note>
<to>Tove</to>
<from>Jani</from>
<!-- <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>