问:
Jsp iterate through object list
I'm having troubles iterating with jsp trough list/lists. Here is my object class called Table:

```<code>public class Table{

private String name;
private List<String> columns;
private List<Row> rows;

... continuing with getters and setters nothing more here

}
</code>```

In my Row class I have just Strings(ex: String name), no lists no nothing.

Currently I have some List
 and I'm iterating trough it like this:

```<code><c:forEach var='table' items='${requestScope.tables}'>
        <c:out value="{table.name}"></c:out>
</c:forEach>
</code>```

Just for testing .. and it prints just {table.name} x times(the correct number of table objects in the table list).

My final goal is something like this (pseudo code):

```<code>for each table in table list
     print name
     for each column in colum list
         print column
     end column list for
     for each Row in row list
         print Row.name
     end row list for
end table list for
</code>```

Could someone help me out with syntax?

答:
You forgot the dollar sign - ${table.name}

Also, you should use double-quotes: var="table"

ContentLicense: CC BY-SA 4.0

Title: Jsp iterate through object list

Body:
I'm having troubles iterating with jsp trough list/lists. Here is my object class called Table:

public class Table{

private String name;
private List<String> columns;
private List<Row> rows;

... continuing with getters and setters nothing more here

}

In my Row class I have just Strings(ex: String name), no lists no nothing.

Currently I have some List
 and I'm iterating trough it like this:

<c:forEach var='table' items='${requestScope.tables}'>
        <c:out value="{table.name}"></c:out>
</c:forEach>

Just for testing .. and it prints just {table.name} x times(the correct number of table objects in the table list).

My final goal is something like this (pseudo code):

for each table in table list
     print name
     for each column in colum list
         print column
     end column list for
     for each Row in row list
         print Row.name
     end row list for
end table list for

Could someone help me out with syntax?


来源: stackexchange

问:
How do I spawn parallel threads on different devices?
I want to run some threads on my CPU ( the localhost host ) and some other on a portable device connected ( like a USB ).

I know that OpenCL supports parallelization, but how do I distribute a work onto a portable devices using OpenCL?

Any other idea to do this other than OpenCL would also help.

答:
Any device which might run an OpenCL task must have an Installable Client Driver associated with it, which can be picked up by the OpenCL Driver on the computer in question. Graphics Cards (especially if they're no older than half a decade) are nearly guaranteed to have a valid ICD, provided their drivers are up-to-date, and many Consumer-level CPUs have ICDs that are provided by their drivers.

However, other devices like a Network Device or a USB device are considerably less guaranteed to have a valid ICD unless they've been specifically designed for use in a Heterogeneous Compute system. If they do have a valid ICD, then it's a mere matter of querying for their platform at runtime and choosing it to use when constructing your OpenCL Context, then using it the same way you'd use OpenCL normally:

```<code>//C++ OpenCL API
cl::Platform target_platform;
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for(cl::Platform & platform : platforms) {
    std::string name = platform.getInfo<CL_PLATFORM_NAME>();
    if(name == /*Whatever the Name of the platform is*/) {
        target_platform = platform;
        break;
    }
}
std::vector<cl::Device> devices;
target_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
cl::Device target_device;
for(cl::Device & device : devices) {
    if(device.getInfo</*...*/>() == /*...*/) {//Whatever properties you need
        target_device = device;
        break;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Any device which might run an OpenCL task must have an Installable Client Driver associated with it, which can be picked up by the OpenCL Driver on the computer in question. Graphics Cards (especially if they're no older than half a decade) are nearly guaranteed to have a valid ICD, provided their drivers are up-to-date, and many Consumer-level CPUs have ICDs that are provided by their drivers.

However, other devices like a Network Device or a USB device are considerably less guaranteed to have a valid ICD unless they've been specifically designed for use in a Heterogeneous Compute system. If they do have a valid ICD, then it's a mere matter of querying for their platform at runtime and choosing it to use when constructing your OpenCL Context, then using it the same way you'd use OpenCL normally:

//C++ OpenCL API
cl::Platform target_platform;
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for(cl::Platform & platform : platforms) {
    std::string name = platform.getInfo<CL_PLATFORM_NAME>();
    if(name == /*Whatever the Name of the platform is*/) {
        target_platform = platform;
        break;
    }
}
std::vector<cl::Device> devices;
target_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
cl::Device target_device;
for(cl::Device & device : devices) {
    if(device.getInfo</*...*/>() == /*...*/) {//Whatever properties you need
        target_device = device;
        break;
    }
}


问:
JS- Traverse object
I have a javascript object that has nested objects as properties. I would like to traverse this javascript object, to get a list of all the properties of every object inside the object.

I wrote a function to do this, but for some reason when I run the function I get an infinite loop of 0's. Does anyone know how the reason and solution for this issue?

```<code>var test = {a: {b: { c: 'value '}}};

var traverse = function(object){
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
        console.log(property);
        traverse(object[property])
    }else {
      console.log('None');
      break;
    }
  }
}
traverse(test);
</code>```

答:
You have a string at the end and this string is separated into a single characters with one index zero. From this string, the character at position zero is taken and the recursion is called again with a single character.

```<code> key          value           comment
-----  -------------------  -----------
  a    {
           b: {
               c: "value "
           }
       }

  b    {
           c: "value "
       }

  c    "value "

  0    "v"
  0    "v"
  0    "v"                  and so on
</code>```

This character has an index zero and so on.

To prevent such habit, you could check for onyl truthy values (prevent null) and type of objects to get traversed.

var test = { a: { b: { c: 'value ' } } };

var traverse = function (object) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            console.log(property);
            if (object[property] && typeof object[property] === 'object') {
                traverse(object[property]);
            }
        } else {
            console.log('None');
        }
    }
}
traverse(test);```

Title: JS- Traverse object

Body:
I have a javascript object that has nested objects as properties. I would like to traverse this javascript object, to get a list of all the properties of every object inside the object.

I wrote a function to do this, but for some reason when I run the function I get an infinite loop of 0's. Does anyone know how the reason and solution for this issue?

var test = {a: {b: { c: 'value '}}};

var traverse = function(object){
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
        console.log(property);
        traverse(object[property])
    }else {
      console.log('None');
      break;
    }
  }
}
traverse(test);

Body:
You have a string at the end and this string is separated into a single characters with one index zero. From this string, the character at position zero is taken and the recursion is called again with a single character.

 key          value           comment
-----  -------------------  -----------
  a    {
           b: {
               c: "value "
           }
       }

  b    {
           c: "value "
       }

  c    "value "

  0    "v"
  0    "v"
  0    "v"                  and so on

This character has an index zero and so on.

To prevent such habit, you could check for onyl truthy values (prevent null) and type of objects to get traversed.

var test = { a: { b: { c: 'value ' } } };

var traverse = function (object) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            console.log(property);
            if (object[property] && typeof object[property] === 'object') {
                traverse(object[property]);
            }
        } else {
            console.log('None');
        }
    }
}
traverse(test);


问:
JavaScript function wrapped in TypeScript function is not working
I am trying to implement a datepicker whose button upon being clicked displays a calendar. For this purpose, I have wrapped datepicker() (JavaScript function) in pickDate() (user defined TypeScript function) but the button is not clicking/displaying anything. What could be going wrong?

Below are my code snippets

HTML file

          <input type='text' class="form-control" />

```

<p><strong>.ts file</strong></p>

```import {Component} from '@angular/core';
import * as $ from 'jquery';

@Component({
    selector : 'pm-datepicker', /** This is a directive which implies this Component's template can be
    used as any other Component's template.  */
    templateUrl : './datepicker.component.html' /** Path to our HTML file */
})

export class DatePickerComponent {

    pickDate() {
        console.log(5); /** To check if something is logging */
        $('#datetimepicker1').datepicker();
    }
}
```

<p><strong>Errors on console</strong></p>

```ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).datepicker is not a function
    at DatePickerComponent.webpackJsonp.../../../../../src/app/datepicker/datepicker.component.ts.DatePickerComponent.pickDate (datepicker.component.ts:18)
    at Object.eval [as handleEvent] (DatePickerComponent.html:21)
    at handleEvent (core.es5.js:11998)
    at callWithDebugContext (core.es5.js:13467)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
    at dispatchEvent (core.es5.js:8614)
    at core.es5.js:9228
    at HTMLSpanElement.<anonymous> (platform-browser.es5.js:2648)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
```

<p><strong>Edit 2</strong></p>

<p>I carried out the following steps : </p>

```npm install jquery-ui --save
```

and then I included the script URLs with respect to jQuery and jQuery-ui in index.html but the errors still persist. Is there anything specifically I need to import in my component.ts or app.module.ts?

答:
Looks like you're going to need to include $.datepicker to get that function. Since it seems you're using webpack, this should be a simple
npm install jquery-ui to get the whole jquery-ui package or npm install jquery-datepicker to just get the datepicker module.

You'll also need to include this in your source before you use it (or add it as an entry point to webpack).

Body:
I am trying to implement a datepicker whose button upon being clicked displays a calendar. For this purpose, I have wrapped datepicker() (JavaScript function) in pickDate() (user defined TypeScript function) but the button is not clicking/displaying anything. What could be going wrong?

Below are my code snippets

HTML file

          <input type='text' class="form-control" />

.ts file

import {Component} from '@angular/core';
import * as $ from 'jquery';

@Component({
    selector : 'pm-datepicker', /** This is a directive which implies this Component's template can be
    used as any other Component's template.  */
    templateUrl : './datepicker.component.html' /** Path to our HTML file */
})

export class DatePickerComponent {

    pickDate() {
        console.log(5); /** To check if something is logging */
        $('#datetimepicker1').datepicker();
    }
}

Errors on console

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).datepicker is not a function
    at DatePickerComponent.webpackJsonp.../../../../../src/app/datepicker/datepicker.component.ts.DatePickerComponent.pickDate (datepicker.component.ts:18)
    at Object.eval [as handleEvent] (DatePickerComponent.html:21)
    at handleEvent (core.es5.js:11998)
    at callWithDebugContext (core.es5.js:13467)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
    at dispatchEvent (core.es5.js:8614)
    at core.es5.js:9228
    at HTMLSpanElement.<anonymous> (platform-browser.es5.js:2648)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)

Edit 2

I carried out the following steps :

npm install jquery-ui --save

and then I included the script URLs with respect to jQuery and jQuery-ui in index.html but the errors still persist. Is there anything specifically I need to import in my component.ts or app.module.ts?


问:
How to overwrite a point in memory in c#?
I want to do have the following functionality:

```<code>var item0 = new Item();
var item1 = item0;
item0 = null;

Console.WriteLine(item1 == null); // true
</code>```

So I'd be overwriting the memory that item0 and item1 point to.
I figured maybe I could do this with pointers..? However, when I tried declaring an item pointer:

```<code>Item* itemPointer;
</code>```

i got an error. Any ideas?

答:
There are no local aliases/references in C#
However there is a ref keyword for arguments:

```<code>static void RefClean(ref String arg){
    arg = null;
}
static void Main(string[] args)
{
    var test = "Hello";
    Console.WriteLine(test == null);
    RefClean(ref test);
    Console.WriteLine(test == null);
}
</code>```

For pointers you need the unsafe keyword, and you have to use unmanaged types only (primitive types and structures built from them), which rules out your case with objects/references. See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/pointer-types for some overview.

Body:
I want to do have the following functionality:

var item0 = new Item();
var item1 = item0;
item0 = null;

Console.WriteLine(item1 == null); // true

So I'd be overwriting the memory that item0 and item1 point to.
I figured maybe I could do this with pointers..? However, when I tried declaring an item pointer:

Item* itemPointer;

i got an error. Any ideas?

Body:
There are no local aliases/references in C#
However there is a ref keyword for arguments:

static void RefClean(ref String arg){
    arg = null;
}
static void Main(string[] args)
{
    var test = "Hello";
    Console.WriteLine(test == null);
    RefClean(ref test);
    Console.WriteLine(test == null);
}

For pointers you need the unsafe keyword, and you have to use unmanaged types only (primitive types and structures built from them), which rules out your case with objects/references. See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/pointer-types for some overview.


问:
How to get the file name and file size for the attachment of my custom post type
I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .

Here is my Meta Box code

```<code>function add_custom_meta_boxes() {

    // Define the custom attachment for posts
    add_meta_box(
        'wp_custom_attachment',
        'Custom Attachment',
        'wp_custom_attachment',
        'circular',
        'side'
    );

} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');

function wp_custom_attachment() {

    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

    $html = '<p class="description">';
        $html .= 'Upload your PDF here.';
    $html .= '</p>';
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';

    echo $html;

} // end wp_custom_attachment

function save_custom_meta_data($id) {

    /* --- security verification --- */
    if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
      return $id;
    } // end if

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $id;
    } // end if

    if('circular' == $_POST['post_type']) {
      if(!current_user_can('edit_page', $id)) {
        return $id;
      } // end if
    } else {
        if(!current_user_can('edit_page', $id)) {
            return $id;
        } // end if
    } // end if
    /* - end security verification - */

    // Make sure the file array isn't empty
    if(!empty($_FILES['wp_custom_attachment']['name'])) {

        // Setup the array of supported file types. In this case, it's just PDF.
        $supported_types = array('application/pdf');

        // Get the file type of the upload
        $arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
        $uploaded_type = $arr_file_type['type'];

        // Check if the type is supported. If not, throw an error.
        if(in_array($uploaded_type, $supported_types)) {

            // Use the WordPress API to upload the file
            $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));

            if(isset($upload['error']) && $upload['error'] != 0) {
                wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
            } else {
                add_post_meta($id, 'wp_custom_attachment', $upload);
                update_post_meta($id, 'wp_custom_attachment', $upload);
            } // end if/else

        } else {
            wp_die("The file type that you've uploaded is not a PDF.");
        } // end if/else

    } // end if

} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
</code>```

do out put the link of that file

```<code><?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
<a href="<?php echo $img['url']; ?>"> Download PDF Here</a>
</code>```

答:
If you can get the attachment ID number ($attachment_id below) you should be able to do something like this to get the name/size:

```<code>$attachment_id = 'YOUR_PDF_ID';
$attahment_file = get_attached_file( $attachment_id );

function getSize($file) {
    $bytes = filesize($file);
    $s = array('b', 'Kb', 'Mb', 'Gb');
    $e = floor(log($bytes)/log(1024));
    return sprintf( '%.2f ' . $s[$e], ( $bytes/pow( 1024, floor($e) ) ) );
}

echo '<p>Name: ' . basename( $attahment_file ) . '</p>';
echo '<p>Size: ' . getSize( $attahment_file ) . '</p>';
</code>```

I found the "getSize" function on another post here. It was more accurate than using the native PHP "filesize" function in terms of matching the size shown in the WP media library meta.

Body:
I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .

Here is my Meta Box code

function add_custom_meta_boxes() {

    // Define the custom attachment for posts
    add_meta_box(
        'wp_custom_attachment',
        'Custom Attachment',
        'wp_custom_attachment',
        'circular',
        'side'
    );

} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');

function wp_custom_attachment() {

    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

    $html = '
';
        $html .= 'Upload your PDF here.';
    $html .= '
';
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';

    echo $html;

} // end wp_custom_attachment

function save_custom_meta_data($id) {

    /* --- security verification --- */
    if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
      return $id;
    } // end if

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $id;
    } // end if

    if('circular' == $_POST['post_type']) {
      if(!current_user_can('edit_page', $id)) {
        return $id;
      } // end if
    } else {
        if(!current_user_can('edit_page', $id)) {
            return $id;
        } // end if
    } // end if
    /* - end security verification - */

    // Make sure the file array isn't empty
    if(!empty($_FILES['wp_custom_attachment']['name'])) {

        // Setup the array of supported file types. In this case, it's just PDF.
        $supported_types = array('application/pdf');

        // Get the file type of the upload
        $arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
        $uploaded_type = $arr_file_type['type'];

        // Check if the type is supported. If not, throw an error.
        if(in_array($uploaded_type, $supported_types)) {

            // Use the WordPress API to upload the file
            $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));

            if(isset($upload['error']) && $upload['error'] != 0) {
                wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
            } else {
                add_post_meta($id, 'wp_custom_attachment', $upload);
                update_post_meta($id, 'wp_custom_attachment', $upload);
            } // end if/else

        } else {
            wp_die("The file type that you've uploaded is not a PDF.");
        } // end if/else

    } // end if

} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');

do out put the link of that file

<?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
<a href="<?php echo $img['url']; ?>"> Download PDF Here

Body:
If you can get the attachment ID number ($attachment_id below) you should be able to do something like this to get the name/size:

$attachment_id = 'YOUR_PDF_ID';
$attahment_file = get_attached_file( $attachment_id );

function getSize($file) {
    $bytes = filesize($file);
    $s = array('b', 'Kb', 'Mb', 'Gb');
    $e = floor(log($bytes)/log(1024));
    return sprintf( '%.2f ' . $s[$e], ( $bytes/pow( 1024, floor($e) ) ) );
}

echo '<p>Name: ' . basename( $attahment_file ) . '</p>';
echo '<p>Size: ' . getSize( $attahment_file ) . '</p>';

I found the "getSize" function on another post here. It was more accurate than using the native PHP "filesize" function in terms of matching the size shown in the WP media library meta.


问:
jQuery attach same event to many id
My question is: How to attach the same series of events to many id's

in this case I'm attaching all of this code to "#employeeBox"

```<code>$("#employeeBox").autocomplete({
                                source: function (request, response) {
                                    $.ajax({
                                        url: '<%:ResolveUrl("~/Lookup/SearchEnterpriseUsers")%>',
                                        dataType: "json",
                                        data: {
                                            featureClass: "P",
                                            style: "full",
                                            maxRows: 12,
                                            nameLike: request.term
                                        },
                                        success: function (data) {
                                            response($.map(data, function (item) {
                                                return {
                                                    label: item.FullName,
                                                    value: item.EmployeeId
                                                }
                                            }))
                                        }
                                    })
                                },
                                minLength: 2,
                                select: function (event, ui) {
                                    alert(ui.item.value)
                                },
                                open: function () {
                                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                                },
                                close: function () {
                                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                                }
                            });
</code>```

What if I want to attach it to many id's.

Like

```<code>for (int i=0; i < count; i++)
"#employee_" + i + "_Box"
</code>```

what's the best way to do this without a lot of repeated code?

thanks!

答: If you gave them all a class of employeeBox you could just do $('.employeeBox').autocomplete().</p>

ContentLicense: CC BY-SA 2.5

Title: jQuery attach same event to many id

Body:
My question is: How to attach the same series of events to many id's

in this case I'm attaching all of this code to "#employeeBox"

$("#employeeBox").autocomplete({
                                source: function (request, response) {
                                    $.ajax({
                                        url: '<%:ResolveUrl("~/Lookup/SearchEnterpriseUsers")%>',
                                        dataType: "json",
                                        data: {
                                            featureClass: "P",
                                            style: "full",
                                            maxRows: 12,
                                            nameLike: request.term
                                        },
                                        success: function (data) {
                                            response($.map(data, function (item) {
                                                return {
                                                    label: item.FullName,
                                                    value: item.EmployeeId
                                                }
                                            }))
                                        }
                                    })
                                },
                                minLength: 2,
                                select: function (event, ui) {
                                    alert(ui.item.value)
                                },
                                open: function () {
                                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                                },
                                close: function () {
                                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                                }
                            });

What if I want to attach it to many id's.

Like

for (int i=0; i < count; i++)
"#employee_" + i + "_Box"

what's the best way to do this without a lot of repeated code?

thanks!


问:
Proxy detection in Python3
The script below works fine when I am using script at home (same PC!):

```<code>import urllib.request

x = urllib.request.urlopen('https://www.google.com/')
print(x.read())
</code>```

the same does not work using the same script when I am connected at work. I do not know proxy address or IP, so my script should use the same way as IE or anything else on this PC.

I found some suggestions about using proxy , but the point it I do not know proxy IP or details. When I move the script to another PC it might have different proxy, so I think hardcoding it is not good approach.
Can I somehow inform Python to autodetect proxy settings?

答:
Going by your eample, I am assuming you are doing a https call over proxy. The urllib documentation hints its not supported. So, instead you may have to settle down with http.

In order to validate that there is nothing wrong with your setup, you may try to do open the IP directly:

```<code>
    import urllib
    # IP address for `http://www.google.com` is `216.58.205.196`
    x = urllib.urlopen('http://216.58.205.196')
    print x.read()
</code>
```

A. There are lots of complaints about Python's trippy auto-detect proxy settings in various other threads. I had this issue only once years ago and I opted for setting a fixed proxy instead of trying to configure auto-detect. To know your proxy, you can go to chrome url chrome://net-internals/#proxy or run netstat -an | grep EST command.

B. Once you have proxy address, you can use following code:

```<code>
    import urllib
    # IP address for `http://www.google.com` is `216.58.205.196`
    x = urllib.urlopen('http://216.58.205.196',
                        proxies={'http': 'http://www.someproxy.com:3128'})
    print x.read()
</code>
```

If you cannot avoid https, then you may consider requests library. I didn't test this, but requests documentation looks quite promising. This is how it can be done!

```
<code>
    import requests
    proxies = {
      'http': 'http://10.10.1.10:3128',
      'https': 'http://10.10.1.10:1080',
    }
    requests.get('https://example.org', proxies=proxies)
</code>```

Edit:

1: You may need to setup proxy authentication in order for 3.B. to work

2: For Special characters, you would need to have the password in unicode: 'p@ssw0rd'.decode('utf-8')

Hope this helps!

Title: Proxy detection in Python3

Body:
The script below works fine when I am using script at home (same PC!):

import urllib.request

x = urllib.request.urlopen('https://www.google.com/')
print(x.read())

the same does not work using the same script when I am connected at work. I do not know proxy address or IP, so my script should use the same way as IE or anything else on this PC.

I found some suggestions about using proxy , but the point it I do not know proxy IP or details. When I move the script to another PC it might have different proxy, so I think hardcoding it is not good approach.
Can I somehow inform Python to autodetect proxy settings?

Body:
Going by your eample, I am assuming you are doing a https call over proxy. The urllib documentation hints its not supported. So, instead you may have to settle down with http.

In order to validate that there is nothing wrong with your setup, you may try to do open the IP directly:

    import urllib
    # IP address for `http://www.google.com` is `216.58.205.196`
    x = urllib.urlopen('http://216.58.205.196')
    print x.read()

A. There are lots of complaints about Python's trippy auto-detect proxy settings in various other threads. I had this issue only once years ago and I opted for setting a fixed proxy instead of trying to configure auto-detect. To know your proxy, you can go to chrome url chrome://net-internals/#proxy or run netstat -an | grep EST command.

B. Once you have proxy address, you can use following code:

    import urllib
    # IP address for `http://www.google.com` is `216.58.205.196`
    x = urllib.urlopen('http://216.58.205.196',
                        proxies={'http': 'http://www.someproxy.com:3128'})
    print x.read()

If you cannot avoid https, then you may consider requests library. I didn't test this, but requests documentation looks quite promising. This is how it can be done!

    import requests
    proxies = {
      'http': 'http://10.10.1.10:3128',
      'https': 'http://10.10.1.10:1080',
    }
    requests.get('https://example.org', proxies=proxies)

Edit:

1: You may need to setup proxy authentication in order for 3.B. to work

2: For Special characters, you would need to have the password in unicode: 'p@ssw0rd'.decode('utf-8')

Hope this helps!


问:
Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation
Even though I manually configured JDK project structure file/Project structure it still shows this error
FAILURE: Build failed with an exception.

`What went wrong:
Execution failed for task ':sample:compileReleaseJavaWithJavac'.

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation.`

I'm confused why it is still looking for C:\Program Files\Java\jre1.8.0_151 instead of JDK

答:
At last, here I found the solution.

I added jdk path org.gradle.java.home=C\:\\Program Files\\Java\\jdk1.8.0_144 to gradle.properties file and did a rebuild. It works now.


问:
Nightwatch same Test with different website in Multilingual
I am facing a difficulty on Nightwatch :

I have several websites working on the same test script but language are different.

Therefore I create a Page for each language (UK, IT, FR ...)

the thing is I would like to call them like that :

```<code>"Nightwatch.js -t Test.js -e chrome -UK"
</code>```

and in my test get the language and connect to the page correspondent

any chance someone can help me do that?

Thank you very much for any help on that issue!

答:
I guess you can create a custom command that can retrieve the command values (using native process.argv or argv npm plugin) and format your url as desired. So your command can look like something like this:

```<code>"Nightwatch.js -t Test.js -e chrome --env=UK"
</code>```

and your custom command like this:

```<code>//this was made purely by memory, maybe it wont work
exports.command = navigate;
var environment = require("argv").argv["env"]
function navigate() {
  var pageUrl = `https://${environment}.google.com`; //format your url as desired
  this.url(landingUrl);
  return this;
}
</code>```

And finally in your tests you only have to call that custom command

Body:
I am facing a difficulty on Nightwatch :

I have several websites working on the same test script but language are different.

Therefore I create a Page for each language (UK, IT, FR ...)

the thing is I would like to call them like that :

"Nightwatch.js -t Test.js -e chrome -UK"

and in my test get the language and connect to the page correspondent

any chance someone can help me do that?

Thank you very much for any help on that issue!

Body:
I guess you can create a custom command that can retrieve the command values (using native process.argv or argv npm plugin) and format your url as desired. So your command can look like something like this:

"Nightwatch.js -t Test.js -e chrome --env=UK"

and your custom command like this:

//this was made purely by memory, maybe it wont work
exports.command = navigate;
var environment = require("argv").argv["env"]
function navigate() {
  var pageUrl = `https://${environment}.google.com`; //format your url as desired
  this.url(landingUrl);
  return this;
}

And finally in your tests you only have to call that custom command


问:
How to style an single individual selectInput menu in R Shiny?
Can you apply css style to a single selectInput menu?

I've found code in other articles that deal with styling selectInput menu's but the outcome affects all of them in the app. I would like to just manipulate individual menus.
I'm also considering adding style to individual elements based on conditionals happening in the server, but that's for another separate question.

test app code:

```<code>library(shiny)
library(shinydashboard)
library(shinyjs)
ui  <-
  fluidPage(
  hr("how do we get the change the style elements of a single select input?)
tags$style(type='text/css',  .selectize-input  { font-size: 8px; line-height: 8px;}
             .selectize-dropdown { font-size: 8px; line-height: 8px; }"),

    selectInput("choice", "choices", c("A", "B", "C")),

    selectInput("choice2", "choices", c("D", "E", "F"))
     )

server < - function(input, output, session) {   }
})
shinyApp(ui = ui, server = server)
</code>```

This approach comes straight from Dean Attali's answer here: examp, and a similar question is asked as final comment, but no answer, so I decided to post a question on the matter since I have the same problem.

for other elements likea textInput field, the way I usually do this is by this:

```<code>tags$style(type='text/css', "#NAMEELEMENT {background-color: green; height: 40px; border-color: #bfbfbf; width: 520px; position: relative;left: 3%}"),
</code>```

where you can attach the tag$style to an element by # and its inputId.

Cheers.

答:
Wrap your selectInput in a div:

```<code>tags$div(id='my_div',
         class='my_class',
         selectInput("choice",
                     "choices",
                      c("A", "B", "C"))),
</code>```

Then you can style it without affecting other selectInput elements:

```<code>#my_div .selectize-dropdown-content > .option {
   background-color: grey;
}
</code>```

or

```<code>.my_class .selectize-dropdown-content > .option {
   background-color: grey;
}
</code>```

As always with CSS, use id to name and to catch a single element, and  class to style multiple elements.

Body:
Can you apply css style to a single selectInput menu?

I've found code in other articles that deal with styling selectInput menu's but the outcome affects all of them in the app. I would like to just manipulate individual menus.
I'm also considering adding style to individual elements based on conditionals happening in the server, but that's for another separate question.

test app code:

library(shiny)
library(shinydashboard)
library(shinyjs)
ui  <-
  fluidPage(
  hr("how do we get the change the style elements of a single select input?)
tags$style(type='text/css',  .selectize-input  { font-size: 8px; line-height: 8px;}
             .selectize-dropdown { font-size: 8px; line-height: 8px; }"),

    selectInput("choice", "choices", c("A", "B", "C")),

    selectInput("choice2", "choices", c("D", "E", "F"))
     )

server < - function(input, output, session) {   }
})
shinyApp(ui = ui, server = server)

This approach comes straight from Dean Attali's answer here: examp, and a similar question is asked as final comment, but no answer, so I decided to post a question on the matter since I have the same problem.

for other elements likea textInput field, the way I usually do this is by this:

tags$style(type='text/css', "#NAMEELEMENT {background-color: green; height: 40px; border-color: #bfbfbf; width: 520px; position: relative;left: 3%}"),

where you can attach the tag$style to an element by # and its inputId.

Cheers.

Body:
Wrap your selectInput in a div:

tags$div(id='my_div',
         class='my_class',
         selectInput("choice",
                     "choices",
                      c("A", "B", "C"))),

Then you can style it without affecting other selectInput elements:

#my_div .selectize-dropdown-content > .option {
   background-color: grey;
}

or

.my_class .selectize-dropdown-content > .option {
   background-color: grey;
}

As always with CSS, use id to name and to catch a single element, and  class to style multiple elements.


问:
What are form factories and when should they be used?
Would someone like to attempt a succinct explanation of what a form_factory, or a modelform_factory is in relation to a form / modelform?

Why use a factory?

Is there an official technical definition for a
factory method?

答:
The modelform_factory method is a method that returns a ModelForm class. Here's an example of why it's useful.

If you have a simple view that uses a form for a single model, then there is no need for a factory, you can simply define the form:

```<code>class ProductForm(forms.ModelForm):
    class Meta:
        model = Product

def add_product_view(request):
    form = ProductForm()
    ...
</code>```

However, if your view needs to handle multiple models, then you might not want to have to define a form class for every model. The modelform_factory lets you create the form class dynamically.

```<code>apps.get_model('newapp', 'mymodel')

def add_model_view(request, model_name):
    Model = apps.get_model('myapp', model_name)
    Form = modelform_factory(Model)
</code>```

The Django admin uses modelform_factory to generate model form classes dynamically. This means you don't need to define a model form every time you register a model in the Django admin.

Body:
The modelform_factory method is a method that returns a ModelForm class. Here's an example of why it's useful.

If you have a simple view that uses a form for a single model, then there is no need for a factory, you can simply define the form:

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product

def add_product_view(request):
    form = ProductForm()
    ...

However, if your view needs to handle multiple models, then you might not want to have to define a form class for every model. The modelform_factory lets you create the form class dynamically.

apps.get_model('newapp', 'mymodel')

def add_model_view(request, model_name):
    Model = apps.get_model('myapp', model_name)
    Form = modelform_factory(Model)

The Django admin uses modelform_factory to generate model form classes dynamically. This means you don't need to define a model form every time you register a model in the Django admin.


问:
Looping through links(stories) and taking screenshots
What I'm trying to do here is loop through Storybook stories so I can perform visual regression testing on them:

```<code>const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });

test('no visual regression for button', async () => {
  const selector = 'a[href*="?selectedKind=Buttons&selectedStory="]';
  const browser = await puppeteer.launch({headless:false, slowMo: 350});
  const page = await browser.newPage();
  await page.goto('http://localhost:8080');

const storyLinks = await page.evaluate(() => {
  const stories = Array.from(document.querySelectorAll('a[href*="?selectedKind=Buttons&selectedStory="]'));
  const links = stories.map(story => story.href);
  return links;
});
 await storyLinks.forEach( (storyLink) => {
   page.goto(storyLink).then(async (res,rej) => {
     const screen = await page.screenshot();
     return await expect(screen).toMatchImageSnapshot();
   });
 });

 await browser.close();
});
</code>```

One problem is that I get this because of the await broswer.close() that isn't waiting for everything to finish:

```<code>Protocol error (Page.navigate): Target closed.

      at Session._onClosed (../../node_modules/puppeteer/lib/Connection.js:209:23)
      at Connection._onClose (../../node_modules/puppeteer/lib/Connection.js:116:15)
      at Connection.dispose (../../node_modules/puppeteer/lib/Connection.js:121:10)
      at Browser.close (../../node_modules/puppeteer/lib/Browser.js:60:22)
      at Object.<anonymous>.test (__tests__/visual.spec.js:24:16)
          at <anonymous>
</code>```

This happens for each storyLink except the first.

If I comment out the await browser.close() line, the screenshots are being taken, but not in the expected wait. Instead of each story having one screenshot, the last story is being screenshotted for the amount of stories. For example, I've got 4 stories in total, but I will have 4 screenshots of the last story instead of one for each story.

I don't understand why this behaviour is happening. The storyLinks returned from the page.evaluate funtions are correct, but then everything breaks and I've got no idea why.

Any ideas?

答:
forEach is not good for async-await. Use for..of instead,

```<code>for (let storyLink of storyLinks) {
        await page.goto(storyLink)
        const screen = await page.screenshot();
        await expect(screen).toMatchImageSnapshot();
};
</code>```

Body:
What I'm trying to do here is loop through Storybook stories so I can perform visual regression testing on them:

const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });

test('no visual regression for button', async () => {
  const selector = 'a[href*="?selectedKind=Buttons&selectedStory="]';
  const browser = await puppeteer.launch({headless:false, slowMo: 350});
  const page = await browser.newPage();
  await page.goto('http://localhost:8080');

const storyLinks = await page.evaluate(() => {
  const stories = Array.from(document.querySelectorAll('a[href*="?selectedKind=Buttons&selectedStory="]'));
  const links = stories.map(story => story.href);
  return links;
});
 await storyLinks.forEach( (storyLink) => {
   page.goto(storyLink).then(async (res,rej) => {
     const screen = await page.screenshot();
     return await expect(screen).toMatchImageSnapshot();
   });
 });

 await browser.close();
});

One problem is that I get this because of the await broswer.close() that isn't waiting for everything to finish:

Protocol error (Page.navigate): Target closed.

      at Session._onClosed (../../node_modules/puppeteer/lib/Connection.js:209:23)
      at Connection._onClose (../../node_modules/puppeteer/lib/Connection.js:116:15)
      at Connection.dispose (../../node_modules/puppeteer/lib/Connection.js:121:10)
      at Browser.close (../../node_modules/puppeteer/lib/Browser.js:60:22)
      at Object.<anonymous>.test (__tests__/visual.spec.js:24:16)
          at <anonymous>

This happens for each storyLink except the first.

If I comment out the await browser.close() line, the screenshots are being taken, but not in the expected wait. Instead of each story having one screenshot, the last story is being screenshotted for the amount of stories. For example, I've got 4 stories in total, but I will have 4 screenshots of the last story instead of one for each story.

I don't understand why this behaviour is happening. The storyLinks returned from the page.evaluate funtions are correct, but then everything breaks and I've got no idea why.

Any ideas?

Body:
forEach is not good for async-await. Use for..of instead,

for (let storyLink of storyLinks) {
        await page.goto(storyLink)
        const screen = await page.screenshot();
        await expect(screen).toMatchImageSnapshot();
};


问:
Shall I restart both nginx and gunicorn when production is updated?
What is the best practice when I have an update for my Django app pushed in my production? Shall I restart both gunicorn and nginx services, with

```<code>sudo service gunicorn restart
sudo service nginx restart
</code>```

or restarting only gunicorn is enough? Finally does the order of the restarts makes any difference if I have to do both the restarts? Thanks!

答:
It entirely depends on how you've configured your box.

To keep downtime to an absolute minimum, I actually load my new release into a different directory on the box while the old release is still running. I create a new virtual environment based on my new release's requirements.txt. Then I start a second instance of gunicorn with the new release running in it (done via supervisord with entries in supervisord.conf), and leave the old instance still running.

I then update my nginx vhost file to point the server to the new release's gunicorn socket, and finally reload nginx. I do a quick check that the new site is up and functioning, and then I stop the old gunicorn instance. If for some reason it's not responding, I switch my nginx config back to point to the old one again, and then go figure out what's wrong.

I do all this using an Ansible script, but here's a great article with some Fabric scripts to do something similar: https://medium.com/@healthchecks/deploying-a-django-app-with-no-downtime-f4e02738ab06

If, on the other hand, you just update your code in-place, then there should be no changes needed to your nginx config, so you shouldn't need to reload it. Just reload gunicorn and you're good to go.

Body:
What is the best practice when I have an update for my Django app pushed in my production? Shall I restart both gunicorn and nginx services, with

sudo service gunicorn restart
sudo service nginx restart

or restarting only gunicorn is enough? Finally does the order of the restarts makes any difference if I have to do both the restarts? Thanks!


问:
How to retrieve selected ListView value when data comes from SQL Server (WPF)
I'm new to C# and WPF so hopefully this is a simple issue.

I have a listview which retrieves data from a SQL Server table.

```<code><ListView Width="450" Margin="10" Grid.Row="1" ItemsSource="{Binding Path=Table}" Name="FIData" SelectionChanged="FIData_SelectionChanged">
       <ListView.View>
         <GridView>
           <GridViewColumn Header="FI #" DisplayMemberBinding="{Binding Path=Id}"/>
           <GridViewColumn Header="FI Short Name" DisplayMemberBinding="{Binding Path=ShortName}"/>
           <GridViewColumn Header="FI Long Name" DisplayMemberBinding="{Binding Path=LongName}"/>
           <GridViewColumn Header="Last Load Date" DisplayMemberBinding="{Binding Path=MostRecentEffectiveDate}"/>
         </GridView>
       </ListView.View>
    </ListView>

SqlConnection con = new SqlConnection();
    SqlDataAdapter ad = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand();

    string strSql = "SELECT Id, ShortName, LongName, MostRecentEffectiveDate FROM Institutions";

public void BindData()
    {
        cmd.CommandText = strSql;
        ad.SelectCommand = cmd;
        con.ConnectionString = "Data Source=DEVDB\\ABC; Initial Catalog=Cat1; Integrated Security=True";
        cmd.Connection = con;
        DataSet ds = new DataSet();
        ad.Fill(ds);
        FIData.DataContext = ds.Tables[0].DefaultView;
        con.Close();
    }

private void Button_Click(object sender, RoutedEventArgs e)
    {
        BindData();
    }
</code>```

When clicking a button, the BindData method is called and my list view populates just fine. My problem is I don't know how to retrieve the data values from the selected list item.

In all of the other examples users are either populating their data from properties in the C# code or XML or some other source. I'm thinking that perhaps one of my problems is I don't understand objects quite right, but I was hoping someone could show me how I go about getting specific values from the selected list. I want to use one of those values later on.

Thanks,

Jason

答:
Here, when you do:

FIData.DataContext = ds.Tables[0].DefaultView;

it maps the actual DataTable with virtual properties, which can be used for data-binding scenarios like yours.

But to answer your question on how you can retrieve the data values, I think you are pretty close because you have FIData_SelectionChanged event for your listview. In that event:

```<code>private void FIData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var myListView = sender as ListView;
  if(myListView != null)
  {
    var selectedItem = myListView.SelectedItem;

    //selectedItem should have an array, which contains data values for the bound object.
  }
}
</code>```

you should inspect the selectedItem above in the debugger and look at what data it contains.

Body:
I'm new to C# and WPF so hopefully this is a simple issue.

I have a listview which retrieves data from a SQL Server table.

<ListView Width="450" Margin="10" Grid.Row="1" ItemsSource="{Binding Path=Table}" Name="FIData" SelectionChanged="FIData_SelectionChanged">
       <ListView.View>
         <GridView>
           <GridViewColumn Header="FI #" DisplayMemberBinding="{Binding Path=Id}"/>
           <GridViewColumn Header="FI Short Name" DisplayMemberBinding="{Binding Path=ShortName}"/>
           <GridViewColumn Header="FI Long Name" DisplayMemberBinding="{Binding Path=LongName}"/>
           <GridViewColumn Header="Last Load Date" DisplayMemberBinding="{Binding Path=MostRecentEffectiveDate}"/>
         </GridView>
       </ListView.View>
    </ListView>

SqlConnection con = new SqlConnection();
    SqlDataAdapter ad = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand();

    string strSql = "SELECT Id, ShortName, LongName, MostRecentEffectiveDate FROM Institutions";

public void BindData()
    {
        cmd.CommandText = strSql;
        ad.SelectCommand = cmd;
        con.ConnectionString = "Data Source=DEVDB\\ABC; Initial Catalog=Cat1; Integrated Security=True";
        cmd.Connection = con;
        DataSet ds = new DataSet();
        ad.Fill(ds);
        FIData.DataContext = ds.Tables[0].DefaultView;
        con.Close();
    }

private void Button_Click(object sender, RoutedEventArgs e)
    {
        BindData();
    }

When clicking a button, the BindData method is called and my list view populates just fine. My problem is I don't know how to retrieve the data values from the selected list item.

In all of the other examples users are either populating their data from properties in the C# code or XML or some other source. I'm thinking that perhaps one of my problems is I don't understand objects quite right, but I was hoping someone could show me how I go about getting specific values from the selected list. I want to use one of those values later on.

Thanks,

Jason

Body:
Here, when you do:

FIData.DataContext = ds.Tables[0].DefaultView;

it maps the actual DataTable with virtual properties, which can be used for data-binding scenarios like yours.

But to answer your question on how you can retrieve the data values, I think you are pretty close because you have FIData_SelectionChanged event for your listview. In that event:

private void FIData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var myListView = sender as ListView;
  if(myListView != null)
  {
    var selectedItem = myListView.SelectedItem;

    //selectedItem should have an array, which contains data values for the bound object.
  }
}

you should inspect the selectedItem above in the debugger and look at what data it contains.


问:
TypeError at /image/ expected string or Unicode object, InMemoryUploadedFile found
I have build a image processing classifier and In this code I am making an api which takes the input image form key 'test_image' and predicts the class of the image but cv2.imread() is giving me this error

TypeError at /image/ expected string or Unicode object, InMemoryUploadedFile found

I know that cv2.imread takes only url of the image but I don't know how to resolve this.

My code:

```<code>def classify_image(request):
    if request.method == 'POST' and request.FILES['test_image']:
        test_image = request.FILES['test_image']
        test_image = cv2.imread(test_image)
        test_image = cv2.resize(test_image, (128, 128))
        test_image = np.array(test_image)
        test_image = test_image.astype('float32')
        test_image /= 255
        print(test_image.shape)

        test_image = np.expand_dims(test_image, axis=0)
        pred = model.predict_classes(test_image)
        print(pred)

   return JsonResponse(pred, safe=False)
</code>```

答:
It looks like the imread method is intended to read an image from a file. There's a different method, imdecode, for reading the image from memory. Try replacing line 4 of your code with this:

```<code>test_image = cv2.imdecode(test_image.read())
</code>```

Source:

https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html

https://docs.djangoproject.com/en/1.11/ref/files/uploads/

Body:
I have build a image processing classifier and In this code I am making an api which takes the input image form key 'test_image' and predicts the class of the image but cv2.imread() is giving me this error

TypeError at /image/ expected string or Unicode object, InMemoryUploadedFile found

I know that cv2.imread takes only url of the image but I don't know how to resolve this.

My code:

def classify_image(request):
    if request.method == 'POST' and request.FILES['test_image']:
        test_image = request.FILES['test_image']
        test_image = cv2.imread(test_image)
        test_image = cv2.resize(test_image, (128, 128))
        test_image = np.array(test_image)
        test_image = test_image.astype('float32')
        test_image /= 255
        print(test_image.shape)

        test_image = np.expand_dims(test_image, axis=0)
        pred = model.predict_classes(test_image)
        print(pred)

   return JsonResponse(pred, safe=False)

Body:
It looks like the imread method is intended to read an image from a file. There's a different method, imdecode, for reading the image from memory. Try replacing line 4 of your code with this:

test_image = cv2.imdecode(test_image.read())

Source:

https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html

https://docs.djangoproject.com/en/1.11/ref/files/uploads/


问:
Single plot through several columns
I have a data file with several columns, let's say, 200. I would like to plot something like

plot 'datafile.dat matrix w image

but using only the even columns in the datafile. I guess that there should be a way combining using and every, but I did not find anything useful yet.

As suggested already in the answers, something like plot "test.dat" every 2 matrix w image should work. Nevertheless, if I have the data

```<code>1   -1  2   -2
3   -3  4   -4
5   -5  6   -6
7   -7  8   -8
</code>```

and I use plot "test.dat" every 2 matrix w image, what I get is
this.

I am using gnuplot 5.0 in Ubuntu 16.04.

Many thanks.

答:
If you have data that looks like

```<code>1   -1  2   -2
3   -3  4   -4
5   -5  6   -6
7   -7  8   -8
</code>```

then you can draw an image of just the odd columns by

```<code>plot "test.dat" every 2 matrix w image
</code>```

Note that all the values are positive, and that the image is upside down. If you want the even columns use

```<code>plot "test.dat" every 2::1 matrix w image
</code>```

This works because the matrix keyword effectively transforms the data into a three-column (x,y,z) format.

Update

There was a bug in some early versions of the gnuplot 5.0 series that caused the behavior you see, see this report. This has been fixed in patchlevel 5 (i.e., gnuplot 5.0.5) and later.

Title: Single plot through several columns

Body:
I have a data file with several columns, let's say, 200. I would like to plot something like

plot 'datafile.dat matrix w image

but using only the even columns in the datafile. I guess that there should be a way combining using and every, but I did not find anything useful yet.

As suggested already in the answers, something like plot "test.dat" every 2 matrix w image should work. Nevertheless, if I have the data

1   -1  2   -2
3   -3  4   -4
5   -5  6   -6
7   -7  8   -8

and I use plot "test.dat" every 2 matrix w image, what I get is
this.

I am using gnuplot 5.0 in Ubuntu 16.04.

Many thanks.

Body:
If you have data that looks like

1   -1  2   -2
3   -3  4   -4
5   -5  6   -6
7   -7  8   -8

then you can draw an image of just the odd columns by

plot "test.dat" every 2 matrix w image

Note that all the values are positive, and that the image is upside down. If you want the even columns use

plot "test.dat" every 2::1 matrix w image

This works because the matrix keyword effectively transforms the data into a three-column (x,y,z) format.

Update

There was a bug in some early versions of the gnuplot 5.0 series that caused the behavior you see, see this report. This has been fixed in patchlevel 5 (i.e., gnuplot 5.0.5) and later.


问:
CakePHP not respecting foreignKey name
I have an articles table with a column tagging_id that needs to reference the id column in a table called tracking_categories as a foreign key.

My Article.php file has the following:

```<code>class Article extends AppModel {
    public $controllerPath = 'articles';
    public $useTable = 'articles';

var $binds = array(
    'TrackingCategory' => array(
        'bindType' => 'belongsTo',
        'className' => 'TrackingCategory',
        'foreignKey' => 'tagging_id'
    ),
    'Channel' => array(
        'bindType' => 'belongsTo',
        'className' => 'Channel',
        'foreignKey' => 'channel_id'
    )
);
</code>```

My TrackingCategory.php looks like this:

```<code>class TrackingCategory extends AppModel {

     public $useTable = 'tracking_categories';
</code>```

I have the following in the AppModel which Article.php inherits:

```<code>function expects($binds, $reset = false) {
    if (func_num_args() > 2 || !is_bool($reset)) {
        throw new InvalidArgumentException('Did you mean to pass an
array of binds?');
    }

    if (!is_array($binds)) {
        $binds = array($binds);
    }

    foreach ($binds as $bind) {

        if (isset($this->binds[$bind])) {
            $tmp = array($this->binds[$bind]['bindType'] => array($bind => $this->binds[$bind]));
            $this->bindModel($tmp, $reset);
        }
    }
}
</code>```

I am getting the following error:
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Article.tracking_category_id' in 'field list'

It is still looking for the column named parsed via CakePHP's naming convention rather than the name that I explicitly set via the foreignKey value.  What am I missing here?

答:
The right syntax should be:

```<code>public $belongsTo = array(
    'TrackingCategory' => array(
        'className' => 'TrackingCategory',
        'foreignKey' => 'tagging_id',
    )
);
</code>```

For more information, see CakePHP 2.x - Associations: Linking Models Together - belongsTo.

Title: CakePHP not respecting foreignKey name

Body:
I have an articles table with a column tagging_id that needs to reference the id column in a table called tracking_categories as a foreign key.

My Article.php file has the following:

class Article extends AppModel {
    public $controllerPath = 'articles';
    public $useTable = 'articles';

var $binds = array(
    'TrackingCategory' => array(
        'bindType' => 'belongsTo',
        'className' => 'TrackingCategory',
        'foreignKey' => 'tagging_id'
    ),
    'Channel' => array(
        'bindType' => 'belongsTo',
        'className' => 'Channel',
        'foreignKey' => 'channel_id'
    )
);

My TrackingCategory.php looks like this:

class TrackingCategory extends AppModel {

     public $useTable = 'tracking_categories';

I have the following in the AppModel which Article.php inherits:

function expects($binds, $reset = false) {
    if (func_num_args() > 2 || !is_bool($reset)) {
        throw new InvalidArgumentException('Did you mean to pass an
array of binds?');
    }

    if (!is_array($binds)) {
        $binds = array($binds);
    }

    foreach ($binds as $bind) {

        if (isset($this->binds[$bind])) {
            $tmp = array($this->binds[$bind]['bindType'] => array($bind => $this->binds[$bind]));
            $this->bindModel($tmp, $reset);
        }
    }
}

I am getting the following error:
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Article.tracking_category_id' in 'field list'

It is still looking for the column named parsed via CakePHP's naming convention rather than the name that I explicitly set via the foreignKey value.  What am I missing here?

Body:
The right syntax should be:

public $belongsTo = array(
    'TrackingCategory' => array(
        'className' => 'TrackingCategory',
        'foreignKey' => 'tagging_id',
    )
);

For more information, see CakePHP 2.x - Associations: Linking Models Together - belongsTo.


问:
How to differentiate two adjacent connected shape

I want to differentiate two component as shown in this picture.
The marked section is my original crop and all other area is weed and I want to detect my only crop section. How to do that in python?

答:
I would start with findContours and drawContours functions, they are described here.

Also it would be possible to find all closed shapes with floodFill (with mask).


问:
How to redirect http to https in codeigniter
Point #1
If I type:

```<code>www.myurl.com/somepage
http://www.myurl.com/somepage
http://myurl.com/somepage
https://myurl.com/somepage
</code>```

have it redirect to

```<code>https://www.myurl.com/somepage
</code>```

Point #2

```<code>When I type in something like www.myurl.com it is redirecting to https://www.myurl.com/index.php.
Make it so the index.php is not displaying. It should just display https://www.myurl.com
</code>```

From Comment htaccess

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^myhost\.com$ [NC]
RewriteRule ^(.*)$ myhost.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /index\.php(/[^\ ]*)?\ HTTP/
RewriteRule ^index\.php(/(.*))?$ myhost.com/$2 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

答:
First go to the application/config/config.php file and look for this line:

```<code>$config['base_url'] = "";
</code>```

Set it to your URL with the https e.g. https://example.com

```<code>$config['base_url'] = "https://example.com";
</code>```

Then go to your .htaccess file and add this line in the example given below.

RewriteRule ^(.*)$ https://example.com/$1 [R,L]

```<code><IfModule mod_rewrite.c>

    #Options +FollowSymLinks
    #Options -Indexes
    RewriteEngine on

    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

    # Send request via index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
    RewriteRule ^(.*)$ https://example.com/$1 [R,L]

</IfModule>
</code>```

Body:
Point #1
If I type:

www.myurl.com/somepage
http://www.myurl.com/somepage
http://myurl.com/somepage
https://myurl.com/somepage

have it redirect to

https://www.myurl.com/somepage

Point #2

When I type in something like www.myurl.com it is redirecting to https://www.myurl.com/index.php.
Make it so the index.php is not displaying. It should just display https://www.myurl.com

From Comment htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^myhost\.com$ [NC]
RewriteRule ^(.*)$ myhost.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /index\.php(/[^\ ]*)?\ HTTP/
RewriteRule ^index\.php(/(.*))?$ myhost.com/$2 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Body:
First go to the application/config/config.php file and look for this line:

$config['base_url'] = "";

Set it to your URL with the https e.g. https://example.com

$config['base_url'] = "https://example.com";

Then go to your .htaccess file and add this line in the example given below.

RewriteRule ^(.*)$ https://example.com/$1 [R,L]

<IfModule mod_rewrite.c>

    #Options +FollowSymLinks
    #Options -Indexes
    RewriteEngine on

    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

    # Send request via index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
    RewriteRule ^(.*)$ https://example.com/$1 [R,L]

</IfModule>


问:
Combinational circuit : Output 2s complement only when select line is high
I want to design a gate-level combinational circuit that implements the below logic. Is it possible to do it without using Adder?

```<code>...
input  wire [3:0] in,
input  wire       sel,
output wire [3:0] out
...

assign out = ({4{sel}} & (~in + 1)) | ({4{~sel}} & in);
</code>```

The above verilog code will be realized into - 4 inverters, 1 full adder and 1 multiplexer. Is it possible to optimize it further?

The idea is to incorporate sel in 2's complement logic and produce a gate circuit that consumes lesser number of gates than adder circuit. Is it really possible?

答:
Try using the Karnaugh map and solve for just the (~in + 1) term.  If you set up the K-map and solve for one bit of the result at a time

```<code>// Input                               Result
// A B C D     -->  ~{A B C D}  --> ~{A B C D}+1
// 0 0 0 0            1 1 1 1         0 0 0 0
// 0 0 0 1            1 1 1 0         1 1 1 1
// 0 0 1 0            1 1 0 1         1 1 1 0
// 0 0 1 1            1 1 0 0         1 1 0 1
// 0 1 0 0            1 0 1 1         1 1 0 0
// 0 1 0 1            1 0 1 0         1 0 1 1
</code>```

... I'll let you write the rest of the map... but a few things start to pop out.

The Result bit D, is always the same as the Input D
The Result bit C appears to be a Input C XOR Input D

If you do some more K map, you will probably find a logical expression for Result bits A and B

Body:
I want to design a gate-level combinational circuit that implements the below logic. Is it possible to do it without using Adder?

...
input  wire [3:0] in,
input  wire       sel,
output wire [3:0] out
...

assign out = ({4{sel}} & (~in + 1)) | ({4{~sel}} & in);

The above verilog code will be realized into - 4 inverters, 1 full adder and 1 multiplexer. Is it possible to optimize it further?

The idea is to incorporate sel in 2's complement logic and produce a gate circuit that consumes lesser number of gates than adder circuit. Is it really possible?

Body:
Try using the Karnaugh map and solve for just the (~in + 1) term.  If you set up the K-map and solve for one bit of the result at a time

// Input                               Result
// A B C D     -->  ~{A B C D}  --> ~{A B C D}+1
// 0 0 0 0            1 1 1 1         0 0 0 0
// 0 0 0 1            1 1 1 0         1 1 1 1
// 0 0 1 0            1 1 0 1         1 1 1 0
// 0 0 1 1            1 1 0 0         1 1 0 1
// 0 1 0 0            1 0 1 1         1 1 0 0
// 0 1 0 1            1 0 1 0         1 0 1 1

... I'll let you write the rest of the map... but a few things start to pop out.

The Result bit D, is always the same as the Input D
The Result bit C appears to be a Input C XOR Input D

If you do some more K map, you will probably find a logical expression for Result bits A and B


问:
Flux.error return 200 http code even if exception is thrown
I work on a project with spring-boot (v2 M3) and spring-webflux.
While coding a feature, I see that my microservice returns me an Http 200 status code while returning an error in a flux.

So, I make a simple test :
I create a simple controller

```<code>@RestController
@RequestMapping(value = "/test")
public class TestController {

   @GetMapping(value = "/errors")
   public Flux<Object> getErrors() {
       return Flux.error(new RuntimeException("test"));
   }
}
</code>```

With a simple exception handler :

```<code>@ControllerAdvice
public class TestExceptionHandler {

     private static final Logger LOGGER = LoggerFactory.getLogger(TestExceptionHandler.class);

     @ExceptionHandler(value = { RuntimeException.class })
     public ResponseEntity<String> handleServerError(final RuntimeException e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
     }
}
</code>```

And I test the result with the webTestClient in a integration test :

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:test.properties")
public class TestErrorsIT {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void getErrors() {

        this.webTestClient.get().uri("/test/errors").accept(MediaType.APPLICATION_STREAM_JSON).exchange().expectStatus()
                        .is5xxServerError();
    }
}
</code>```

As a result, my test fails because my controller that returns an error flux returns a 200 status code instead of a 503 status code (the exception log "test" is well traced in my console). Do you know why ?

java.lang.AssertionError: Range for response status value 200
  expected: but was:

GET http://localhost:54432/test/errors
    WebTestClient-Request-Id: [1]
    Accept: [application/stream+json]

No content

< 200 OK < Content-Type: [application/stream+json] <
  Transfer-Encoding: [chunked] < Date: [Fri, 03 Nov 2017 09:42:53 GMT]

Content not available yet

答:
In this instance, the application has a dependency on spring-cloud-starter-eureka, which itself has a transitive dependency on spring-boot-starter-web.

Adding spring-boot-starter-web to a Spring Boot application turns it into a Spring MVC application, which explains this behavior.

Body:
I work on a project with spring-boot (v2 M3) and spring-webflux.
While coding a feature, I see that my microservice returns me an Http 200 status code while returning an error in a flux.

So, I make a simple test :
I create a simple controller

@RestController
@RequestMapping(value = "/test")
public class TestController {

   @GetMapping(value = "/errors")
   public Flux<Object> getErrors() {
       return Flux.error(new RuntimeException("test"));
   }
}

With a simple exception handler :

@ControllerAdvice
public class TestExceptionHandler {

     private static final Logger LOGGER = LoggerFactory.getLogger(TestExceptionHandler.class);

     @ExceptionHandler(value = { RuntimeException.class })
     public ResponseEntity<String> handleServerError(final RuntimeException e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
     }
}

And I test the result with the webTestClient in a integration test :

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:test.properties")
public class TestErrorsIT {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void getErrors() {

        this.webTestClient.get().uri("/test/errors").accept(MediaType.APPLICATION_STREAM_JSON).exchange().expectStatus()
                        .is5xxServerError();
    }
}

As a result, my test fails because my controller that returns an error flux returns a 200 status code instead of a 503 status code (the exception log "test" is well traced in my console). Do you know why ?

java.lang.AssertionError: Range for response status value 200
  expected: but was:

GET http://localhost:54432/test/errors
    WebTestClient-Request-Id: [1]
    Accept: [application/stream+json]

No content

< 200 OK < Content-Type: [application/stream+json] <
  Transfer-Encoding: [chunked] < Date: [Fri, 03 Nov 2017 09:42:53 GMT]

Content not available yet


问:
How to overwrite a point in memory in c#?
I want to do have the following functionality:

```<code>var item0 = new Item();
var item1 = item0;
item0 = null;

Console.WriteLine(item1 == null); // true
</code>```

So I'd be overwriting the memory that item0 and item1 point to.
I figured maybe I could do this with pointers..? However, when I tried declaring an item pointer:

```<code>Item* itemPointer;
</code>```

i got an error. Any ideas?

答:
Since C# 7 You can use Ref Locals:

```<code>var item0 = new Item();
ref var item1 = ref item0;
item0 = null;

Console.WriteLine(item1 == null); // true
// THIS WORKS!
</code>```

Ref returns and ref locals have mainly been introduced to avoid copying large structs in time sensitive scenarios like gaming where large arrays of vectors have to be processed. I don't see the advantage in using them with reference types. They tend to make the code hard to understand, thus I would restrict their use to exceptional and rare cases.

Body:
I want to do have the following functionality:

var item0 = new Item();
var item1 = item0;
item0 = null;

Console.WriteLine(item1 == null); // true

So I'd be overwriting the memory that item0 and item1 point to.
I figured maybe I could do this with pointers..? However, when I tried declaring an item pointer:

Item* itemPointer;

i got an error. Any ideas?

Body:
Since C# 7 You can use Ref Locals:

var item0 = new Item();
ref var item1 = ref item0;
item0 = null;

Console.WriteLine(item1 == null); // true
// THIS WORKS!

Ref returns and ref locals have mainly been introduced to avoid copying large structs in time sensitive scenarios like gaming where large arrays of vectors have to be processed. I don't see the advantage in using them with reference types. They tend to make the code hard to understand, thus I would restrict their use to exceptional and rare cases.


问:
Precisely scale image
I am trying to precisely and predictably scale an image in C# to a different resolution, both up and down. When I open the resulting images with external tools such as Gimp, the results are not satisfying with my current settings.

```<code>public Image Square(Image image, int res) {
    Bitmap sq = new Bitmap(res, res, image.PixelFormat);
    Graphics canvas = Graphics.FromImage(sq);
    canvas.CompositingQuality = CompositingQuality.HighQuality;
    canvas.SmoothingMode = SmoothingMode.None;
    canvas.InterpolationMode = InterpolationMode.Bicubic;
    canvas.DrawImage(sq, 0, 0, res, res);
    return sq;
}
</code>```

The results are okay when scaling down (but far from perfect), but there are side-effects when scaling up:

This picture has a resolution of 2x2 pixels. The alpha channel is set to opaque for all pixels.

After scaling it to 4x4 pixels, this is the result:

Apparently, the C# graphics library introduced transparency while scaling the picture. This method should still work if the given image has transparent pictures, so removing the alpha channel is not an option.

Similarly, when scaling pictures down, there are problems at the edges of the resulting images as well, usually either very dark or transparent.

Is there any way to circumvent this behavior?

Edit: I already tried NearestNeighbor for downscaling only, but it results in this:

Edit 2: With WrapMode.TileFlipXY, the transparent edge is gone, but red only makes up 25% of the image instead of 50% as it should be:

答:
You're asking for bicubic interpolation and you're getting it. What you want is the "nearest neighbor" option as outlined in the docs:</p>

```<code>canvas.InterpolationMode = InterpolationMode.NearestNeighbor;
</code>```

Title: Precisely scale image

Body:
I am trying to precisely and predictably scale an image in C# to a different resolution, both up and down. When I open the resulting images with external tools such as Gimp, the results are not satisfying with my current settings.

public Image Square(Image image, int res) {
    Bitmap sq = new Bitmap(res, res, image.PixelFormat);
    Graphics canvas = Graphics.FromImage(sq);
    canvas.CompositingQuality = CompositingQuality.HighQuality;
    canvas.SmoothingMode = SmoothingMode.None;
    canvas.InterpolationMode = InterpolationMode.Bicubic;
    canvas.DrawImage(sq, 0, 0, res, res);
    return sq;
}

The results are okay when scaling down (but far from perfect), but there are side-effects when scaling up:

This picture has a resolution of 2x2 pixels. The alpha channel is set to opaque for all pixels.

After scaling it to 4x4 pixels, this is the result:

Apparently, the C# graphics library introduced transparency while scaling the picture. This method should still work if the given image has transparent pictures, so removing the alpha channel is not an option.

Similarly, when scaling pictures down, there are problems at the edges of the resulting images as well, usually either very dark or transparent.

Is there any way to circumvent this behavior?

Edit: I already tried NearestNeighbor for downscaling only, but it results in this:

Edit 2: With WrapMode.TileFlipXY, the transparent edge is gone, but red only makes up 25% of the image instead of 50% as it should be:

Body:
You're asking for bicubic interpolation and you're getting it. What you want is the "nearest neighbor" option as outlined in the docs:

canvas.InterpolationMode = InterpolationMode.NearestNeighbor;


问:
Python 'height' is not defined
Python is saying that the name 'height' is not defined, and I have no idea why that is, as according to my logic, I return the variable height, so I would be able to access it within my for loop?

Can someone point me in the right direction?
Thanks.
Edit: the get_int() is a function inside the cs50 library.

```<code>import cs50

def main():

    print("Enter a number between 0 and 26: ", end="")

    i = get_height("Enter height: ", end="")

def get_height():
    while True:
        height = get_int()
        if height <= 0 or height >= 23:
            break
    return height

for i in range(height):
    print(" " * (height - i), end="")
    print("#" * (i + 2), end="")
    print("")

if __name__ == "__main__":
    main()
</code>```

答: First, off you need to use hight = raw_input("What is your hight") to get your height. You can then use int(height) to use it as an integer. Secondly, you need to have it be top-down processing.

Title: Python 'height' is not defined

Body:
Python is saying that the name 'height' is not defined, and I have no idea why that is, as according to my logic, I return the variable height, so I would be able to access it within my for loop?

Can someone point me in the right direction?
Thanks.
Edit: the get_int() is a function inside the cs50 library.

import cs50

def main():

    print("Enter a number between 0 and 26: ", end="")

    i = get_height("Enter height: ", end="")

def get_height():
    while True:
        height = get_int()
        if height <= 0 or height >= 23:
            break
    return height

for i in range(height):
    print(" " * (height - i), end="")
    print("#" * (i + 2), end="")
    print("")

if __name__ == "__main__":
    main()


问:
Strange MySQL/PHP issue: mysql query does not execute and there is no error
I ran into a strange bug in my PHP web app that I'm unable to sort out. The php script fetches a row from the database, it processes it and serializes a new query and writes back the row to the database.

I copied the code that does this:

```<code>foreach($a as $key => $value)
{
    $a[$key]="'".mysql_real_escape_string($value)."'";
}
$a['lastUpdate']="$when";
//assembling request
$assignments=array();
foreach($a as $key => $value)
{
    $assignments[]="$key=$value";
}

$q="UPDATE wtfb2_villages SET ".implode(',',$assignments)." WHERE (id=${a['id']})";
logText($q);
logText(mysql_error());
$r=mysql_query($q) or die(__FILE__.':'.__LINE__.':'.mysql_error().':'.$q);
logText(mysql_affected_rows());
logText('Mysql error in query is: '.mysql_error()."\n");
</code>```

That UPDATE seemingly executes. mysql_error() gives an empty string. mysql_affected_rows says 1 just like when everything is done. But if I look into the table using phpmyadmin I saw that nothing is changed.

I logged the query itself its:

```<code>UPDATE wtfb2_villages SET id='22',ownerId='56',villageName='Új falu',x='0',y='1',buildPoints='7.2226273148149',barracksLevel='0',archeryRangeLevel='0',stablesLevel='0',workshopLevel='0',townHallLevel='0',blacksmithLevel='0',goldmineLevel='1',wallLevel='0',spearmen='0',archers='0',knights='0',catapults='0',diplomats='0',spearmanLevel='0',archerLevel='0',knightLevel='0',catapultLevel='0',spearmenTraining='0',archersTraining='0',knightsTraining='0',catapultsTraining='0',diplomatsTraining='0',lastUpdate='2011-01-18 21:56:10' WHERE (id='22')
</code>```

If I just copy-paste this query directly into the phpmyadmin it executes it and I see the result in the table.

The table is using myIsam engine. So no transactions or anythin such.

I got stuck at this problem more than 2 hours and I'm unable to find out what's going on.

This is the only one query that does this. queries before and after this one executing properly.

Any ideas?

答: Looking at your query log, is ID a primary key? I'm not sure you can include it in your update query if so. It's been a while since I've done DB work though.</p>

Body:
I ran into a strange bug in my PHP web app that I'm unable to sort out. The php script fetches a row from the database, it processes it and serializes a new query and writes back the row to the database.

I copied the code that does this:

foreach($a as $key => $value)
{
    $a[$key]="'".mysql_real_escape_string($value)."'";
}
$a['lastUpdate']="$when";
//assembling request
$assignments=array();
foreach($a as $key => $value)
{
    $assignments[]="$key=$value";
}

$q="UPDATE wtfb2_villages SET ".implode(',',$assignments)." WHERE (id=${a['id']})";
logText($q);
logText(mysql_error());
$r=mysql_query($q) or die(__FILE__.':'.__LINE__.':'.mysql_error().':'.$q);
logText(mysql_affected_rows());
logText('Mysql error in query is: '.mysql_error()."\n");

That UPDATE seemingly executes. mysql_error() gives an empty string. mysql_affected_rows says 1 just like when everything is done. But if I look into the table using phpmyadmin I saw that nothing is changed.

I logged the query itself its:

UPDATE wtfb2_villages SET id='22',ownerId='56',villageName='Új falu',x='0',y='1',buildPoints='7.2226273148149',barracksLevel='0',archeryRangeLevel='0',stablesLevel='0',workshopLevel='0',townHallLevel='0',blacksmithLevel='0',goldmineLevel='1',wallLevel='0',spearmen='0',archers='0',knights='0',catapults='0',diplomats='0',spearmanLevel='0',archerLevel='0',knightLevel='0',catapultLevel='0',spearmenTraining='0',archersTraining='0',knightsTraining='0',catapultsTraining='0',diplomatsTraining='0',lastUpdate='2011-01-18 21:56:10' WHERE (id='22')

If I just copy-paste this query directly into the phpmyadmin it executes it and I see the result in the table.

The table is using myIsam engine. So no transactions or anythin such.

I got stuck at this problem more than 2 hours and I'm unable to find out what's going on.

This is the only one query that does this. queries before and after this one executing properly.

Any ideas?


问:
Multiple activity on one button click
I have a problem with creating 2 activities for 1 button. I created a button and I managed to connect that button with one activity but I dont know how to add another activity to the same button.. What am I trying to do is that when we press on that button it will start playing animation (I managed to do that) but I also want it to send SMS to a specific number. I have code for that, but I dont know how to include / connect everything together.

Code from a button:

```<code><Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" />
</code>```

Code from a imageview (animation):

```<code><ImageView

    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:scaleType="centerInside"
    android:src="@drawable/keers" />
</code>```

Code from main activity, for animation:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.imageView);

    button = (Button) findViewById(R.id.button);

    running = false;

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            if(!running){
            ((AnimationDrawable) imageView.getDrawable()).start();
            running = true;}
        }
    }
    );
}
}
</code>```

Now what I want to add for the same button is this :

```<code>public void sendText(View paramView)
{
    Toast.makeText(this, "SENT",Toast.LENGTH_SHORT).show();
    SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);
</code>```

I'm not that experienced in programming, so it might be pretty easy for you guys.

答:
Both actions seen to be fired by the same Button, so you may add both to the onClickListener</p>

```<code>button.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        if(!running){
        ((AnimationDrawable) imageView.getDrawable()).start();
        running = true;}
         Toast.makeText(view.getContext(), "SENT",Toast.LENGTH_SHORT).show(); //Or YourActivity.this
         SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);
    }
}
</code>```

Title: Multiple activity on one button click

Body:
I have a problem with creating 2 activities for 1 button. I created a button and I managed to connect that button with one activity but I dont know how to add another activity to the same button.. What am I trying to do is that when we press on that button it will start playing animation (I managed to do that) but I also want it to send SMS to a specific number. I have code for that, but I dont know how to include / connect everything together.

Code from a button:

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" />

Code from a imageview (animation):

<ImageView

    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:scaleType="centerInside"
    android:src="@drawable/keers" />

Code from main activity, for animation:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.imageView);

    button = (Button) findViewById(R.id.button);

    running = false;

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            if(!running){
            ((AnimationDrawable) imageView.getDrawable()).start();
            running = true;}
        }
    }
    );
}
}

Now what I want to add for the same button is this :

public void sendText(View paramView)
{
    Toast.makeText(this, "SENT",Toast.LENGTH_SHORT).show();
    SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);

I'm not that experienced in programming, so it might be pretty easy for you guys.

Body:
Both actions seen to be fired by the same Button, so you may add both to the onClickListener

button.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        if(!running){
        ((AnimationDrawable) imageView.getDrawable()).start();
        running = true;}
         Toast.makeText(view.getContext(), "SENT",Toast.LENGTH_SHORT).show(); //Or YourActivity.this
         SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);
    }
}


问:
How to loop through an array of arrays using jQuery or JavaScript?
I have a json array like this

```<code>var data = key: [
    {
        arr1: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr2: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr3: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    }
]
</code>```

I wanted to loop through key which is 3 times, and inside the key loop I wanted loop again through each of the elements inside key.

First I tried $.each which works fine for key array. And inside the each function I tried to get the key values using Object.key(this) inside the loop which returned me the names

```<code>arr1, arr2, arr3
</code>```

But I'm not able to loop through the names I got.

```<code>$.each(data, function(i, e) {
    Object.keys(this).each(function(index, element) {
        console.log(element);
    })
})
</code>```

I don't know if this is the right way of doing it, when I tried doing it this was. I got an error telling .each is not a function.

Any help will be much appreciated.

答:
If you want to keep with the jQuery pattern, then just keep using each for each nested level:

var data = [{arr1: [{value: 1}, {value: 2}, {value: 3}]}, {arr2: [{value: 1}, {value: 2}, {value: 3}]}, {arr3: [{value: 1}, {value: 2}, {value: 3}]}];

$.each(data, function(i, e) {
    $.each(e, function(key, arr) {
        console.log(key);
        $.each(arr, function(index, obj) {
            console.log("...", index, obj.value);
        });
    });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Body:
I have a json array like this

var data = key: [
    {
        arr1: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr2: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr3: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    }
]

I wanted to loop through key which is 3 times, and inside the key loop I wanted loop again through each of the elements inside key.

First I tried $.each which works fine for key array. And inside the each function I tried to get the key values using Object.key(this) inside the loop which returned me the names

arr1, arr2, arr3

But I'm not able to loop through the names I got.

$.each(data, function(i, e) {
    Object.keys(this).each(function(index, element) {
        console.log(element);
    })
})

I don't know if this is the right way of doing it, when I tried doing it this was. I got an error telling .each is not a function.

Any help will be much appreciated.

Body:
If you want to keep with the jQuery pattern, then just keep using each for each nested level:

var data = [{arr1: [{value: 1}, {value: 2}, {value: 3}]}, {arr2: [{value: 1}, {value: 2}, {value: 3}]}, {arr3: [{value: 1}, {value: 2}, {value: 3}]}];

$.each(data, function(i, e) {
    $.each(e, function(key, arr) {
        console.log(key);
        $.each(arr, function(index, obj) {
            console.log("...", index, obj.value);
        });
    });
})

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>