问:
Problems when scaling a YUV image using libyuv library
I'm developing a camera app based on Camera API 2 and I have found several problems using the libyuv.
I want to convert YUV_420_888 images retrieved from a ImageReader, but I'm having some problems with scaling in a reprocessable surface.

In essence: Images come out with tones of green instead of having the corresponding tones (I'm exporting the .yuv files and checking them using http://rawpixels.net/).

You can see an input example here:

And what I get after I perform scaling:

I think I am doing something wrong with strides, or providing an invalid YUV format (maybe I have to transform the image to another format?). However, I can't figure out where is the error since I don't know how to correlate the green color to the scaling algorithm.

This is the conversion code I am using, you can ignore the return NULL as there is further processing that is not related to the problem.

```<code>#include <jni.h>
#include <stdint.h>
#include <android/log.h>
#include <inc/libyuv/scale.h>
#include <inc/libyuv.h>
#include <stdio.h>

#define  LOG_TAG    "libyuv-jni"

#define unused(x) UNUSED_ ## x __attribute__((__unused__))
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS_)

struct YuvFrame {
    int width;
    int height;
    uint8_t *data;
    uint8_t *y;
    uint8_t *u;
    uint8_t *v;
};

static struct YuvFrame i420_input_frame;
static struct YuvFrame i420_output_frame;

extern "C" {

JNIEXPORT jbyteArray JNICALL
Java_com_android_camera3_camera_hardware_session_output_photo_yuv_YuvJniInterface_scale420YuvByteArray(
        JNIEnv *env, jclass /*clazz*/, jbyteArray yuvByteArray_, jint src_width, jint src_height,
        jint out_width, jint out_height) {

    jbyte *yuvByteArray = env->GetByteArrayElements(yuvByteArray_, NULL);

    //Get input and output length
    int input_size = env->GetArrayLength(yuvByteArray_);
    int out_size = out_height * out_width;

    //Generate input frame
    i420_input_frame.width = src_width;
    i420_input_frame.height = src_height;
    i420_input_frame.data = (uint8_t *) yuvByteArray;
    i420_input_frame.y = i420_input_frame.data;
    i420_input_frame.u = i420_input_frame.y + input_size;
    i420_input_frame.v = i420_input_frame.u + input_size / 4;

    //Generate output frame
    free(i420_output_frame.data);
    i420_output_frame.width = out_width;
    i420_output_frame.height = out_height;
    i420_output_frame.data = new unsigned char[out_size * 3 / 2];
    i420_output_frame.y = i420_output_frame.data;
    i420_output_frame.u = i420_output_frame.y + out_size;
    i420_output_frame.v = i420_output_frame.u + out_size / 4;
    libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear;

    int result = I420Scale(i420_input_frame.y, i420_input_frame.width,
                           i420_input_frame.u, i420_input_frame.width / 2,
                           i420_input_frame.v, i420_input_frame.width / 2,
                           i420_input_frame.width, i420_input_frame.height,
                           i420_output_frame.y, i420_output_frame.width,
                           i420_output_frame.u, i420_output_frame.width / 2,
                           i420_output_frame.v, i420_output_frame.width / 2,
                           i420_output_frame.width, i420_output_frame.height,
                           mode);
    LOGD("Image result %d", result);
    env->ReleaseByteArrayElements(yuvByteArray_, yuvByteArray, 0);
    return NULL;
}
</code>```

答:
You can try that code that it uses the y_size instead of full size of your array.

```<code>    ...
    //Get input and output length
    int input_size = env->GetArrayLength(yuvByteArray_);
    int y_size = src_width * src_height;
    int out_size = out_height * out_width;

    //Generate input frame
    i420_input_frame.width = src_width;
    i420_input_frame.height = src_height;
    i420_input_frame.data = (uint8_t *) yuvByteArray;
    i420_input_frame.y = i420_input_frame.data;
    i420_input_frame.u = i420_input_frame.y + y_size;
    i420_input_frame.v = i420_input_frame.u + y_size / 4;

    //Generate output frame
    free(i420_output_frame.data);
    i420_output_frame.width = out_width;
    i420_output_frame.height = out_height;
    i420_output_frame.data = new unsigned char[out_size * 3 / 2];
    i420_output_frame.y = i420_output_frame.data;
    i420_output_frame.u = i420_output_frame.y + out_size;
    i420_output_frame.v = i420_output_frame.u + out_size / 4;
    ...
</code>```

probably your code is based on that https://github.com/begeekmyfriend/yasea/blob/master/library/src/main/libenc/jni/libenc.cc and according to that code you have to use the y_size

Body:
I'm developing a camera app based on Camera API 2 and I have found several problems using the libyuv.
I want to convert YUV_420_888 images retrieved from a ImageReader, but I'm having some problems with scaling in a reprocessable surface.

In essence: Images come out with tones of green instead of having the corresponding tones (I'm exporting the .yuv files and checking them using http://rawpixels.net/).

You can see an input example here:

And what I get after I perform scaling:

I think I am doing something wrong with strides, or providing an invalid YUV format (maybe I have to transform the image to another format?). However, I can't figure out where is the error since I don't know how to correlate the green color to the scaling algorithm.

This is the conversion code I am using, you can ignore the return NULL as there is further processing that is not related to the problem.

#include <jni.h>
#include <stdint.h>
#include <android/log.h>
#include <inc/libyuv/scale.h>
#include <inc/libyuv.h>
#include <stdio.h>

#define  LOG_TAG    "libyuv-jni"

#define unused(x) UNUSED_ ## x __attribute__((__unused__))
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS_)

struct YuvFrame {
    int width;
    int height;
    uint8_t *data;
    uint8_t *y;
    uint8_t *u;
    uint8_t *v;
};

static struct YuvFrame i420_input_frame;
static struct YuvFrame i420_output_frame;

extern "C" {

JNIEXPORT jbyteArray JNICALL
Java_com_android_camera3_camera_hardware_session_output_photo_yuv_YuvJniInterface_scale420YuvByteArray(
        JNIEnv *env, jclass /*clazz*/, jbyteArray yuvByteArray_, jint src_width, jint src_height,
        jint out_width, jint out_height) {

    jbyte *yuvByteArray = env->GetByteArrayElements(yuvByteArray_, NULL);

    //Get input and output length
    int input_size = env->GetArrayLength(yuvByteArray_);
    int out_size = out_height * out_width;

    //Generate input frame
    i420_input_frame.width = src_width;
    i420_input_frame.height = src_height;
    i420_input_frame.data = (uint8_t *) yuvByteArray;
    i420_input_frame.y = i420_input_frame.data;
    i420_input_frame.u = i420_input_frame.y + input_size;
    i420_input_frame.v = i420_input_frame.u + input_size / 4;

    //Generate output frame
    free(i420_output_frame.data);
    i420_output_frame.width = out_width;
    i420_output_frame.height = out_height;
    i420_output_frame.data = new unsigned char[out_size * 3 / 2];
    i420_output_frame.y = i420_output_frame.data;
    i420_output_frame.u = i420_output_frame.y + out_size;
    i420_output_frame.v = i420_output_frame.u + out_size / 4;
    libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear;

    int result = I420Scale(i420_input_frame.y, i420_input_frame.width,
                           i420_input_frame.u, i420_input_frame.width / 2,
                           i420_input_frame.v, i420_input_frame.width / 2,
                           i420_input_frame.width, i420_input_frame.height,
                           i420_output_frame.y, i420_output_frame.width,
                           i420_output_frame.u, i420_output_frame.width / 2,
                           i420_output_frame.v, i420_output_frame.width / 2,
                           i420_output_frame.width, i420_output_frame.height,
                           mode);
    LOGD("Image result %d", result);
    env->ReleaseByteArrayElements(yuvByteArray_, yuvByteArray, 0);
    return NULL;
}

Body:
You can try that code that it uses the y_size instead of full size of your array.

    ...
    //Get input and output length
    int input_size = env->GetArrayLength(yuvByteArray_);
    int y_size = src_width * src_height;
    int out_size = out_height * out_width;

    //Generate input frame
    i420_input_frame.width = src_width;
    i420_input_frame.height = src_height;
    i420_input_frame.data = (uint8_t *) yuvByteArray;
    i420_input_frame.y = i420_input_frame.data;
    i420_input_frame.u = i420_input_frame.y + y_size;
    i420_input_frame.v = i420_input_frame.u + y_size / 4;

    //Generate output frame
    free(i420_output_frame.data);
    i420_output_frame.width = out_width;
    i420_output_frame.height = out_height;
    i420_output_frame.data = new unsigned char[out_size * 3 / 2];
    i420_output_frame.y = i420_output_frame.data;
    i420_output_frame.u = i420_output_frame.y + out_size;
    i420_output_frame.v = i420_output_frame.u + out_size / 4;
    ...

probably your code is based on that https://github.com/begeekmyfriend/yasea/blob/master/library/src/main/libenc/jni/libenc.cc and according to that code you have to use the y_size


来源: stackexchange

问:
Access VBA Function doesn't return any value on query
I have the following Access VBA Module (which returns info as needed as i tested it via Debug.Print), i then use it the following way in the SQL code.

```<code>Public Function DayInterval(DueDate As String) As String
Dim Today As Date
Dim ConvertData As Date

Today = Date
ConvertDate = DateSerial(Year(DueDate), Month(DueDate), Day(DueDate))

Select Case DateDiff("d", ConvertDate, Today)
    Case 1 To 10
      DueDate = "0-10"
    Case 11 To 30
      DueDate = "11-30"
    Case 31 To 60
      DueDate = "31-60"
    Case 61 To 90
      DueDate = "61-90"
   Case 91 To 180
      DueDate = "91-180"
   Case 181 To 365
      DueDate = "181-365"
   Case 366 To 540
      DueDate = "366-540"
   Case 541 To 730
      DueDate = "541-730"
   Case Else
      DueDate = ">730"
End Select

DayInterval = DueDate

End Function

SELECT
DueDate AS [Date],
DayInterval([DUE_DATE]) AS [Interval]
FROM Invoices;
</code>```

The problem is that when i run the above query, i get no results.

Any light on why this happens?

Thank you.

答:
You must use a true date value:

```<code>ConvertDate = DateSerial(Year(DateValue(DueDate)), Month(DateValue(DueDate)), Day(DateValue(DueDate)))
</code>```

Or just (see Minty's comment):

```<code>ConvertDate = DateValue(DueDate)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following Access VBA Module (which returns info as needed as i tested it via Debug.Print), i then use it the following way in the SQL code.

Public Function DayInterval(DueDate As String) As String
Dim Today As Date
Dim ConvertData As Date

Today = Date
ConvertDate = DateSerial(Year(DueDate), Month(DueDate), Day(DueDate))

Select Case DateDiff("d", ConvertDate, Today)
    Case 1 To 10
      DueDate = "0-10"
    Case 11 To 30
      DueDate = "11-30"
    Case 31 To 60
      DueDate = "31-60"
    Case 61 To 90
      DueDate = "61-90"
   Case 91 To 180
      DueDate = "91-180"
   Case 181 To 365
      DueDate = "181-365"
   Case 366 To 540
      DueDate = "366-540"
   Case 541 To 730
      DueDate = "541-730"
   Case Else
      DueDate = ">730"
End Select

DayInterval = DueDate

End Function

SELECT
DueDate AS [Date],
DayInterval([DUE_DATE]) AS [Interval]
FROM Invoices;

The problem is that when i run the above query, i get no results.

Any light on why this happens?

Thank you.

Body:
You must use a true date value:

ConvertDate = DateSerial(Year(DateValue(DueDate)), Month(DateValue(DueDate)), Day(DateValue(DueDate)))

Or just (see Minty's comment):

ConvertDate = DateValue(DueDate)


问:
SVG : Link to a location in the containing document
I'm currently developing a site which uses a SVG based map, with clickable points in it. Idealy I would like these maps to point to locations in the HTML document that contains it (one for each region).

HTML :

```<code><object type="image/svg+xml" data="https://ffu.jmaris.me/carte.svg">
  Your browser does not support SVG
</object>
<div id="region1" class="region"> Stuff ...</div>
<div id="region2" class="region"> Stuff ...</div>
<div id="region3" class="region"> Stuff ...</div>
<div id="region4" class="region"> Stuff ...</div>
</code>```

CSS :

```<code>.region {display:none;}
.region div:target{display:block;}
</code>```

I'd like to be able to point to page.html#region2 inside my SVG without using absolute paths (as its currently running on a developpment server,and, in addition, after deployment the URL risks changing in the future.

Is there a way to do this ?

Thanks in advance

答:
You'd have to rely on javascript here.

Anchors () inside an <object> will change the object's document's location, so we can't use it directly.

However, if your files share the same origin, and that you are not running the whole thing in an overly protected iframe like the ones of stacksnippets™ you can access the parent document quite easily :

```<code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100">
    <a id="loc1" xlink:href="#">
      <rect x="0" y="0" width="20" height="20" fill="green"/>
    </a>
    <a id="loc2" xlink:href="#">
      <rect x="50" y="0" width="20" height="20" fill="red"/>
    </a>
    <script>
    var anchors = document.querySelectorAll('a');
    anchors.forEach(function(a){
        a.addEventListener('click', function(e){
            // where anchor's id represent parent doc element's ids.
            window.parent.location.hash = this.id;
            });
        });
    </script>
</svg>
</code>```

Live plunker

And a workaround which uses the PostMessage API for overly protected iframes :

window.onmessage = e => {
  // you may want to be sure this is the message you want
  window.location.hash = e.data;
}
// here it would be saved as an external file
document.querySelector('object').data = URL.createObjectURL(new Blob([`
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100">

    <rect x="0" y="0" width="20" height="20" fill="green"/>

    <rect x="50" y="0" width="20" height="20" fill="red"/>

Body:
I'm currently developing a site which uses a SVG based map, with clickable points in it. Idealy I would like these maps to point to locations in the HTML document that contains it (one for each region).

HTML :

<object type="image/svg+xml" data="https://ffu.jmaris.me/carte.svg">
  Your browser does not support SVG
</object>

 Stuff ...

 Stuff ...

 Stuff ...

 Stuff ...

CSS :

.region {display:none;}
.region div:target{display:block;}

I'd like to be able to point to page.html#region2 inside my SVG without using absolute paths (as its currently running on a developpment server,and, in addition, after deployment the URL risks changing in the future.

Is there a way to do this ?

Thanks in advance

Body:
You'd have to rely on javascript here.

Anchors (<a>) inside an <object> will change the object's document's location, so we can't use it directly.

However, if your files share the same origin, and that you are not running the whole thing in an overly protected iframe like the ones of stacksnippets™ you can access the parent document quite easily :

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100">
    <a id="loc1" xlink:href="#">
      <rect x="0" y="0" width="20" height="20" fill="green"/>
    </a>
    <a id="loc2" xlink:href="#">
      <rect x="50" y="0" width="20" height="20" fill="red"/>
    </a>
    <script>
    var anchors = document.querySelectorAll('a');
    anchors.forEach(function(a){
        a.addEventListener('click', function(e){
            // where anchor's id represent parent doc element's ids.
            window.parent.location.hash = this.id;
            });
        });
    </script>
</svg>

Live plunker

And a workaround which uses the PostMessage API for overly protected iframes :

window.onmessage = e => {
  // you may want to be sure this is the message you want
  window.location.hash = e.data;
}
// here it would be saved as an external file
document.querySelector('object').data = URL.createObjectURL(new Blob([`
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100">
  <a id="loc1" xlink:href="#">
    <rect x="0" y="0" width="20" height="20" fill="green"/>
  </a>
  <a id="loc2" xlink:href="#">
    <rect x="50" y="0" width="20" height="20" fill="red"/>
  </a>
  <script>
  var anchors = document.querySelectorAll('a');
  anchors.forEach(function(a){
    a.addEventListener('click', function(e){
      // post our #id
      window.parent.postMessage( this.id, '*' );
      });
    });
  <\/script>
</svg>
`], {
  type: 'image/svg+xml'
}));

div {
  margin-top: 100vh;
}

<object data="file.svg"></object>
<div id="loc1">loc1</div>
<div id="loc2">loc2</div>


问:
How to avoid having 2 times | async in this situation (4.0.0)?
I would like to avoid to use .subscribe() in this component.
I tried *ngIf="user$ | async as user" but it did not work.

How can I make a local variable with user$ | async un order to use it at different places in this view?

<app-xpbar *ngIf="user$ | async"></app-xpbar>

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user$ | async"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

```

答:
Update

As @yurzui pointed out, this only works if the references to the introduced variable user are within the <pp-xpbar> element where it's introduced.
Otherwise the variable won't be in scope (like in the code example below)

Original

In Angular4 you can use

<app-xpbar *ngIf="user$ | async; let user"></app-xpbar>

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

```

See also

https://github.com/angular/angular/blob/master/CHANGELOG.md#400-beta0-2016-12-15

https://github.com/angular/angular/commit/b4db73d

https://github.com/angular/angular/issues/13061

https://github.com/angular/angular/pull/13297

For the as syntax mentioned in the comments see

https://github.com/angular/angular/blob/master/CHANGELOG.md#400-rc4-2017-03-17

Body:
Update

As @yurzui pointed out, this only works if the references to the introduced variable user are within the <pp-xpbar> element where it's introduced.
Otherwise the variable won't be in scope (like in the code example below)

Original

In Angular4 you can use

<app-xpbar *ngIf="user$ | async; let user"></app-xpbar>

<header class="header">

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

</header>

See also

https://github.com/angular/angular/blob/master/CHANGELOG.md#400-beta0-2016-12-15

https://github.com/angular/angular/commit/b4db73d

https://github.com/angular/angular/issues/13061

https://github.com/angular/angular/pull/13297

For the as syntax mentioned in the comments see

https://github.com/angular/angular/blob/master/CHANGELOG.md#400-rc4-2017-03-17


问:
PHP return array if breaking chain in singleton
I've built a singleton class with chaining methods (to be used in a template).

To make chaining work I need to return new static. It allows the next chain to be added. The problem I have is that I don't want to return the static object if there are no more chains.

Example

```<code><?php
class bread {
  public static $array;
  public static function blueprints() {
    static::$array = array('some', 'values');
    return new static;
  }
  public static function fields() {
    return static::$array;
  }
}

$blueprints = bread::blueprints();
$fields = bread::blueprints()->fields();

print_r($blueprint) // Returns object - FAIL
print_r($fields ) // Returns array - OK
</code>```

In the example above I want $blueprints to return an array, because there are no more methods chained on it.

How can that be done?

答:
You can try this:
$blueprints = (array)bread::blueprints();</p>

Body:
I've built a singleton class with chaining methods (to be used in a template).

To make chaining work I need to return new static. It allows the next chain to be added. The problem I have is that I don't want to return the static object if there are no more chains.

Example

<?php
class bread {
  public static $array;
  public static function blueprints() {
    static::$array = array('some', 'values');
    return new static;
  }
  public static function fields() {
    return static::$array;
  }
}

$blueprints = bread::blueprints();
$fields = bread::blueprints()->fields();

print_r($blueprint) // Returns object - FAIL
print_r($fields ) // Returns array - OK

In the example above I want $blueprints to return an array, because there are no more methods chained on it.

How can that be done?


问:
How to determine DICOM / DICOMDIR images relationship?
The DICOM images have "Slice location" parameter recorded in addition to the "Slice Thickness".

Question: "Slice location" in where? I understand it's in the body depth - but it must be in images as well, right?

I think a series must or may have a corresponding series in which we can find a reference of the "Slice Location".

If I am right, How to find that those images?  And then how to establish the point of the slice in the corresponding images?

As well, if you know a well written refference guide to dicom image structure, please share.

Thanks a lot.

答:
Here's a page that contains some good information on DICOM:

http://www.thefullwiki.org/DICOM

As to your question; I think you're looking for the "image number", which defines an order to the image.  The "slice location" is a spatial coordinate as to the offset of the image slice; the "image number" is an integer indicating the order of an image in reference to other images.  YMMV; DICOM is a very loosely adhered to standard.

ContentLicense: CC BY-SA 2.5


问:
wordpress error url image when upload change "htpp" not "http"
wordpress error url image when upload change "htpp" not "http"

See this image:

Any help?

答: Check Wordpress Address and Site Address in Settings -> General options.


问:
"ImportError no module named gnuradio" when trying to execute ./uhd_fft
I have followed instructions out lined here:

http://forums.nuand.com/forums/viewtopic.php?f=9&t=2804

and installed GNU Radio from GIT repo (scroll down to the section that says "Building GNURADIO from GIT".  I used the ./build-gnuradio.sh script to do this and it took a while, but it appeared to build successfully, as per the instructions.

I am running on Ubuntu 12.04 LTS.

When I attempt to run the "./uhd_fft" function I get the following error message:

```<code>Traceback (most recent call last):
  File "./uhd_fft", line 23, in <module>
    from gnuradio import gr, gru
ImportError: No module named gnuradio
</code>```

I have Googled this error message and most of the forums claim there is a problem with the PYTHONPATH.

When I do

```<code>echo $PYTHONPATH
/usr/bin/python2.7
</code>```

But when I check the python2.7 directory I do not see gnuradio.  So I guess it makes sense I'm getting an import error when it tries to import gnuradio. But the bigger question is why?

I installed GNU Radio (per instructions from nuand forum) using ./build-gnuradio.sh script.  So I should have it installed.

I would appreciate if it python / GNU Radio experts from the community could weigh in.

答:
One of the reason for this error is, when the default python is selected incorrectly. To see which python is selected type the following command in the Terminal:

```<code>      "sudo port select python"
</code>```

it will display all the python available on your mac.
like:

```<code>    python26

    python27-apple(Active)

    python27
</code>```

For Gnuradio you need python27,if other python is active like in the example above you can change it by the following command:

```<code>    "sudo port select python python27"
</code>```

Now RUN your python code,it should work.If python27 is already active you may consider changing the path manually as suggested by others

Body:
I have followed instructions out lined here:

http://forums.nuand.com/forums/viewtopic.php?f=9&t=2804

and installed GNU Radio from GIT repo (scroll down to the section that says "Building GNURADIO from GIT".  I used the ./build-gnuradio.sh script to do this and it took a while, but it appeared to build successfully, as per the instructions.

I am running on Ubuntu 12.04 LTS.

When I attempt to run the "./uhd_fft" function I get the following error message:

Traceback (most recent call last):
  File "./uhd_fft", line 23, in <module>
    from gnuradio import gr, gru
ImportError: No module named gnuradio

I have Googled this error message and most of the forums claim there is a problem with the PYTHONPATH.

When I do

echo $PYTHONPATH
/usr/bin/python2.7

But when I check the python2.7 directory I do not see gnuradio.  So I guess it makes sense I'm getting an import error when it tries to import gnuradio. But the bigger question is why?

I installed GNU Radio (per instructions from nuand forum) using ./build-gnuradio.sh script.  So I should have it installed.

I would appreciate if it python / GNU Radio experts from the community could weigh in.

Body:
One of the reason for this error is, when the default python is selected incorrectly. To see which python is selected type the following command in the Terminal:

      "sudo port select python"

it will display all the python available on your mac.
like:

    python26

    python27-apple(Active)

    python27

For Gnuradio you need python27,if other python is active like in the example above you can change it by the following command:

    "sudo port select python python27"

Now RUN your python code,it should work.If python27 is already active you may consider changing the path manually as suggested by others


问:
How to add the UDID to the testFlight Portal
Hi one of our team members wants to add their device to the testFlight account, I have sent the Invitation from the portal and they have accepted It, and I need UDID of that device for the provision profile, they should send it manually?or TestFlight Portal will fetch their UDID If they just accept the invitation ?

答:
Ask user to send his UDID and his Apple id.(User can find his UDID by connecting the device to mac,then go to iTunes -> click on device icon -> click on serial number. For Apple id go to Settings -> iTunes & App store)

Add the UDID in developer account(under device section).

Create provisioning profile.

Now login to itunesconnect.apple.com,go to Users and Roles, add the user using user's Apple id(user's Apple id you got in step 1).

Once you add the user, test flight will send the invitation mail to the user on given Apple id(generally it's a mail id user used to sign in to itunes). Ask user the to accept the invitation which he got on Apple id(mail id).

Once user accept the invitation, upload your build to TestFlight using Xcode.

Now go to iTunes-> My apps -> Select your app  -> TestFlight -> Internal Testing -> Add internal tester(user you added in step 5) -> select version to test(select the build you have just uploaded from Xcode).

Once you click on start testing, user will get the Testflight notification on their device to download the app.

Note: In order to upload the build to iTunes, you should create your app in iTunes under My Apps section -> +.


问:
C++ array pointer
I came across a C++ program like this

```<code>#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}
</code>```

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

答:
a is an int-array with 10 elements: int [10]. b is a pointer to an int-array with 5 elements: int (*) [5]. b is initialized with the value of a and explicitly casted using the C-style cast: (int(*)[5]) a.

Effectively a is a 1x10 matrix and b is a 2x5 matrix, it is in fact a "reshape" of a into b, with the same content. The "most" dangerous thing here is that the reshape does not perform a deep copy, i.e., changes to b also affect a and vice versa;

The type, here int, is completely irrelevant. Here is an online example, with several different types.

Title: C++ array pointer

Body:
I came across a C++ program like this

#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?


问:
Can I prevent function execution using &=?
Example code follows:

```<code>bool result;
result = Operation1();
result &= Operation2();
result &= Operation3();
return result;
</code>```

The intention is to ensure that, if any of the functions returns false, the functions that follow are not called. Is this syntax correct or do I need to do result = result && Operation2();?

答:
I generally see this pattern written as:</p>

```<code>bool result = true;
result = result && Operation1();
result = result && Operation2();
result = result && Operation3();
return result;
</code>```

Body:
Example code follows:

bool result;
result = Operation1();
result &= Operation2();
result &= Operation3();
return result;

The intention is to ensure that, if any of the functions returns false, the functions that follow are not called. Is this syntax correct or do I need to do result = result && Operation2();?

Body:
I generally see this pattern written as:

bool result = true;
result = result && Operation1();
result = result && Operation2();
result = result && Operation3();
return result;


问:
subprocess not running the command generated though the command works on terminal
```<code>cmd= ["sudo", "cat", "{filepath}".format(filepath=filepath), "|","egrep", "-v","\'{filteruser}\'".format(filteruser=filteruser)]
</code>```

fileformat and filteruser can be blank too

config file below

```<code>[plugin_haproxy]
user= tara
host=localhost
filepath=/etc/haproxy/haproxy.global.inc
filter=
</code>```

This is the command I want to run on subprocess, checking the above variable values with pdb shows bellow value and looks great

```<code>['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]
</code>```

Manullay running the code sudo cat /etc/haproxy/haproxy.global.inc | egrep -v " '' " on terminal works great

Why is subprocess not able to process it.

"cat: |: No such file or directory\ncat: egrep: No such file or
  directory\ncat:

答:
You can either use shell=True as was already suggested, or use subprocess to pipe:

```<code>p1 = subprocess.Popen(['sudo', 'cat', '/etc/haproxy/haproxy.global.inc'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['egrep', '-v', "''"], stdin=p1.stdout,stdout=subprocess.PIPE)
</code>```

Body:
cmd= ["sudo", "cat", "{filepath}".format(filepath=filepath), "|","egrep", "-v","\'{filteruser}\'".format(filteruser=filteruser)]

fileformat and filteruser can be blank too

config file below

[plugin_haproxy]
user= tara
host=localhost
filepath=/etc/haproxy/haproxy.global.inc
filter=

This is the command I want to run on subprocess, checking the above variable values with pdb shows bellow value and looks great

['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]

Manullay running the code sudo cat /etc/haproxy/haproxy.global.inc | egrep -v " '' " on terminal works great

Why is subprocess not able to process it.

"cat: |: No such file or directory\ncat: egrep: No such file or
  directory\ncat:

Body:
You can either use shell=True as was already suggested, or use subprocess to pipe:

p1 = subprocess.Popen(['sudo', 'cat', '/etc/haproxy/haproxy.global.inc'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['egrep', '-v', "''"], stdin=p1.stdout,stdout=subprocess.PIPE)


问:
Multi language using Codeigniter
Confuse to use multi language using codeigniter.

Example,
my domain is www.example.com
then I have 3 language, English (en), Japan (jp), China (cn)
and now I need access every language like:

```<code>www.example.com/en/bla-bla/
www.example.com/jp/bla-bla/
www.example.com/cn/bla-bla/
</code>```

but, I dont want make controller every language.
have you idea ?

答:
You should use routing to pass language as variable to your controller to display content in correct language. For example you can do it like that:
In application\config\routes.php

```<code>$route['(:any)/product'] = 'product/index/$1';
</code>```

In controller:

```<code>class Product extends CI_Controller
{
    public function index($lang = '') {
        //for link http://example.com/en/product there will be 'en' in $lang
    }
}
</code>```

Documentation:
https://www.codeigniter.com/user_guide/general/routing.html

Title: Multi language using Codeigniter

Body:
Confuse to use multi language using codeigniter.

Example,
my domain is www.example.com
then I have 3 language, English (en), Japan (jp), China (cn)
and now I need access every language like:

www.example.com/en/bla-bla/
www.example.com/jp/bla-bla/
www.example.com/cn/bla-bla/

but, I dont want make controller every language.
have you idea ?

Body:
You should use routing to pass language as variable to your controller to display content in correct language. For example you can do it like that:
In application\config\routes.php

$route['(:any)/product'] = 'product/index/$1';

In controller:

class Product extends CI_Controller
{
    public function index($lang = '') {
        //for link http://example.com/en/product there will be 'en' in $lang
    }
}

Documentation:
https://www.codeigniter.com/user_guide/general/routing.html


问:
How to run a plugin only on a particular platform
I have a maven plugin that only needs to execute on linux. I found this configuration that seems to work

How do I make this plugin run only on non-Windows platforms?

```<code><profiles>
  <profile>
    <activation>
      <os>
        <family>!mac</family>
      </os>
    </activation>
    <build>
      <plugins>
        <plugin>
          ...
        </plugin>
      </plugins>
    </build>
    ...
  </profile>
</profiles>
</code>```

How do I modify it so that it executes only on linux?

答:
There is no OS <family> value that distinguishes Linux from Unixes, but you can use <name> instead.

```<code><profiles>
  <profile>
    <activation>
      <os>
        <name>Linux</name>
      </os>
    </activation>
    <build>
      <plugins>
        <plugin>
          ...
        </plugin>
      </plugins>
    </build>
    ...
  </profile>
</profiles>
</code>```

FYI, to double-check the value for <name> on your Linux machine, execute java -XshowSettings:properties and look for the os.name property. (On all Linux distributions I have checked, this is just Linux.)

Body:
I have a maven plugin that only needs to execute on linux. I found this configuration that seems to work

How do I make this plugin run only on non-Windows platforms?

<profiles>
  <profile>
    <activation>
      <os>
        <family>!mac</family>
      </os>
    </activation>
    <build>
      <plugins>
        <plugin>
          ...
        </plugin>
      </plugins>
    </build>
    ...
  </profile>
</profiles>

How do I modify it so that it executes only on linux?

Body:
There is no OS <family> value that distinguishes Linux from Unixes, but you can use <name> instead.

<profiles>
  <profile>
    <activation>
      <os>
        <name>Linux</name>
      </os>
    </activation>
    <build>
      <plugins>
        <plugin>
          ...
        </plugin>
      </plugins>
    </build>
    ...
  </profile>
</profiles>

FYI, to double-check the value for <name> on your Linux machine, execute java -XshowSettings:properties and look for the os.name property. (On all Linux distributions I have checked, this is just Linux.)


问:
Website will download instead of opening in browser
My website will initiate a download instead of opening in the browser. I can access the login redirect and wp-admin however.

website is: www.keymoneyconcepts.com.au

My .htaccess file looks like the below:

# BEGIN WordPress
<IfModule mod_expires.c>
 ExpiresActive On
 ExpiresByType image/jpg "access plus 1 year"
 ExpiresByType image/jpeg "access plus 1 year"
 ExpiresByType image/gif "access plus 1 year"
 ExpiresByType image/png "access plus 1 year"
 ExpiresByType text/css "access plus 1 month"
 ExpiresByType application/pdf "access plus 1 month"
 ExpiresByType text/javascript "access plus 1 month"
 ExpiresByType image/x-icon "access plus 1 year"
 ExpiresDefault "access plus 1 weeks"
</IfModule>
Options -Indexes
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^/wp-content/endurance-page-cache/ - [L]
 RewriteCond %{REQUEST_METHOD} !POST
 RewriteCond %{QUERY_STRING} !.*=.*
 RewriteCond %{HTTP_COOKIE} !(wordpress_test_cookie|comment_author|wp\-postpass|wordpress_logged_in|wptouch_switch_toggle|wp_woocommerce_session_) [NC]
 RewriteCond %{DOCUMENT_ROOT}/wp-content/endurance-page-cache/$1/_index.html -f
 RewriteRule ^(.*)$ /wp-content/endurance-page-cache/$1/_index.html [L]
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress```

Would you have any suggestions?

Thanks

答:
check it via fiddler,
i got

HTTP/1.1 200 OK
Server: Apache
Last-Modified: Fri, 10 Mar 2017 00:21:28 GMT
ETag: "1a2-54a5557bcafa7"
Cache-Control: max-age=604800
Expires: Wed, 05 Apr 2017 01:25:19 GMT
Content-Type: application/x-httpd-php
X-Cacheable: YES
Content-Length: 418
Accept-Ranges: bytes
Date: Wed, 29 Mar 2017 08:51:08 GMT
X-Varnish: 657727275 657725514
Age: 26749
Via: 1.1 varnish
Connection: keep-alive

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( FILE ) . '/wp-blog-header.php' );

Body:
My website will initiate a download instead of opening in the browser. I can access the login redirect and wp-admin however.

website is: www.keymoneyconcepts.com.au

My .htaccess file looks like the below:

# BEGIN WordPress
<IfModule mod_expires.c>
 ExpiresActive On
 ExpiresByType image/jpg "access plus 1 year"
 ExpiresByType image/jpeg "access plus 1 year"
 ExpiresByType image/gif "access plus 1 year"
 ExpiresByType image/png "access plus 1 year"
 ExpiresByType text/css "access plus 1 month"
 ExpiresByType application/pdf "access plus 1 month"
 ExpiresByType text/javascript "access plus 1 month"
 ExpiresByType image/x-icon "access plus 1 year"
 ExpiresDefault "access plus 1 weeks"
</IfModule>
Options -Indexes
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^/wp-content/endurance-page-cache/ - [L]
 RewriteCond %{REQUEST_METHOD} !POST
 RewriteCond %{QUERY_STRING} !.*=.*
 RewriteCond %{HTTP_COOKIE} !(wordpress_test_cookie|comment_author|wp\-postpass|wordpress_logged_in|wptouch_switch_toggle|wp_woocommerce_session_) [NC]
 RewriteCond %{DOCUMENT_ROOT}/wp-content/endurance-page-cache/$1/_index.html -f
 RewriteRule ^(.*)$ /wp-content/endurance-page-cache/$1/_index.html [L]
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Would you have any suggestions?

Thanks


问:
HTML CSS - Images not displaying?
```<code><td class="participants">
   <img alt="" src="https://s3.amazonaws.com/app-name-production/profile_pics/1/small/xxxxx.jpeg">
   <img alt="xxxxxxxx" src="https://s3.amazonaws.com/app-name-production/profile_pics/5/small/xxxxx.jpg">
 </td>
</code>```

Hello, I have the follow code block above which shows images. this div is shown via an AJAX request which then injects the images into the page. Everything in the injection works fine, text, links etc, except for these images.

For some reason sometimesthe images don't show in the browser? But if I highlight the text with my mouse they show up, or if I refresh they'll show up.

What would cause the images not to appear on the page when everything else is?

```<code>Adding CSS:

.table-request-list .participants {
text-align: left;
width: 180px;
}
.table-request-list table td {
vertical-align: middle;
}
.table-request-list .request-item, .conversation-item td {
border-bottom: 1px solid #ECECEC;
}
.table-request-list .participants img {
vertical-align: bottom;
}
</code>```

答: The issue was that the floated divs didn't have hard width and heights. Adding that did the trick.</p>

Title: HTML CSS - Images not displaying?

Body:
Hello, I have the follow code block above which shows images. this div is shown via an AJAX request which then injects the images into the page. Everything in the injection works fine, text, links etc, except for these images.

For some reason sometimesthe images don't show in the browser? But if I highlight the text with my mouse they show up, or if I refresh they'll show up.

What would cause the images not to appear on the page when everything else is?

Adding CSS:

.table-request-list .participants {
text-align: left;
width: 180px;
}
.table-request-list table td {
vertical-align: middle;
}
.table-request-list .request-item, .conversation-item td {
border-bottom: 1px solid #ECECEC;
}
.table-request-list .participants img {
vertical-align: bottom;
}


问:
How to insert strings in Array? Using BASH script
Here is the text in myText.txt:

```<code>   a    d
   b    e
   c    f
</code>```

a and d are separated with \t and each row are separated with \n. I would like to insert these in an two arrays.

This must be the content:

```<code>  arr1=(a b c)
  arr2=(d e f)
</code>```

Code done so far:

```<code>  c1=`cat $2 | cut -f1`
  c2=`cat $2 | cut -f2`
</code>```

But I don't know how to place these values in the array/s.

答:
Lets built the variable first:

```<code>a=$'a\td\nb\te\nc\tf'
echo "$a"
#Output
a       d
b       e
c       f
</code>```

Split to arrays with pure bash:

```<code>while IFS=$'\t' read -r var1 var2; do
arr1+=("$var1")
arr2+=("$var2")
done <<<"$a"
declare -p arr1 arr2
#Output
declare -a arr1='([0]="a" [1]="b" [2]="c")'
declare -a arr2='([0]="d" [1]="e" [2]="f")'
</code>```

Split to arrays with bash and awk , without loop:

```<code>arr1=($(awk -F'\t' '{print $1}' <<<"$a"))
arr2=($(awk -F'\t' '{print $2}' <<<"$a"))
#Output as before
</code>```

Body:
Here is the text in myText.txt:

   a    d
   b    e
   c    f

a and d are separated with \t and each row are separated with \n. I would like to insert these in an two arrays.

This must be the content:

  arr1=(a b c)
  arr2=(d e f)

Code done so far:

  c1=`cat $2 | cut -f1`
  c2=`cat $2 | cut -f2`

But I don't know how to place these values in the array/s.

Body:
Lets built the variable first:

a=$'a\td\nb\te\nc\tf'
echo "$a"
#Output
a       d
b       e
c       f

Split to arrays with pure bash:

while IFS=$'\t' read -r var1 var2; do
arr1+=("$var1")
arr2+=("$var2")
done <<<"$a"
declare -p arr1 arr2
#Output
declare -a arr1='([0]="a" [1]="b" [2]="c")'
declare -a arr2='([0]="d" [1]="e" [2]="f")'

Split to arrays with bash and awk , without loop:

arr1=($(awk -F'\t' '{print $1}' <<<"$a"))
arr2=($(awk -F'\t' '{print $2}' <<<"$a"))
#Output as before


问:
Can't save hashed password to database using bcrypt and bookshelf
Still quite new to nodejs, so I frequently get tripped up by the whole asynchronous thing. I am attempting to hash a password before storing it in the database, using bcrypt and bookshelf. Pretty straight forward right...

I am calling the save action like so,

```<code>create(data) {
    this.logger.info(`creating account`);
    return bookshelf.transaction(trx => {
        return new Account().save(data, { method: 'insert', transacting: trx });
    });
}
</code>```

and in the account model, I intercept the save action

```<code>initialize: function() {
    let _this = this;
    const saltRounds = 10;
    _this.on('creating', function () {
        bcrypt.genSaltSync(saltRounds, function(err, salt) {
            bcrypt.hashSync(_this.get('password'), salt, function (err, hash) {
                if (err) throw err;

                _this.set('password', hash);
            });
        });
    });
}
</code>```

Everything i've looked up so far says this should work, but the plain text password is still getting saved into the database instead of the hashed password. What am I doing wrong?

答:
i am not sure but i believe the error is because you are using es6 let and not var
then the context of this will defer </p>

Body:
Still quite new to nodejs, so I frequently get tripped up by the whole asynchronous thing. I am attempting to hash a password before storing it in the database, using bcrypt and bookshelf. Pretty straight forward right...

I am calling the save action like so,

create(data) {
    this.logger.info(`creating account`);
    return bookshelf.transaction(trx => {
        return new Account().save(data, { method: 'insert', transacting: trx });
    });
}

and in the account model, I intercept the save action

initialize: function() {
    let _this = this;
    const saltRounds = 10;
    _this.on('creating', function () {
        bcrypt.genSaltSync(saltRounds, function(err, salt) {
            bcrypt.hashSync(_this.get('password'), salt, function (err, hash) {
                if (err) throw err;

                _this.set('password', hash);
            });
        });
    });
}

Everything i've looked up so far says this should work, but the plain text password is still getting saved into the database instead of the hashed password. What am I doing wrong?


问:
How to re-open something after used `JQuery.remove()`?
I used a free template for my app and with this template there is a button to "hide" list like this:

the little x button

And the executed code is the following one:

```<code>$(document).on('click', '.close-link', function () {
   var $BOX_PANEL = $(this).closest('.x_panel');
   $BOX_PANEL.remove();
});
</code>```

Now I'm trying to add a button to re-open this list but here comes the struggle I can't find a way to do that. I checked the documentation of JQuery remove() and there is not JQuery open()...

Do you guy have an idea ?

[EDIT] maybe the HTML would be great so :

```<code><div class="col-md-6 col-sm-12 col-xs-12">
    <div class="x_panel">
        <div class="x_title">
            <h2>Machines</h2>
               <ul class="nav navbar-right panel_toolbox">
                  <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                  <li class="dropdwon">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                     <ul class="dropdown-menu" role="menu"></ul>
                  </li>
                  {{#if isNotHome}}<li><a class="backLocalHostDocker"><i class="fa fa-home"></i></a></li>{{/if}}
                  <li><a class="close-link" id="closeList"><i class="fa fa-close"></i></a></li>
              </ul>
           <div class="clearfix"></div>
         </div>
         <div class="x_content">
             <br />
             <ul class="container"></ul>
         </div>
    </div>
</div>
</code>```

I just cleaned the code to just display the structure

答:
Use jQuery detach()

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

jQuery detach()

Body:
I used a free template for my app and with this template there is a button to "hide" list like this:

the little x button

And the executed code is the following one:

$(document).on('click', '.close-link', function () {
   var $BOX_PANEL = $(this).closest('.x_panel');
   $BOX_PANEL.remove();
});

Now I'm trying to add a button to re-open this list but here comes the struggle I can't find a way to do that. I checked the documentation of JQuery remove() and there is not JQuery open()...

Do you guy have an idea ?

[EDIT] maybe the HTML would be great so :

Machines

                  {{#if isNotHome}}

{{/if}}

I just cleaned the code to just display the structure


问:
How to print struct variables in console?
How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang?

```<code>type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    Data    `json:"data"`
    Commits Commits `json:"commits"`
}
</code>```

答:
I think it would be better to implement a custom stringer if you want some kind of formatted output of a struct

for example

```<code>package main

    import "fmt"

    type Project struct {
        Id int64 `json:"project_id"`
        Title string `json:"title"`
        Name string `json:"name"`
    }

    func (p Project) String() string {
        return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title, p.Name)
    }

    func main() {
        o := Project{Id: 4, Name: "hello", Title: "world"}
        fmt.Printf("%+v\n", o)
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang?

type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    Data    `json:"data"`
    Commits Commits `json:"commits"`
}

Body:
I think it would be better to implement a custom stringer if you want some kind of formatted output of a struct

for example

package main

    import "fmt"

    type Project struct {
        Id int64 `json:"project_id"`
        Title string `json:"title"`
        Name string `json:"name"`
    }

    func (p Project) String() string {
        return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title, p.Name)
    }

    func main() {
        o := Project{Id: 4, Name: "hello", Title: "world"}
        fmt.Printf("%+v\n", o)
    }


问:
Convert CSV to XML when CSV contains both character and number data
From this thread, I got the basic info on how to parse CSV to create XML. Unfortunately, the text fields (all enclosed in quotes) sometimes contain commas, so line.split(',') gives me too many columns. I can't figure out how to parse the CSV so line.split(',') distinguishes between commas within a text field, and commas separating fields. Any thoughts on how to do that?

Thanks!

答: If your CSV files are too complex to make writing your own parser practical, use another parser.  The Office ACE OLEDB provider may already be available on your system, but may be overkill for your purposes.  I haven't used any of the lightweight alternatives, so I can't speak to their suitability.</p>


问:
OpenCV: Replace ilLoadImage with cv::imread
I'm using hessgpu for efficiently compute hessian-affine SIFT descriptors using GPUs.

In this project, Devil is used for reading images: if SiftGPU::RunSIFT(const char *imgpath) is called (implemented here), then ilLoadImage is used in GLTexImage.cpp for reading images (as RGB images).

However, in my project I use cv::imread to read images. The project provides SiftGPU::RunSIFT(int width, int height, const void * data, unsigned int gl_format, unsigned int gl_type) to compute descriptors from data provided directly from the user.

So I tried:

```<code>cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
sift.RunSIFT(img.cols, img.rows, img.data, GL_LUMINANCE, GL_UNSIGNED_BYTE);
</code>```

But this produce slightly less keypoints than sift.RunSIFT("image.jpg");. I tried to use:

```<code>cv::Mat img = cv::imread("image.jpg");
sift.RunSIFT(img.cols, img.rows, img.data, GL_RGB, GL_UNSIGNED_BYTE);
</code>```

But this produces 0 keypoints, so something very wrong happens. I think:

iLoadImage uses RGB image, while the only working method that I found up to now using cv::imread works only with grayscale images.

It's possible that devil use a different process to read images than OpenCV, espcecially for RGB images (since using the second approach produced 0 keypoints).

How can I do the equivalent of ilLoadimage using cv::imread?

答:
It seems that something's wrong with types, try this one:

```<code>Mat img = imread("image.jpg");
sift.RunSIFT(img.cols, img.rows, img.data, GL_BGR, GL_3_BYTES);
</code>```

Or this one

```<code>cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
sift.RunSIFT(img.cols, img.rows, img.data, GL_RED, GL_UNSIGNED_BYTE);
</code>```

Body:
I'm using hessgpu for efficiently compute hessian-affine SIFT descriptors using GPUs.

In this project, Devil is used for reading images: if SiftGPU::RunSIFT(const char *imgpath) is called (implemented here), then ilLoadImage is used in GLTexImage.cpp for reading images (as RGB images).

However, in my project I use cv::imread to read images. The project provides SiftGPU::RunSIFT(int width, int height, const void * data, unsigned int gl_format, unsigned int gl_type) to compute descriptors from data provided directly from the user.

So I tried:

cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
sift.RunSIFT(img.cols, img.rows, img.data, GL_LUMINANCE, GL_UNSIGNED_BYTE);

But this produce slightly less keypoints than sift.RunSIFT("image.jpg");. I tried to use:

cv::Mat img = cv::imread("image.jpg");
sift.RunSIFT(img.cols, img.rows, img.data, GL_RGB, GL_UNSIGNED_BYTE);

But this produces 0 keypoints, so something very wrong happens. I think:

iLoadImage uses RGB image, while the only working method that I found up to now using cv::imread works only with grayscale images.

It's possible that devil use a different process to read images than OpenCV, espcecially for RGB images (since using the second approach produced 0 keypoints).

How can I do the equivalent of ilLoadimage using cv::imread?

Body:
It seems that something's wrong with types, try this one:

Mat img = imread("image.jpg");
sift.RunSIFT(img.cols, img.rows, img.data, GL_BGR, GL_3_BYTES);

Or this one

cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
sift.RunSIFT(img.cols, img.rows, img.data, GL_RED, GL_UNSIGNED_BYTE);


问:
Create edge from attribute with ArangoDB AQL
I have imported a list of documents (in a collection named "assemblies"). One of the attributes is "parent_id".
Based on this, I want to construct the graph, that is implicitly described by this attribute.

```<code>"id","name","parent_id"
"30","Top level"
"30.1","30.1 Child 1","30"
"30.2","30.2 Child 2","30"
</code>```

This is the query, that I expected to give me the info for creating the edge collection (named "contains", so it is from parent to child):

```<code>FOR assy IN assemblies
  LET parent = (
    FOR parent IN assemblies
      FILTER parent.id == assy.parent_id
      RETURN parent
  )
  RETURN {_from: parent._key, _to: assy._key}
</code>```

What am I doing wrong? Could you give me the full query for inserting the edges?

答:
The problem is that the result of your subquery in parent is an array and not an document. But there is actually no need of a subquery. You can also performe a join, which should offer better performance and is easier to read.
You also have to use the value of _id insteadt of _key for the fields _from and _to of your edges.

The following query does exactly what you want.

```<code>FOR assy IN assemblies
  FOR parent IN assemblies
    FILTER parent.id == assy.parent_id
    INSERT {_from: parent._id, _to: assy._id} IN contains
    RETURN NEW
</code>```

Node: the RETURN NEW is optional. You can check with it whether the import was successful. With larger amount of data I would drop this.

Body:
I have imported a list of documents (in a collection named "assemblies"). One of the attributes is "parent_id".
Based on this, I want to construct the graph, that is implicitly described by this attribute.

"id","name","parent_id"
"30","Top level"
"30.1","30.1 Child 1","30"
"30.2","30.2 Child 2","30"

This is the query, that I expected to give me the info for creating the edge collection (named "contains", so it is from parent to child):

FOR assy IN assemblies
  LET parent = (
    FOR parent IN assemblies
      FILTER parent.id == assy.parent_id
      RETURN parent
  )
  RETURN {_from: parent._key, _to: assy._key}

What am I doing wrong? Could you give me the full query for inserting the edges?

Body:
The problem is that the result of your subquery in parent is an array and not an document. But there is actually no need of a subquery. You can also performe a join, which should offer better performance and is easier to read.
You also have to use the value of _id insteadt of _key for the fields _from and _to of your edges.

The following query does exactly what you want.

FOR assy IN assemblies
  FOR parent IN assemblies
    FILTER parent.id == assy.parent_id
    INSERT {_from: parent._id, _to: assy._id} IN contains
    RETURN NEW

Node: the RETURN NEW is optional. You can check with it whether the import was successful. With larger amount of data I would drop this.


问:
mysql error 1064 when inserting

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(country,ping,order) VALUES (China,1,1)' at line 1

this is my code

```<code>INSERT INTO
  (country, ping, order)
VALUES
  ('China', '1', '1');
</code>```

答:
Your insert statement is missing the table name:</p>

```<code>INSERT INTO tbl_name (col_name,...) VALUES (expr,...)
</code>```

Title: mysql error 1064 when inserting

Body:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(country,ping,order) VALUES (China,1,1)' at line 1

this is my code

INSERT INTO
  (country, ping, order)
VALUES
  ('China', '1', '1');

Body:
Your insert statement is missing the table name:

INSERT INTO tbl_name (col_name,...) VALUES (expr,...)


问:
How to access Google analytics api WITHOUT logging through google login dialog (javascript)?
I can retrieve analytics data using Core Reporting API v4, but for that I am required to login through google sign in dialog.

How can I get the data skipping this step i.e., I don't to want to login through the Google user interface.

答:
Turns out I misread the question - it looks like you are looking for a service account. A service account allows for non-interactive authentication against Google APIs.

You create a service account in the Google API console. There you can download a file with credentials that are used for authentication. This is handled non-interactively without opening a browser.

You need to add the email of the service account to the resource you want to access (e.g. to your Analytics account).

Details are in the link (this is a PHP example, but service accounts work regardless of programming language).

Old answer:

Somebody has to log in to get the data (GA accounts always need authentication), so if you don't want to log in via the browser you need an intermediary application that authenticates against Google and then publicy exposes the data.

There is a project Google Analytics Super Proxy that does this, however it requires a bit of setup.

A simpler way would be to use the Analytics Add-On in a Google Spreadsheet, share that publicly and embed it in your page, or format the output as HTML or JSON via some Apps script and pull it into your page for display.


问:
Calling a function recursively in the context of "export default"?
This may be obvious to others but I don't know the syntax for calling a function recursively in the following code:

```<code>//request.js
    export default {

      send() {
       ... do stuff ...
       this.send(); // Can't call "send" of undefined
      }
    }

//main.js
import request from './request'

export default class Main extends Component {
   init() {
      request.send();
  }
}
</code>```

In the above example, I'm calling the send function from main.js. All this is working fine but I have a condition in the send function that will recall the same function. The problem is that I have no idea how to call the function from within the function. Anybody?

答:
If you want to call the default export recursively in Node.js, using Babel.js to transpile, you can use the exports object:

```<code>// request.js

export default {
  send() {
    console.log('Yo');
    setTimeout(() => {
      exports.default.send();
    }, 1000);
  },
};
</code>```

Importing:

```<code>// main.js

import request from './request';

request.send(); // Writes "Yo" to the console once per second
</code>```

This is because Babel.js simply transforms to the CommonJS syntax. This:

```<code>export default 42;
</code>```

Becomes this:

```<code>Object.defineProperty(exports, "__esModule", {
  value: true
});

exports.default = 42;
</code>```

No idea how this may change in a future implementation of ES6 Modules in Node.js.

Body:
This may be obvious to others but I don't know the syntax for calling a function recursively in the following code:

//request.js
    export default {

      send() {
       ... do stuff ...
       this.send(); // Can't call "send" of undefined
      }
    }

//main.js
import request from './request'

export default class Main extends Component {
   init() {
      request.send();
  }
}

In the above example, I'm calling the send function from main.js. All this is working fine but I have a condition in the send function that will recall the same function. The problem is that I have no idea how to call the function from within the function. Anybody?

Body:
If you want to call the default export recursively in Node.js, using Babel.js to transpile, you can use the exports object:

// request.js

export default {
  send() {
    console.log('Yo');
    setTimeout(() => {
      exports.default.send();
    }, 1000);
  },
};

Importing:

// main.js

import request from './request';

request.send(); // Writes "Yo" to the console once per second

This is because Babel.js simply transforms to the CommonJS syntax. This:

export default 42;

Becomes this:

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports.default = 42;

No idea how this may change in a future implementation of ES6 Modules in Node.js.


问:
How can I make Intent From Activity to Fragment in android?
Like this. It is working good from fragment to activity.</p>
```<code>Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);
</code>```

答:
Try this,</p>

```<code>Fragment fragment = new TestFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
</code>```

Body:
Like this. It is working good from fragment to activity.

Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);

Body:
Try this,

Fragment fragment = new TestFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();


问:
Adjusted Boxplot in Python
For my thesis, I am trying to identify outliers in my data set. The data set is constructed of 160000 times of one variable from a real process environment. In this environment however, there can be measurements that are not actual data from the process itself but simply junk data. I would like to filter them out with I little help of literature instead of only "expert opinion".

Now I've read about the IQR method of seeing whether possible outliers lie when dealing with a symmetric distribution like the normal distribution. However, my data set is right skewed and by distribution fitting, inverse gamma and lognormal where the best fit.

So, during my search for methods for non-symmetric distributions, I found this topic on crossvalidated where user603's answer is interesting in particular: Is there a boxplot variant for Poisson distributed data?

In user603's answer, he states that an adjusted boxplot helps to identify possible outliers in your dataset and that R and Matlab have functions for this

(There is an R implementation of this
  (::()robustbase::adjbox()) as well as
  a matlab one (in a library called libra)

I was wondering if there is such a function in Python. Or is there a way to calculate the medcouple (see paper in user603's answer) with python?

I really would like to see what comes out the adjusted boxplot for my data..

答:
In the module statsmodels.stats.stattools there is a function medcouple(), which is the measure of the skewness used in the Adjusted Boxplot.

enter link description here

With this variable you can calculate the interval beyond which outliers are defined.

Title: Adjusted Boxplot in Python


问:
laravel ORM merge two json arrays
Excuse me, I use laravel ORM have two json arrays , like this:

php

```<code>$personnels = Personnel::all();
$skills = Languagelv::all();
return view('bs_sidebar/recommend',[
            'personnels' => $personnels,
            'skills' => $skills,
]);
</code>```

model

```<code>class Personnel extends Model
{
    protected $table = 'personnels';

    protected $fillable = ['name', 'sex'];
}

class Personnels_skill extends Model
{
    public $timestamps = false;
    protected $table = 'personnels_skill';
    protected $fillable = ['skill_name','personnels_id'];
}
</code>```

json result

```<code>{personnels:[
    {"id" : 1,"name"  : "bruce","sex"   : 1},
    {"id" : 2,"name" : "peter","sex"  : 0}
    ]
};
{skill:[
        {"id" : 1,"skill_name": 'php', "personnels_id" : 1},
        {"id" : 2,"skill_name": 'jsp',"personnels_id" : 1},
        {"id" : 3,"skill_name": 'asp',"personnels_id" : 2}
       ]
};
</code>```

I want to merge two json arrays

(personnels id = skill personnels_id )

skill arrays is into personnels arrays

like this result:

```<code>{merge:[
        {"id":1,"name":"bruce","sex:1,"skill":[{"id": 1,"skill_name": 'php', "personnels_id" : 1},{"id": 2,"skill_name": 'jsp',"personnels_id" : 1}]},

        {"id":2,"name":"peter","sex":0,"skill":[{"id": 3,"skill_name": 'asp',"personnels_id" : 2}
        ]
};
</code>```

How can I do , please help me, thank you.

答:
let's try this
it will work.   </p>

```<code>      foreach ($personnels as $key => $value) {
        $skill_list = DB::table('skill')->where('personnels_id','=',$value->id)->get();
        $personnels[$key]->skill = $skill_list;
                    }

return view('bs_sidebar/recommend',['personnels' => $personnels]);
</code>```

Title: laravel ORM merge two json arrays

Body:
Excuse me, I use laravel ORM have two json arrays , like this:

php

$personnels = Personnel::all();
$skills = Languagelv::all();
return view('bs_sidebar/recommend',[
            'personnels' => $personnels,
            'skills' => $skills,
]);

model

class Personnel extends Model
{
    protected $table = 'personnels';

    protected $fillable = ['name', 'sex'];
}

class Personnels_skill extends Model
{
    public $timestamps = false;
    protected $table = 'personnels_skill';
    protected $fillable = ['skill_name','personnels_id'];
}

json result

{personnels:[
    {"id" : 1,"name"  : "bruce","sex"   : 1},
    {"id" : 2,"name" : "peter","sex"  : 0}
    ]
};
{skill:[
        {"id" : 1,"skill_name": 'php', "personnels_id" : 1},
        {"id" : 2,"skill_name": 'jsp',"personnels_id" : 1},
        {"id" : 3,"skill_name": 'asp',"personnels_id" : 2}
       ]
};

I want to merge two json arrays

(personnels id = skill personnels_id )

skill arrays is into personnels arrays

like this result:

{merge:[
        {"id":1,"name":"bruce","sex:1,"skill":[{"id": 1,"skill_name": 'php', "personnels_id" : 1},{"id": 2,"skill_name": 'jsp',"personnels_id" : 1}]},

        {"id":2,"name":"peter","sex":0,"skill":[{"id": 3,"skill_name": 'asp',"personnels_id" : 2}
        ]
};

How can I do , please help me, thank you.

Body:
let's try this
it will work.

      foreach ($personnels as $key => $value) {
        $skill_list = DB::table('skill')->where('personnels_id','=',$value->id)->get();
        $personnels[$key]->skill = $skill_list;
                    }

return view('bs_sidebar/recommend',['personnels' => $personnels]);


问:
Basic4android - Jsonparser
I have json format like below :

```<code>{"response":[{Pasien={id=24, name=Erren}, Detailtransaksi=[], Upk={name=Poli Umum}, Pendaftaran={antrian=1, id=1, user_id=9, modified=2015-03-01 14:08:46, keterangan=demam tinggi, pasien_id=24}},
 {Pasien={id=21, name=Lulu Batam}, Detailtransaksi=[], Upk={name=Poli Umum}, Pendaftaran={antrian=2, id=2, user_id=9, modified=2015-03-01 14:09:05, keterangan=kantong kering akut, pasien_id=21}}
]}
</code>```

but I don't know,how to take the array data into the list.

答:
You can use JSONParser class.
First you should add the JSON library to your project, then declare a JSONParser variable and initialize it with your JSON text.

Now you can use the following two methods to get the result:
parser.NextArray As List (when there are more than one element in JSON text)
parser.NextObject As Map (when there is only one object in the json text)

```<code>private Sub ParseResponse (text As String) As List
parser.Initialize(text)
Private returnList As List
Private jsonMap As Map
Private jsonList As List

Try
    jsonList = parser.NextArray
    returnList = jsonList
    Return returnList
Catch
    Try
        jsonMap = parser.NextObject
        returnList.Add(jsonMap)
        Return returnList
    Catch
        Return Null     ' not a json text
    End Try
End Try
</code>```

End Sub

Title: Basic4android - Jsonparser

Body:
I have json format like below :

{"response":[{Pasien={id=24, name=Erren}, Detailtransaksi=[], Upk={name=Poli Umum}, Pendaftaran={antrian=1, id=1, user_id=9, modified=2015-03-01 14:08:46, keterangan=demam tinggi, pasien_id=24}},
 {Pasien={id=21, name=Lulu Batam}, Detailtransaksi=[], Upk={name=Poli Umum}, Pendaftaran={antrian=2, id=2, user_id=9, modified=2015-03-01 14:09:05, keterangan=kantong kering akut, pasien_id=21}}
]}

but I don't know,how to take the array data into the list.

Body:
You can use JSONParser class.
First you should add the JSON library to your project, then declare a JSONParser variable and initialize it with your JSON text.

Now you can use the following two methods to get the result:
parser.NextArray As List (when there are more than one element in JSON text)
parser.NextObject As Map (when there is only one object in the json text)

private Sub ParseResponse (text As String) As List
parser.Initialize(text)
Private returnList As List
Private jsonMap As Map
Private jsonList As List

Try
    jsonList = parser.NextArray
    returnList = jsonList
    Return returnList
Catch
    Try
        jsonMap = parser.NextObject
        returnList.Add(jsonMap)
        Return returnList
    Catch
        Return Null     ' not a json text
    End Try
End Try

End Sub


答: you are missing table name. also make sure that those quotes are necessary</p>

Title: mysql error 1064 when inserting


问:
why can't I get the right sum of 1D array with numba (cuda python)?
I try to use cuda python with numba.
The code is to calculate the sum of a 1D array as follows, but I don't know how to get one value result rather than three values.

python3.5 with numba
+ CUDA8.0

```<code>import os,sys,time
import pandas as pd
import numpy as np
from numba import cuda, float32

os.environ['NUMBAPRO_NVVM']=r'D:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\bin\nvvm64_31_0.dll'
os.environ['NUMBAPRO_LIBDEVICE']=r'D:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\libdevice'

bpg = (1,1)
tpb = (1,3)

@cuda.jit
def calcu_sum(D,T):
    ty = cuda.threadIdx.y
    bh = cuda.blockDim.y
    index_i = ty
    L = len(D)
    su = 0
    while index_i<L:
        su +=D[index_i]
        index_i +=bh
    print('su:',su)
    T[0,0]=su
    print('T:',T[0,0])

D = np.array([ 0.42487645,0.41607881,0.42027071,0.43751907,0.43512794,0.43656972,
               0.43940639,0.43864551,0.43447691,0.43120232], dtype=np.float32)
T = np.empty([1,1])
print('D: ',D)

stream = cuda.stream()
with stream.auto_synchronize():
    dD = cuda.to_device(D, stream)
    dT= cuda.to_device(TE, stream)
    calcu_sum[bpg, tpb, stream](dD,dT)
</code>```

The output is:

```<code>D:  [ 0.42487645  0.41607881  0.42027071  0.43751907  0.43512794  0.43656972
  0.43940639  0.43864551  0.43447691  0.43120232]
su:  1.733004
su:  1.289852
su:  1.291317
T: 1.733004
T: 1.289852
T: 1.291317
</code>```

Why can't I get the output "4.31417383" rather than "1.733004 1.289852 1.291317" ? 1.733004+1.289852+1.291317=4.314173.

I'm new to numba, read the numba documentation, but don't know how to do it. Can someone give advice ?

答:
The reason you don't get the sum you expect is because you haven't written code to produce that sum.

The basic CUDA programming model (whether you use CUDA C, Fortran or Python as your language) is that you write kernel code which is executed by each thread. You have written code for each thread to read and sum part of the input array. You have not written any code for those threads to share and sum their individual partial sums into a final sum.

There is an extremely well described algorithm for doing this -- it is called a parallel reduction. You can find an introduction to the algorithm in a PDF which ships in the examples of every version of the CUDA toolkit, or download a presentation about it here. You can also read a more modern version of the algorithm which uses newer features of CUDA (warp shuffle instructions and atomic transactions) here.

After you have studied the reduction algorithm, you will need to adapt the standard CUDA C kernel code into the Numba Python kernel dialect. At the bare minimum, something like this:

```<code>tpb = (1,3)

@cuda.jit
def calcu_sum(D,T):

    ty = cuda.threadIdx.y
    bh = cuda.blockDim.y
    index_i = ty
    sbuf = cuda.shared.array(tpb, float32)

    L = len(D)
    su = 0
    while index_i < L:
        su += D[index_i]
        index_i +=bh

    print('su:',su)

    sbuf[0,ty] = su
    cuda.syncthreads()

    if ty == 0:
        T[0,0] = 0
        for i in range(0, bh):
            T[0,0] += sbuf[0,i]
        print('T:',T[0,0])
</code>```

will probably do what you want, although it is still a long way from an optimal parallel shared memory reduction, as you will see when you read the material I provided links to.

Body:
I try to use cuda python with numba.
The code is to calculate the sum of a 1D array as follows, but I don't know how to get one value result rather than three values.

python3.5 with numba
+ CUDA8.0

import os,sys,time
import pandas as pd
import numpy as np
from numba import cuda, float32

os.environ['NUMBAPRO_NVVM']=r'D:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\bin\nvvm64_31_0.dll'
os.environ['NUMBAPRO_LIBDEVICE']=r'D:\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\libdevice'

bpg = (1,1)
tpb = (1,3)

@cuda.jit
def calcu_sum(D,T):
    ty = cuda.threadIdx.y
    bh = cuda.blockDim.y
    index_i = ty
    L = len(D)
    su = 0
    while index_i<L:
        su +=D[index_i]
        index_i +=bh
    print('su:',su)
    T[0,0]=su
    print('T:',T[0,0])

D = np.array([ 0.42487645,0.41607881,0.42027071,0.43751907,0.43512794,0.43656972,
               0.43940639,0.43864551,0.43447691,0.43120232], dtype=np.float32)
T = np.empty([1,1])
print('D: ',D)

stream = cuda.stream()
with stream.auto_synchronize():
    dD = cuda.to_device(D, stream)
    dT= cuda.to_device(TE, stream)
    calcu_sum[bpg, tpb, stream](dD,dT)

The output is:

D:  [ 0.42487645  0.41607881  0.42027071  0.43751907  0.43512794  0.43656972
  0.43940639  0.43864551  0.43447691  0.43120232]
su:  1.733004
su:  1.289852
su:  1.291317
T: 1.733004
T: 1.289852
T: 1.291317

Why can't I get the output "4.31417383" rather than "1.733004 1.289852 1.291317" ? 1.733004+1.289852+1.291317=4.314173.

I'm new to numba, read the numba documentation, but don't know how to do it. Can someone give advice ?

Body:
The reason you don't get the sum you expect is because you haven't written code to produce that sum.

The basic CUDA programming model (whether you use CUDA C, Fortran or Python as your language) is that you write kernel code which is executed by each thread. You have written code for each thread to read and sum part of the input array. You have not written any code for those threads to share and sum their individual partial sums into a final sum.

There is an extremely well described algorithm for doing this -- it is called a parallel reduction. You can find an introduction to the algorithm in a PDF which ships in the examples of every version of the CUDA toolkit, or download a presentation about it here. You can also read a more modern version of the algorithm which uses newer features of CUDA (warp shuffle instructions and atomic transactions) here.

After you have studied the reduction algorithm, you will need to adapt the standard CUDA C kernel code into the Numba Python kernel dialect. At the bare minimum, something like this:

tpb = (1,3)

@cuda.jit
def calcu_sum(D,T):

    ty = cuda.threadIdx.y
    bh = cuda.blockDim.y
    index_i = ty
    sbuf = cuda.shared.array(tpb, float32)

    L = len(D)
    su = 0
    while index_i < L:
        su += D[index_i]
        index_i +=bh

    print('su:',su)

    sbuf[0,ty] = su
    cuda.syncthreads()

    if ty == 0:
        T[0,0] = 0
        for i in range(0, bh):
            T[0,0] += sbuf[0,i]
        print('T:',T[0,0])

will probably do what you want, although it is still a long way from an optimal parallel shared memory reduction, as you will see when you read the material I provided links to.


问:
Use single post action method for multiple views
I have an sms sms application, which has different templates that users can use to send their SMSs, I used different view to represent different templates, however I want to use one action method to send an SMS, i might be different templates but at the end of the day user will send an sms which has two parameters, message itself and cell number to which this sms is to be send to,

Here is my 3 templates for now

```<code>   [HttpGet]
    public ActionResult BookingServiceReminder()
    {
        return View();
    }

    [HttpGet]
    public ActionResult ServiceReminder()
    {
        return View();
    }

    [HttpGet]
    public ActionResult DetailedReminder()
    {
        return View();
    }

    [HttpPost]
    public ActionResult SendSMS(string message, string cellNumber)
    {
        if (_dbManager.SendSMS(cellNumber, message, User.Identity.Name))
        {
            TempData["Success"] = "Message was successfully sent";
        }
        else
        {
            TempData["Error"] = "An error occured while sending the message";
        }
        return RedirectToAction("BookingServiceReminder");
    }
</code>```

My question is, is there a way of using one method for all this views, I dont want to have multiple post methods which will almost have same code except the redirectToAction on which I want to return then current view(current template).

答:
Yes, you can.

You would need to keep track someway that at which action user should be redirected after sending the sms.

One way for it is you can pass the flag back to view and post it as hidden field to determine that which action should be redirected to :

```<code>[HttpGet]
public ActionResult BookingServiceReminder()
{
    ViewBag.RedirectTo = "BookingServiceReminder";
    return View();
}

[HttpGet]
public ActionResult ServiceReminder()
{
    ViewBag.RedirectTo = "ServiceReminder";
    return View();
}

[HttpGet]
public ActionResult DetailedReminder()
{
    ViewBag.RedirectTo = "DetailedReminder";
    return View();
}
</code>```

and in View you can have a hidden field which would post to action :

```<code><input type="hidden" value="@ViewBag.RedirectTo" name="RedirectTo">
</code>```

and in action add a new paramter:

```<code>[HttpPost]
public ActionResult SendSMS(string message, string cellNumber,string RedirectTo)
{
    if (_dbManager.SendSMS(cellNumber, message, User.Identity.Name))
    {
        TempData["Success"] = "Message was successfully sent";
    }
    else
    {
        TempData["Error"] = "An error occured while sending the message";
    }
    return RedirectToAction(RedirectTo);
}
</code>```

Body:
I have an sms sms application, which has different templates that users can use to send their SMSs, I used different view to represent different templates, however I want to use one action method to send an SMS, i might be different templates but at the end of the day user will send an sms which has two parameters, message itself and cell number to which this sms is to be send to,

Here is my 3 templates for now

   [HttpGet]
    public ActionResult BookingServiceReminder()
    {
        return View();
    }

    [HttpGet]
    public ActionResult ServiceReminder()
    {
        return View();
    }

    [HttpGet]
    public ActionResult DetailedReminder()
    {
        return View();
    }

    [HttpPost]
    public ActionResult SendSMS(string message, string cellNumber)
    {
        if (_dbManager.SendSMS(cellNumber, message, User.Identity.Name))
        {
            TempData["Success"] = "Message was successfully sent";
        }
        else
        {
            TempData["Error"] = "An error occured while sending the message";
        }
        return RedirectToAction("BookingServiceReminder");
    }

My question is, is there a way of using one method for all this views, I dont want to have multiple post methods which will almost have same code except the redirectToAction on which I want to return then current view(current template).

Body:
Yes, you can.

You would need to keep track someway that at which action user should be redirected after sending the sms.

One way for it is you can pass the flag back to view and post it as hidden field to determine that which action should be redirected to :

[HttpGet]
public ActionResult BookingServiceReminder()
{
    ViewBag.RedirectTo = "BookingServiceReminder";
    return View();
}

[HttpGet]
public ActionResult ServiceReminder()
{
    ViewBag.RedirectTo = "ServiceReminder";
    return View();
}

[HttpGet]
public ActionResult DetailedReminder()
{
    ViewBag.RedirectTo = "DetailedReminder";
    return View();
}

and in View you can have a hidden field which would post to action :

<input type="hidden" value="@ViewBag.RedirectTo" name="RedirectTo">

and in action add a new paramter:

[HttpPost]
public ActionResult SendSMS(string message, string cellNumber,string RedirectTo)
{
    if (_dbManager.SendSMS(cellNumber, message, User.Identity.Name))
    {
        TempData["Success"] = "Message was successfully sent";
    }
    else
    {
        TempData["Error"] = "An error occured while sending the message";
    }
    return RedirectToAction(RedirectTo);
}


问:
PHP uploading large files, takes long and error
I'm uploading a large file via ajax. The upload speed is fine but when the progress bar get's to 100%, there is a long wait and then i get this error

Failed to load resource: the server responded with a status of 504 (Gateway Time-out) - upload.php.

The file does appear in the destination folder but there isn't a server response.

This doesn't happen to smaller files.  It seems to take long to move_uploaded_file from the Temp folder to the destination folder.

```<code>  var xhr, hUploadSpeed;
        function sendFile()
        {
            document.getElementById("serverresponse").innerHTML = "";//clear previous server response

            var url = "http://www.example.com/wp-content/themes/theme1/file-upload/upload.php";
            var formData = new FormData(document.getElementById("form1"));
            xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', uploadProgress, false);//EventListener for upload progress
            xhr.addEventListener('abort', uploadAbort, false);//EventListener for abort
            xhr.addEventListener('error', uploadError, false);//EventListener for error
            xhr.addEventListener('load', uploadThrough, false);//EventListener for completed upload

            xhr.open("POST", url, true);
            //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //no longer necessary here
            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4 && xhr.status == 200)
                {
                    document.getElementById("serverresponse").innerHTML = xhr.responseText;
                }
            }

            xhr.send(formData); //Send to server
            hUploadSpeed = setInterval(UploadSpeed, 1000); //per seconds
        }
</code>```

Upload.php

```<code>//You can access the uploaded files through $_FILES
if(isset($_FILES["file1"]))
    $target_file = $_SERVER['DOCUMENT_ROOT']."/videos/".$_FILES["file1"]['name'];
    move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file);

echo "File uploaded successfully.";
</code>```

This works perfectly with smaller files 50mb but when i get to files around 300mb.  It takes so long?

I have a dedicated server with this php.ini

```<code>upload_max_filesize = 1200M
post_max_size = 1200M
max_input_vars = 1000
memory_limit = -1
max_file_uploads = 20
max_execution_time = 7200
max_input_time = 7200
max_input_vars = 1000
</code>```

Why does it take so long?  How do i solve?

答:
I think that your problem can be this php bug :
https://bugs.php.net/bug.php?id=73807
You php config is ok.

Fixed in 7 and 7.1 branch. Not In php 5.6 now. Maybe soon.
If you can, upgrade your app to 7.1 (performances are also more than 2 times faster), if you can't just wait php > 5.6.30

Body:
I'm uploading a large file via ajax. The upload speed is fine but when the progress bar get's to 100%, there is a long wait and then i get this error

Failed to load resource: the server responded with a status of 504 (Gateway Time-out) - upload.php.

The file does appear in the destination folder but there isn't a server response.

This doesn't happen to smaller files.  It seems to take long to move_uploaded_file from the Temp folder to the destination folder.

  var xhr, hUploadSpeed;
        function sendFile()
        {
            document.getElementById("serverresponse").innerHTML = "";//clear previous server response

            var url = "http://www.example.com/wp-content/themes/theme1/file-upload/upload.php";
            var formData = new FormData(document.getElementById("form1"));
            xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', uploadProgress, false);//EventListener for upload progress
            xhr.addEventListener('abort', uploadAbort, false);//EventListener for abort
            xhr.addEventListener('error', uploadError, false);//EventListener for error
            xhr.addEventListener('load', uploadThrough, false);//EventListener for completed upload

            xhr.open("POST", url, true);
            //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //no longer necessary here
            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4 && xhr.status == 200)
                {
                    document.getElementById("serverresponse").innerHTML = xhr.responseText;
                }
            }

            xhr.send(formData); //Send to server
            hUploadSpeed = setInterval(UploadSpeed, 1000); //per seconds
        }

Upload.php

//You can access the uploaded files through $_FILES
if(isset($_FILES["file1"]))
    $target_file = $_SERVER['DOCUMENT_ROOT']."/videos/".$_FILES["file1"]['name'];
    move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file);

echo "File uploaded successfully.";

This works perfectly with smaller files 50mb but when i get to files around 300mb.  It takes so long?

I have a dedicated server with this php.ini

upload_max_filesize = 1200M
post_max_size = 1200M
max_input_vars = 1000
memory_limit = -1
max_file_uploads = 20
max_execution_time = 7200
max_input_time = 7200
max_input_vars = 1000

Why does it take so long?  How do i solve?


答:
You're missing the Table Name.  Try:</p>

```<code>INSERT INTO MYTABLENAME (country,ping,order) VALUES ('China','1','1');
</code>```

Title: mysql error 1064 when inserting

Body:
You're missing the Table Name.  Try:

INSERT INTO MYTABLENAME (country,ping,order) VALUES ('China','1','1');


问:
Calculating how many days between dates, diffrent months
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.

I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:

```<code>var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

答:
You can calculate the difference(days) between two dates by using the code below.</p>

```<code>var dateOne = new Date(firstDate);
var dateTwo = new Date(secondDate);
var dateDifference = Math.floor((dateTwo - dateOne) / 86400000);
console.log(dateDifference);
</code>```

Body:
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.

I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:

var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

Body:
You can calculate the difference(days) between two dates by using the code below.

var dateOne = new Date(firstDate);
var dateTwo = new Date(secondDate);
var dateDifference = Math.floor((dateTwo - dateOne) / 86400000);
console.log(dateDifference);


答:
To reduce height you have to specify it in the CSS of your div, or directly like this :

you can do the same for the width :

Title: HighCharts: render the xAise line as the yAise line

Body:
I am trying to render the xAise line as the yAise line but I do not know which configuration attribute would display it? How can I reduce the height of the HighCharts too? I tried the 'maxPadding: 0' in the yAxis but without seccuss.

https://jsfiddle.net/ow6hqmu3/

Highcharts.chart('container',
{
    chart: {
        type: 'columnrange',
        inverted: true
    },
    credits: {
        enabled: false
    },
    title: {
        text: null
    },
    subTitle: {
        text: null
    },
    legend: {
        enabled: false,
    },
    plotOptions: {
        series: {
            pointWidth: 30
        }
    },
  xAxis: {
    min: 0,
    max: 3,
    categories: [' ',' ',' ','Woring time'],
    title: {
      text: null
    },
          gridLineWidth: 0
    },
    yAxis: {
        type: 'datetime',
        title: {
            text: null
        },
        labels: {
            rotation: -45
        },
        tickInterval: 1800000,
        gridLineWidth: 0
    },
    series: [{
      data: [
            [3, 1483337940000, 1483338000000],
            [3, 1483338300000, 1483339740000],
            [3, 1483340580000, 1483340640000],
            [3, 1483340820000, 1483341000000],
            [3, 1483342860000, 1483342920000],
            [3, 1483346460000, 1483346520000],
            [3, 1483347180000, 1483348440000],
            [3, 1483348620000, 1483348740000],
            [3, 1483350180000, 1483350240000],
            [3, 1483350420000, 1483351380000],
            [3, 1483353300000, 1483353420000],
            [3, 1483355280000, 1483355340000],
            [3, 1483358580000, 1483359780000],
        ]
    }]
 }
);

Body:
To reduce height you have to specify it in the CSS of your div, or directly like this :

<div id="container" style="height: 100px;"></div>

you can do the same for the width :

<div id="container" style="height: 100px; width=300px"></div>