问:
cudamemcpy array of pointers where each pointer points to an array
I am attempting to create an array of pointers on the host. Each pointer in the array points to an array of size 4. When I try to copy a pointer to the device, the copy fails and the device cannot access the contents of the array to which the pointer points to. How would I copy a pointer from an array of pointers that points to an array from host to device?</p>

```<code>__global__ void kernel(int* D)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    while (tid < 4)
    {
        printf("Device = %d\n", D[tid]);
        tid += blockDim.x * gridDim.x;
    }
}

int main(void)
{
    cudaProfilerStart();

    int* H[2];
    int* D[2];
    int test1[4] = { 1, 2, 3, 4 };
    int test2[4] = { 10, 20, 30, 40 };

    H[0] = test1;
    H[1] = test2;

    HANDLE_ERROR(cudaMalloc((void**)&D[0], 4 * sizeof(int)));
    HANDLE_ERROR(cudaMemcpy(D[0], H[0], 4 * sizeof(int), cudaMemcpyHostToDevice));
    kernel <<<1, 4 >>>(D[0]);

    cudaProfilerStop();

    return 0;
}
</code>```

答:
As talonmies pointed out there is nothing wrong with the Code. However, you will not see the prints in your kernel, the reason being that the kernel call is asynchronous and your process ends before the kernel prints can be executed. A synchronization call will solve this problem here. However, in real code this might not be needed.</p>

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

__global__ void kernel(int* D)
{
        int tid = threadIdx.x + blockIdx.x * blockDim.x;
        while (tid < 4)
        {
                printf("Device = %d\n", D[tid]);
                tid += blockDim.x * gridDim.x;
        }
}

int main(void)
{
        // cudaProfilerStart();

        int* H[2];
        int* D[2];
        int test1[4] = { 1, 2, 3, 4 };
        int test2[4] = { 10, 20, 30, 40 };

        H[0] = test1;
        H[1] = test2;

        cudaMalloc((void**)&D[0], 4 * sizeof(int));
        cudaMemcpy(D[0], H[0], 4 * sizeof(int), cudaMemcpyHostToDevice);
        kernel <<<1, 1 >>>(D[0]);

        cudaError_t cudaerr1 = cudaDeviceSynchronize();
        if (cudaerr1 != cudaSuccess)
                printf("kernel launch failed with error \"%s\".\n",
                        cudaGetErrorString(cudaerr1));

         //cudaProfilerStop();

        return 0;
}
</code>```

Body:
I am attempting to create an array of pointers on the host. Each pointer in the array points to an array of size 4. When I try to copy a pointer to the device, the copy fails and the device cannot access the contents of the array to which the pointer points to. How would I copy a pointer from an array of pointers that points to an array from host to device?

__global__ void kernel(int* D)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    while (tid < 4)
    {
        printf("Device = %d\n", D[tid]);
        tid += blockDim.x * gridDim.x;
    }
}

int main(void)
{
    cudaProfilerStart();

    int* H[2];
    int* D[2];
    int test1[4] = { 1, 2, 3, 4 };
    int test2[4] = { 10, 20, 30, 40 };

    H[0] = test1;
    H[1] = test2;

    HANDLE_ERROR(cudaMalloc((void**)&D[0], 4 * sizeof(int)));
    HANDLE_ERROR(cudaMemcpy(D[0], H[0], 4 * sizeof(int), cudaMemcpyHostToDevice));
    kernel <<<1, 4 >>>(D[0]);

    cudaProfilerStop();

    return 0;
}

Body:
As talonmies pointed out there is nothing wrong with the Code. However, you will not see the prints in your kernel, the reason being that the kernel call is asynchronous and your process ends before the kernel prints can be executed. A synchronization call will solve this problem here. However, in real code this might not be needed.

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

__global__ void kernel(int* D)
{
        int tid = threadIdx.x + blockIdx.x * blockDim.x;
        while (tid < 4)
        {
                printf("Device = %d\n", D[tid]);
                tid += blockDim.x * gridDim.x;
        }
}

int main(void)
{
        // cudaProfilerStart();

        int* H[2];
        int* D[2];
        int test1[4] = { 1, 2, 3, 4 };
        int test2[4] = { 10, 20, 30, 40 };

        H[0] = test1;
        H[1] = test2;

        cudaMalloc((void**)&D[0], 4 * sizeof(int));
        cudaMemcpy(D[0], H[0], 4 * sizeof(int), cudaMemcpyHostToDevice);
        kernel <<<1, 1 >>>(D[0]);

        cudaError_t cudaerr1 = cudaDeviceSynchronize();
        if (cudaerr1 != cudaSuccess)
                printf("kernel launch failed with error \"%s\".\n",
                        cudaGetErrorString(cudaerr1));

         //cudaProfilerStop();

        return 0;
}


来源: stackexchange

问:
Input string was not in a correct format (double)
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

```<code>double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}
</code>```

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.

答:
Try this

Double.TryParse(values_in_string[x], NumberStyles.Any, CultureInfo.InvariantCulture, out val);

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.


问:
jsf customize all error messages
My task is to translate all the messages of an application into another language, different than English. The tricky part is with the messages generated by the JSF framework itself. I came across various articles showing how to customize some particular conversion or validation error message, but i am interested in customizing every possible error message that the application might generate (including, for example, authentication and navigation error messages).

Is there a file that contains all the possible error messages?

So far, i came across a file named Messages.properties, located in the jsf-api jar , which contains Validation, Converter and Component error messages. But that is not enough, there is plenty other errors apart from these.

This jar is actually named jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar and is located under jboss-eap\modules\system\layers\base\javax\faces\api\main folder.

Inside this jar, the Messages.properties file is located under the javax\faces package.

I currently use Red Hat JBoss Enterprise Application Platform - Version 6.4.0.GA, JSF Implementation-Version: 2.1.28.Final-redhat-1

答:
The problem can be split into two parts:

How do i override a framework error message?

What is the list of all possible error messages that can be generated by the JSF framework?

Part 1: OVERRIDING FRAMEWORK'S ERROR MESSAGES

In my project, under WebContent\WEB-INF, there is faces-config.xml, which contains <message-bundle>resources</message-bundle>. 'resources' points to src\resources.properties. In this .properties file, i just have to add the corresponding entries, like

```<code>javax.faces.converter.DateTimeConverter.DATE={2}: ''{0}'' non poteva essere inteso come una data.
</code>```

Should such error be generated by the application, the translated message will be displayed.
However, as i understand from Cannot override validation error message, the use of a resources.properties file under src is maven specific. Different packaging technologies may require different solutions.

Part 2: LIST OF ALL ERROR MESSAGES

Taking a look at the files contained in javax.faces.jar http://www.java2s.com/Code/Jar/j/Downloadjavaxfacesjar.htm , i see the following packages:

javax.faces.application

javax.faces.bean

javax.faces.component

javax.faces.context

javax.faces.convert

javax.faces.el

javax.faces.event

javax.faces.lifecycle

javax.faces.model

javax.faces.render

javax.faces.validator

javax.faces.view

javax.faces.webapp

For every class in each of these packages, i have to add entries in the resources.properties for every error that this class might raise.
But what are the errors that a class might raise? And what should the entry in the resource.properties look like?

I let myself guided by the entries that I've found in the Messages.properties file inside the jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar (which I've mentioned in the question). It has the following entries, among many others:

```<code># ==============================================================================
# Component Errors
# ==============================================================================
javax.faces.component.UIInput.CONVERSION={0}: Conversion error occurred.
javax.faces.component.UIInput.REQUIRED={0}: Validation Error: Value is required.
javax.faces.component.UIInput.UPDATE={0}: An error occurred when processing your submitted information.
</code>```

In my IDE (eclipse), i click on an import statement  import javax.faces.component.UIInput; to navigate to UIInput.class . In the Class File Editor , i have the following lines :

```<code>  // Field descriptor #193 Ljava/lang/String;
  public static final java.lang.String CONVERSION_MESSAGE_ID = "javax.faces.component.UIInput.CONVERSION";

  // Field descriptor #193 Ljava/lang/String;
  public static final java.lang.String REQUIRED_MESSAGE_ID = "javax.faces.component.UIInput.REQUIRED";

  // Field descriptor #193 Ljava/lang/String;
  public static final java.lang.String UPDATE_MESSAGE_ID = "javax.faces.component.UIInput.UPDATE";
</code>```

I remark that the value of the String field is exactly the key that must be added in the resources.properties, like, for example, javax.faces.component.UIInput.CONVERSION.

For a new class, like, for example, javax.faces.validator.RegexValidator class, I will do the following: open it  in class file editor, pick those fields whose name ends in _ID, like :

```<code>  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String VALIDATOR_ID = "javax.faces.RegularExpression";

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String PATTERN_NOT_SET_MESSAGE_ID = "javax.faces.validator.RegexValidator.PATTERN_NOT_SET";

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String NOT_MATCHED_MESSAGE_ID = "javax.faces.validator.RegexValidator.NOT_MATCHED";

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String MATCH_EXCEPTION_MESSAGE_ID = "javax.faces.validator.RegexValidator.MATCH_EXCEPTION";
</code>```

and add the following entries to the resources.properties file:

```<code>javax.faces.RegularExpression=custom message
javax.faces.validator.RegexValidator.PATTERN_NOT_SET=custom message
javax.faces.validator.RegexValidator.NOT_MATCHED=custom message
javax.faces.validator.RegexValidator.MATCH_EXCEPTION=custom message
</code>```

Unfortunately, given the huge number of classes for which error messages must be provided, i don't find this as a feasible solution.

UPDATE

I just realized why only Conversion and Validation error messages should be provided: because they are related to user input, which the programmer cannot control. All the other errors like Navigation related issues must be properly handled by the programmer. Such errors should not appear in the first place, so it does not make sense to translate those messages anyway.

Title: jsf customize all error messages

Body:
The problem can be split into two parts:

How do i override a framework error message?

What is the list of all possible error messages that can be generated by the JSF framework?

Part 1: OVERRIDING FRAMEWORK'S ERROR MESSAGES

In my project, under WebContent\WEB-INF, there is faces-config.xml, which contains <message-bundle>resources</message-bundle>. 'resources' points to src\resources.properties. In this .properties file, i just have to add the corresponding entries, like

javax.faces.converter.DateTimeConverter.DATE={2}: ''{0}'' non poteva essere inteso come una data.

Should such error be generated by the application, the translated message will be displayed.
However, as i understand from Cannot override validation error message, the use of a resources.properties file under src is maven specific. Different packaging technologies may require different solutions.

Part 2: LIST OF ALL ERROR MESSAGES

Taking a look at the files contained in javax.faces.jar http://www.java2s.com/Code/Jar/j/Downloadjavaxfacesjar.htm , i see the following packages:

javax.faces.application

javax.faces.bean

javax.faces.component

javax.faces.context

javax.faces.convert

javax.faces.el

javax.faces.event

javax.faces.lifecycle

javax.faces.model

javax.faces.render

javax.faces.validator

javax.faces.view

javax.faces.webapp

For every class in each of these packages, i have to add entries in the resources.properties for every error that this class might raise.
But what are the errors that a class might raise? And what should the entry in the resource.properties look like?

I let myself guided by the entries that I've found in the Messages.properties file inside the jboss-jsf-api_2.1_spec-2.1.28.Final-redhat-1.jar (which I've mentioned in the question). It has the following entries, among many others:

# ==============================================================================
# Component Errors
# ==============================================================================
javax.faces.component.UIInput.CONVERSION={0}: Conversion error occurred.
javax.faces.component.UIInput.REQUIRED={0}: Validation Error: Value is required.
javax.faces.component.UIInput.UPDATE={0}: An error occurred when processing your submitted information.

In my IDE (eclipse), i click on an import statement  import javax.faces.component.UIInput; to navigate to UIInput.class . In the Class File Editor , i have the following lines :

  // Field descriptor #193 Ljava/lang/String;
  public static final java.lang.String CONVERSION_MESSAGE_ID = "javax.faces.component.UIInput.CONVERSION";

  // Field descriptor #193 Ljava/lang/String;
  public static final java.lang.String REQUIRED_MESSAGE_ID = "javax.faces.component.UIInput.REQUIRED";

  // Field descriptor #193 Ljava/lang/String;
  public static final java.lang.String UPDATE_MESSAGE_ID = "javax.faces.component.UIInput.UPDATE";

I remark that the value of the String field is exactly the key that must be added in the resources.properties, like, for example, javax.faces.component.UIInput.CONVERSION.

For a new class, like, for example, javax.faces.validator.RegexValidator class, I will do the following: open it  in class file editor, pick those fields whose name ends in _ID, like :

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String VALIDATOR_ID = "javax.faces.RegularExpression";

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String PATTERN_NOT_SET_MESSAGE_ID = "javax.faces.validator.RegexValidator.PATTERN_NOT_SET";

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String NOT_MATCHED_MESSAGE_ID = "javax.faces.validator.RegexValidator.NOT_MATCHED";

  // Field descriptor #30 Ljava/lang/String;
  public static final java.lang.String MATCH_EXCEPTION_MESSAGE_ID = "javax.faces.validator.RegexValidator.MATCH_EXCEPTION";

and add the following entries to the resources.properties file:

javax.faces.RegularExpression=custom message
javax.faces.validator.RegexValidator.PATTERN_NOT_SET=custom message
javax.faces.validator.RegexValidator.NOT_MATCHED=custom message
javax.faces.validator.RegexValidator.MATCH_EXCEPTION=custom message

Unfortunately, given the huge number of classes for which error messages must be provided, i don't find this as a feasible solution.

UPDATE

I just realized why only Conversion and Validation error messages should be provided: because they are related to user input, which the programmer cannot control. All the other errors like Navigation related issues must be properly handled by the programmer. Such errors should not appear in the first place, so it does not make sense to translate those messages anyway.


问:
Disable Editing in rows if first Cell is empty for a datagrid in WPF
I am binding a DataTable to Datagrid. Number of columns and rows in datatable is determined at runtime. But number of rows displayed in datagrid is fixed to 36.

So if sometimes datatable have <36 rows, empty rows are displayed to maintain height of datagrid. Reason behind doing this is that I am printing the Grid containing datagrid and I dont want to mess up Height and Width of print template.

```<code>    <DataGrid x:Name="TestPointsDataGrid" ItemsSource="{Binding TestPointsTable,Mode=TwoWay}" HorizontalScrollBarVisibility="Disabled"
CanUserResizeColumns="False" CanUserResizeRows="False" MouseRightButtonUp="DataGrid_MouseRightButtonUp"
                                      CanUserAddRows="False" >
</code>```

To disable first and last columns I did below style triggers :

```<code>    <Style TargetType="{x:Type DataGridCell}">
       <Style.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
             <Setter Property="Background" Value="Aqua"></Setter>
          </Trigger>
          <DataTrigger Value="Type" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
              <Setter Property="IsEnabled"  Value="false" />
              <Setter Property="FontWeight" Value="DemiBold"/>
           </DataTrigger>
           <DataTrigger Value="B or A" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
               <Setter Property="IsEnabled"  Value="false" />
               <Setter Property="FontWeight" Value="DemiBold"/>
               <Setter Property="Foreground" Value="Black"/>
            </DataTrigger>
       </Style.Triggers>
   </Style>
</code>```

Example :

As shown in above images, numbers of columns are unknown.
First column and last column is always fixed in my case. i.e. "Type" and "B or A" respectively. I was able to set IsEnabled = false for these columns.

If there is something in first column, let user edit that row except first and last column.
How do I set those empty rows' IsEnabled property to false ? Or just any workaround to prevent user from typing anything in those rows except not displaying those rows.

答:
The easiest thing for you to do is to add a BeginningEdit event handler and cancel the edit if the row that the user is trying to edit is empty...</p>

```<code><DataGrid x:Name="dataGrid" ItemsSource="{Binding PartCollection}" AutoGenerateColumns="True" BeginningEdit="dataGrid_BeginningEdit">

    private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        if((e.Row.Item as Part).Manufacturer == "XYZ")
        {
            e.Cancel = true;
        }
    }
</code>```

Body:
I am binding a DataTable to Datagrid. Number of columns and rows in datatable is determined at runtime. But number of rows displayed in datagrid is fixed to 36.

So if sometimes datatable have <36 rows, empty rows are displayed to maintain height of datagrid. Reason behind doing this is that I am printing the Grid containing datagrid and I dont want to mess up Height and Width of print template.

    <DataGrid x:Name="TestPointsDataGrid" ItemsSource="{Binding TestPointsTable,Mode=TwoWay}" HorizontalScrollBarVisibility="Disabled"
CanUserResizeColumns="False" CanUserResizeRows="False" MouseRightButtonUp="DataGrid_MouseRightButtonUp"
                                      CanUserAddRows="False" >

To disable first and last columns I did below style triggers :

   </Style>

Example :

As shown in above images, numbers of columns are unknown.
First column and last column is always fixed in my case. i.e. "Type" and "B or A" respectively. I was able to set IsEnabled = false for these columns.

If there is something in first column, let user edit that row except first and last column.
How do I set those empty rows' IsEnabled property to false ? Or just any workaround to prevent user from typing anything in those rows except not displaying those rows.

Body:
The easiest thing for you to do is to add a BeginningEdit event handler and cancel the edit if the row that the user is trying to edit is empty...

<DataGrid x:Name="dataGrid" ItemsSource="{Binding PartCollection}" AutoGenerateColumns="True" BeginningEdit="dataGrid_BeginningEdit">

    private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        if((e.Row.Item as Part).Manufacturer == "XYZ")
        {
            e.Cancel = true;
        }
    }


问:
processing this string with php
I have a text string that looks like this

```<code>var1=red&var2=green&var3=blue&var4=magenta
</code>```

How can manipulate this string isolate the value of var2 which in this case is green

答: I'd start with parse_url  What you have looks close enough to an URL param string that you might as well use the built in methods for handling URLs.</p>

ContentLicense: CC BY-SA 2.5

Title: processing this string with php

Body:
I have a text string that looks like this

var1=red&var2=green&var3=blue&var4=magenta

How can manipulate this string isolate the value of var2 which in this case is green


问:
Angular2 callback vs Promise/Observable
Context:

I have AWS cognito working on an Angular 2 app. The AWS demo uses callbacks to handle asynchronous requests.

```<code>public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});
</code>```

}

Is it possible to implement the same functionality with Promise or Observable?

Thanks in advance.

答:
You can also make use of a Subject and create the observable somewhat manually (but at least you might better understand how to do the conversion).

```<code>public getSession(callback: CognitoCallback): Observable<any> {
  let cognitoUser: CognitoUser = this.getCurrentUser();
  let cognitoUtil = this;

  // You can easily get an Observable from an RxJS subject by calling asObservable().
  // more importantly, you can send values/errors to that observable by calling subject.next(valueToSend) or subject.error(errorToSend)
  let subject = new Subject();

  cognitoUser.getSession(function (err, session) {

    if (err) {
      let error = new CognitoError(err.name, err.message);
      //callback.cognitoCallback(error, null);
      // replace with subject error notification
      subject.error(error);
      return;
    }
    if (!session.isValid()) {
      let error = new CognitoError("SessionInvalid", "Session is not valid");
      //callback.cognitoCallback(error, session);
      subject.error(error);
      return;
    }
    //callback.cognitoCallback(null, session);
    // send the session down through the observable
    subject.next(session);
    cognitoUtil.setCurrentUser(cognitoUser);

    // finish off the observable
    subject.complete();
    return;
  });

  return subject.asObservable();
}
</code>```

The example above will return an Observable that you can then use for other purposes.

Title: Angular2 callback vs Promise/Observable

Body:
Context:

I have AWS cognito working on an Angular 2 app. The AWS demo uses callbacks to handle asynchronous requests.

public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});

}

Is it possible to implement the same functionality with Promise or Observable?

Thanks in advance.

Body:
You can also make use of a Subject and create the observable somewhat manually (but at least you might better understand how to do the conversion).

public getSession(callback: CognitoCallback): Observable<any> {
  let cognitoUser: CognitoUser = this.getCurrentUser();
  let cognitoUtil = this;

  // You can easily get an Observable from an RxJS subject by calling asObservable().
  // more importantly, you can send values/errors to that observable by calling subject.next(valueToSend) or subject.error(errorToSend)
  let subject = new Subject();

  cognitoUser.getSession(function (err, session) {

    if (err) {
      let error = new CognitoError(err.name, err.message);
      //callback.cognitoCallback(error, null);
      // replace with subject error notification
      subject.error(error);
      return;
    }
    if (!session.isValid()) {
      let error = new CognitoError("SessionInvalid", "Session is not valid");
      //callback.cognitoCallback(error, session);
      subject.error(error);
      return;
    }
    //callback.cognitoCallback(null, session);
    // send the session down through the observable
    subject.next(session);
    cognitoUtil.setCurrentUser(cognitoUser);

    // finish off the observable
    subject.complete();
    return;
  });

  return subject.asObservable();
}

The example above will return an Observable that you can then use for other purposes.


问:
How can I share a cache between Gunicorn workers?
I am working on a small service using Gunicorn and Flask (Python 3.6).The pseudocode below shows roughly the behavior I want. There are a lot of serialized foo objects, and I want to hold as many of these in memory as possible and delete them on a LRU basis.

```<code>cache = Cache()

@app.route('/')
def foobar():
    name = request.args['name']
    foo = cache.get(name)
    if foo is None:
        foo = load_foo(name)
        cache.add(foo)

    return foo.bar()
</code>```

The problem I am having is I do not know how to share this cache between Gunicorn workers. I'm working with limited memory and don't want to be holding duplicate objects. Certain objects will be used very often and some probably never, so I think it really makes sense to hold them in memory.

This is just something that will only be taking requests from another application (both running on the same server), I just wanted to keep this code separate. Am I going the completely wrong direction by even using Gunicorn in the first place?

答: I don't see anything wrong with using Gunicorn, but it's probably not necessary to think about scaling horizontally unless you are close to putting this into production. Anyway, I'd recommend using a separate service as a cache, rather than having one in python memory. That way, each worker can open a connection to the cache as needed. Redis is a popular option, but you may have to do some data manipulation to store the data, e.g. store the data as a JSON string rather than a python object. Redis can act as a LRU cache by configuring it: https://redis.io/topics/lru-cache</p>

ContentLicense: CC BY-SA 4.0

Body:
I am working on a small service using Gunicorn and Flask (Python 3.6).The pseudocode below shows roughly the behavior I want. There are a lot of serialized foo objects, and I want to hold as many of these in memory as possible and delete them on a LRU basis.

cache = Cache()

@app.route('/')
def foobar():
    name = request.args['name']
    foo = cache.get(name)
    if foo is None:
        foo = load_foo(name)
        cache.add(foo)

    return foo.bar()

The problem I am having is I do not know how to share this cache between Gunicorn workers. I'm working with limited memory and don't want to be holding duplicate objects. Certain objects will be used very often and some probably never, so I think it really makes sense to hold them in memory.

This is just something that will only be taking requests from another application (both running on the same server), I just wanted to keep this code separate. Am I going the completely wrong direction by even using Gunicorn in the first place?


问:
passing model in layout in asp.net mvc with multiple classes
I have 4 view models , one controller , _layout.cshtml and index.cshtml .
the objective is to get left accordian menu in the _layout but with model

left menu willl be like a accordian menu , where clicked submenu will open and when clicked again it will close .

js - css is totaly fine - the only problem i am facing of object reference null error .

if i try it in a new view , it works , creates problem when its in layout . But i have to put it in layout.cshtml

-----------------_layout.cshtml-------------

```<code>@model LeftSubMenuFinal.ViewModels.LayoutViewModel

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
     @using (Html.BeginForm("Index", "Menu"))
        {
            <div id="accordian">
                <ul>
                    <li>
                        @{
            foreach (var MenuItem in Model._homeViewModel.LeftMenuModel)
            {
                var SubMenuItem = Model._homeViewModel.LeftSubMenuModel.Where(m => m.MainMenuID == MenuItem.ID);

                <h3><a href="@MenuItem.MainMenuURL"> @MenuItem.MainMenuItem </a></h3>

                if (SubMenuItem.Count() > 0)
                {
                    <ul>
                        @foreach (var SubItem in SubMenuItem)
                        {
                            @*<li><a href='@SubItem.SubMenuURL'>@SubItem.SubMenuItem</a></li>*@
                            <li>@Html.ActionLink(@SubItem.SubMenuItem, @SubItem.SubMenuActionURL, @SubItem.SubMenuControllerURL)</li>
                        }
                    </ul>
                }

            }
                        }
                </ul>
            </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>
</code>```

---------------------LayoutViewModel ---------------------

```<code>public HomeViewModel _homeViewModel { get; set; }

        public LayoutViewModel()
        {

            _homeViewModel.LeftMenuModel= new List<MainMenu>();
            _homeViewModel.LeftMenuModel = _homeViewModel.GetMainMenu();
            _homeViewModel.LeftSubMenuModel = new List<SubMenu>();
            _homeViewModel.LeftSubMenuModel = _homeViewModel.GetSubMenu();
        }
</code>```

-------------------------HomeViewModel---------------

```<code> public class HomeViewModel :LayoutViewModel
    {
        public List<MainMenu> LeftMenuModel { get; set; }
        public List<SubMenu> LeftSubMenuModel { get; set; }

        public List<MainMenu> GetMainMenu()
        {
            List<MainMenu> ObjMainMenu = new List<MainMenu>();
            ObjMainMenu.Add(new MainMenu { ID = 1, MainMenuItem = "Parent menu 1 ", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 2, MainMenuItem = "Parent menu 2", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 3, MainMenuItem = "Parent menu 3", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 4, MainMenuItem = "Parent menu 4", MainMenuURL = "#" });
            return ObjMainMenu;
        }
        public List<SubMenu> GetSubMenu()
        {
            List<SubMenu> ObjSubMenu = new List<SubMenu>();
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "sub menu1", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "sub menu2", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "sub menu3", SubMenuControllerURL = "#", SubMenuActionURL = "#" });

            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "sub menu1", SubMenuControllerURL = "Home", SubMenuActionURL = "Index" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "sub menu2", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "sub menu3", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            return ObjSubMenu;
        }
    }
</code>```

-----------------------MainMenu.cs------

```<code>public class MainMenu :LayoutViewModel
    {

        public int ID;
        public string MainMenuItem;
        public string MainMenuURL;
    }
</code>```

------------------SubMenu.cs--------------------

```<code> public class SubMenu :LayoutViewModel
    {
        public int MainMenuID;
        public string SubMenuItem;
        public string SubMenuControllerURL;
        public string SubMenuActionURL;
    }
</code>```

-------------------------MenuController ------------

```<code> public class MenuController : Controller
    {
        //
        // GET: /Menu/
        public ActionResult Index()
        {
            HomeViewModel model = new HomeViewModel();

            return View("Index",model);
        }
    }
</code>```

------------------Index.cshtml  -- Menu controller -----------------

```<code>@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
Menu - Index
</code>```

----------------------Js =-----------------------

```<code>$(document).ready(function () {
    $("#accordian h3").click(function () {
        $("#accordian ul ul").slideUp();
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown();
        }
    });
});
</code>```

------------------------css files --------------------------

```<code>#accordian {
    background: #4D6974;
    width: 300px;
    margin: 50px auto 0 auto;
    color: white;
   position:absolute;
   height:400px;
    /*Shadow */
    box-shadow: 0 5px 15px 1px rgba(0, 0, 0, 0.6), 0 0 200px 1px rgba(255, 255, 255, 0.5);
}
    /*heading styles*/
    #accordian h3 {
        font-size: 30px;
        line-height: 30px;
        padding: 0 15px;
        cursor: pointer;
        /*fallback for browsers not supporting gradients*/
        background: #003040;
        background: linear-gradient(#003040, #002535);
    }
        /*heading hover effect*/
        #accordian h3:hover {
            text-shadow: 0 0 1px rgba(255, 255, 255, 0.7);
        }
        /*iconfont styles*/
        #accordian h3 a {
            color: white;
            text-decoration: none;
            font-size: 20px;
            line-height: 30px;
            padding: 0 10px;
            /*transition for smooth hover animation*/
        }

            #accordian h3 a:hover {
                color: #E1E1E1;
            }
    /*list items*/
    #accordian li {
        list-style-type: none;
        background: #4D6974;
    }
    /*links*/
    #accordian ul ul li a {
        color: white;
        text-decoration: none;
        font-size: 15px;
        line-height: 27px;
        display: block;
        padding: 0 15px;
        /*transition for  hover animation*/
        transition: all 0.15s;
    }
        /*hover effect on links*/
        #accordian ul ul li a:hover {
            background: #003545;
            border-left: 10px solid red;
        }
    /* hide the non active */
    #accordian ul ul {
        display: none;
    }

    #accordian li.active ul {
        display: block;
    }
</code>```

-----error coming in the below place of _layout.cshtml
the model is always null

```<code> <li>
                    @{
        foreach (var MenuItem in Model._homeViewModel.LeftMenuModel)
        {
            var SubMenuItem = Model._homeViewModel.LeftSubMenuModel.Where(m => m.MainMenuID == MenuItem.ID);

            <h3><a href="@MenuItem.MainMenuURL"> @MenuItem.MainMenuItem </a></h3>
</code>```

答:
If it's only an issue with your layout page, perhaps you need to reconsider how you have structured your view models. Something seems off in regards to the order of your Models. It should probably be structured closer to something like:

```<code>@model ViewModels.LayoutViewModel.LeftSubMenuFinal
</code>```

You could also render it as a partial view within the layout. Something like:

```<code>@{
   Html.RenderPartial("your view", your_model);
}
</code>```

Body:
I have 4 view models , one controller , _layout.cshtml and index.cshtml .
the objective is to get left accordian menu in the _layout but with model

left menu willl be like a accordian menu , where clicked submenu will open and when clicked again it will close .

js - css is totaly fine - the only problem i am facing of object reference null error .

if i try it in a new view , it works , creates problem when its in layout . But i have to put it in layout.cshtml

-----------------_layout.cshtml-------------

@model LeftSubMenuFinal.ViewModels.LayoutViewModel

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

     @using (Html.BeginForm("Index", "Menu"))
        {

                        @{
            foreach (var MenuItem in Model._homeViewModel.LeftMenuModel)
            {
                var SubMenuItem = Model._homeViewModel.LeftSubMenuModel.Where(m => m.MainMenuID == MenuItem.ID);

 @MenuItem.MainMenuItem

                if (SubMenuItem.Count() > 0)
                {

                        @foreach (var SubItem in SubMenuItem)
                        {
                            @*
@SubItem.SubMenuItem
*@

@Html.ActionLink(@SubItem.SubMenuItem, @SubItem.SubMenuActionURL, @SubItem.SubMenuControllerURL)

                        }

                }

            }
                        }

        @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

---------------------LayoutViewModel ---------------------

public HomeViewModel _homeViewModel { get; set; }

        public LayoutViewModel()
        {

            _homeViewModel.LeftMenuModel= new List<MainMenu>();
            _homeViewModel.LeftMenuModel = _homeViewModel.GetMainMenu();
            _homeViewModel.LeftSubMenuModel = new List<SubMenu>();
            _homeViewModel.LeftSubMenuModel = _homeViewModel.GetSubMenu();
        }

-------------------------HomeViewModel---------------

 public class HomeViewModel :LayoutViewModel
    {
        public List<MainMenu> LeftMenuModel { get; set; }
        public List<SubMenu> LeftSubMenuModel { get; set; }

        public List<MainMenu> GetMainMenu()
        {
            List<MainMenu> ObjMainMenu = new List<MainMenu>();
            ObjMainMenu.Add(new MainMenu { ID = 1, MainMenuItem = "Parent menu 1 ", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 2, MainMenuItem = "Parent menu 2", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 3, MainMenuItem = "Parent menu 3", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 4, MainMenuItem = "Parent menu 4", MainMenuURL = "#" });
            return ObjMainMenu;
        }
        public List<SubMenu> GetSubMenu()
        {
            List<SubMenu> ObjSubMenu = new List<SubMenu>();
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "sub menu1", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "sub menu2", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "sub menu3", SubMenuControllerURL = "#", SubMenuActionURL = "#" });

            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "sub menu1", SubMenuControllerURL = "Home", SubMenuActionURL = "Index" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "sub menu2", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "sub menu3", SubMenuControllerURL = "#", SubMenuActionURL = "#" });
            return ObjSubMenu;
        }
    }

-----------------------MainMenu.cs------

public class MainMenu :LayoutViewModel
    {

        public int ID;
        public string MainMenuItem;
        public string MainMenuURL;
    }

------------------SubMenu.cs--------------------

 public class SubMenu :LayoutViewModel
    {
        public int MainMenuID;
        public string SubMenuItem;
        public string SubMenuControllerURL;
        public string SubMenuActionURL;
    }

-------------------------MenuController ------------

 public class MenuController : Controller
    {
        //
        // GET: /Menu/
        public ActionResult Index()
        {
            HomeViewModel model = new HomeViewModel();

            return View("Index",model);
        }
    }

------------------Index.cshtml  -- Menu controller -----------------

@{
    ViewBag.Title = "Index";
}

Index

Menu - Index

----------------------Js =-----------------------

$(document).ready(function () {
    $("#accordian h3").click(function () {
        $("#accordian ul ul").slideUp();
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown();
        }
    });
});

------------------------css files --------------------------

#accordian {
    background: #4D6974;
    width: 300px;
    margin: 50px auto 0 auto;
    color: white;
   position:absolute;
   height:400px;
    /*Shadow */
    box-shadow: 0 5px 15px 1px rgba(0, 0, 0, 0.6), 0 0 200px 1px rgba(255, 255, 255, 0.5);
}
    /*heading styles*/
    #accordian h3 {
        font-size: 30px;
        line-height: 30px;
        padding: 0 15px;
        cursor: pointer;
        /*fallback for browsers not supporting gradients*/
        background: #003040;
        background: linear-gradient(#003040, #002535);
    }
        /*heading hover effect*/
        #accordian h3:hover {
            text-shadow: 0 0 1px rgba(255, 255, 255, 0.7);
        }
        /*iconfont styles*/
        #accordian h3 a {
            color: white;
            text-decoration: none;
            font-size: 20px;
            line-height: 30px;
            padding: 0 10px;
            /*transition for smooth hover animation*/
        }

            #accordian h3 a:hover {
                color: #E1E1E1;
            }
    /*list items*/
    #accordian li {
        list-style-type: none;
        background: #4D6974;
    }
    /*links*/
    #accordian ul ul li a {
        color: white;
        text-decoration: none;
        font-size: 15px;
        line-height: 27px;
        display: block;
        padding: 0 15px;
        /*transition for  hover animation*/
        transition: all 0.15s;
    }
        /*hover effect on links*/
        #accordian ul ul li a:hover {
            background: #003545;
            border-left: 10px solid red;
        }
    /* hide the non active */
    #accordian ul ul {
        display: none;
    }

    #accordian li.active ul {
        display: block;
    }

-----error coming in the below place of _layout.cshtml
the model is always null

                    @{
        foreach (var MenuItem in Model._homeViewModel.LeftMenuModel)
        {
            var SubMenuItem = Model._homeViewModel.LeftSubMenuModel.Where(m => m.MainMenuID == MenuItem.ID);

 @MenuItem.MainMenuItem

Body:
If it's only an issue with your layout page, perhaps you need to reconsider how you have structured your view models. Something seems off in regards to the order of your Models. It should probably be structured closer to something like:

@model ViewModels.LayoutViewModel.LeftSubMenuFinal

You could also render it as a partial view within the layout. Something like:

@{
   Html.RenderPartial("your view", your_model);
}


问:
i am trying to code in c sharp and i have a 3D array like this
i am trying to code in c sharp and i have a 3D array like this:

1 7 13

3 9 15

5 11 17

here is my code:

```<code> int row = 3;
            int col = 3;
            int[,] times;
            times = new int[col, row];
            string matrixstring = " ";
            int mult = -1;

            for (int j = 0; j != row; j++)
            {
                for (int i = 0; i != col; i++)
                {
                    mult = mult + 2;
                    matrixstring += mult.ToString();
                    matrixstring += " ";
                }
                    matrixstring += Environment.NewLine;
                }
                this.richTextBox1.Text = matrixstring;
</code>```

i got output :

1  3 5

7  9 11

13 15 17

so whats the problem in my code..?

答:
The problem with your code is, that you increase the value in the inner loop, which is building one line, by 2, so of course you get the output as you have shown it below your code.
If you want to get the output as it is at the beginning of your question, then you should increase the value in the inner loop by 6. The starting values of the lines should be increased by 2.
By the way you do not use the times array.
An example producing the above output:

```<code>        int row = 3;
        int col = 3;
        string matrixstring = "";

        for (int j = 0; j != row; j++) {
            int mult = 1+j*2;
            for (int i = 0; i != col; i++) {
                matrixstring += mult.ToString ();
                matrixstring += " ";
                mult += 6;
            }
            matrixstring += Environment.NewLine;
            this.richTextBox1.Text = matrixstring;
</code>```

Body:
i am trying to code in c sharp and i have a 3D array like this:

1 7 13

3 9 15

5 11 17

here is my code:

 int row = 3;
            int col = 3;
            int[,] times;
            times = new int[col, row];
            string matrixstring = " ";
            int mult = -1;

            for (int j = 0; j != row; j++)
            {
                for (int i = 0; i != col; i++)
                {
                    mult = mult + 2;
                    matrixstring += mult.ToString();
                    matrixstring += " ";
                }
                    matrixstring += Environment.NewLine;
                }
                this.richTextBox1.Text = matrixstring;

i got output :

1  3 5

7  9 11

13 15 17

so whats the problem in my code..?

Body:
The problem with your code is, that you increase the value in the inner loop, which is building one line, by 2, so of course you get the output as you have shown it below your code.
If you want to get the output as it is at the beginning of your question, then you should increase the value in the inner loop by 6. The starting values of the lines should be increased by 2.
By the way you do not use the times array.
An example producing the above output:

        int row = 3;
        int col = 3;
        string matrixstring = "";

        for (int j = 0; j != row; j++) {
            int mult = 1+j*2;
            for (int i = 0; i != col; i++) {
                matrixstring += mult.ToString ();
                matrixstring += " ";
                mult += 6;
            }
            matrixstring += Environment.NewLine;
            this.richTextBox1.Text = matrixstring;


问:
Swift GET request with parameters
I'm very new to swift, so I will probably have a lot of faults in my code but what I'm trying to achieve is send a GET request to a localhost server with paramters. More so I'm trying to achieve it given my function take two parameters baseURL:string,params:NSDictionary. I am not sure how to combine those two into the actual URLRequest ? Here is what I have tried so far

```<code>    func sendRequest(url:String,params:NSDictionary){
       let urls: NSURL! = NSURL(string:url)
       var request = NSMutableURLRequest(URL:urls)
       request.HTTPMethod = "GET"
       var data:NSData! =  NSKeyedArchiver.archivedDataWithRootObject(params)
       request.HTTPBody = data
       println(request)
       var session = NSURLSession.sharedSession()
       var task = session.dataTaskWithRequest(request, completionHandler:loadedData)
       task.resume()

    }

}

func loadedData(data:NSData!,response:NSURLResponse!,err:NSError!){
    if(err != nil){
        println(err?.description)
    }else{
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println(jsonResult)

    }

}
</code>```

答:
I am using this, try it in playground. Define the base urls as Struct in Constants</p>

```<code>struct Constants {

    struct APIDetails {
        static let APIScheme = "https"
        static let APIHost = "restcountries.eu"
        static let APIPath = "/rest/v1/alpha/"
    }
}

private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {

    var components = URLComponents()
    components.scheme = Constants.APIDetails.APIScheme
    components.host   = Constants.APIDetails.APIHost
    components.path   = Constants.APIDetails.APIPath
    if let paramPath = pathparam {
        components.path = Constants.APIDetails.APIPath + "\(paramPath)"
    }
    if !parameters.isEmpty {
        components.queryItems = [URLQueryItem]()
        for (key, value) in parameters {
            let queryItem = URLQueryItem(name: key, value: "\(value)")
            components.queryItems!.append(queryItem)
        }
    }

    return components.url!
}

let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")

//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true
</code>```

Title: Swift GET request with parameters

Body:
I'm very new to swift, so I will probably have a lot of faults in my code but what I'm trying to achieve is send a GET request to a localhost server with paramters. More so I'm trying to achieve it given my function take two parameters baseURL:string,params:NSDictionary. I am not sure how to combine those two into the actual URLRequest ? Here is what I have tried so far

    func sendRequest(url:String,params:NSDictionary){
       let urls: NSURL! = NSURL(string:url)
       var request = NSMutableURLRequest(URL:urls)
       request.HTTPMethod = "GET"
       var data:NSData! =  NSKeyedArchiver.archivedDataWithRootObject(params)
       request.HTTPBody = data
       println(request)
       var session = NSURLSession.sharedSession()
       var task = session.dataTaskWithRequest(request, completionHandler:loadedData)
       task.resume()

    }

}

func loadedData(data:NSData!,response:NSURLResponse!,err:NSError!){
    if(err != nil){
        println(err?.description)
    }else{
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println(jsonResult)

    }

}

Body:
I am using this, try it in playground. Define the base urls as Struct in Constants

struct Constants {

    struct APIDetails {
        static let APIScheme = "https"
        static let APIHost = "restcountries.eu"
        static let APIPath = "/rest/v1/alpha/"
    }
}

private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {

    var components = URLComponents()
    components.scheme = Constants.APIDetails.APIScheme
    components.host   = Constants.APIDetails.APIHost
    components.path   = Constants.APIDetails.APIPath
    if let paramPath = pathparam {
        components.path = Constants.APIDetails.APIPath + "\(paramPath)"
    }
    if !parameters.isEmpty {
        components.queryItems = [URLQueryItem]()
        for (key, value) in parameters {
            let queryItem = URLQueryItem(name: key, value: "\(value)")
            components.queryItems!.append(queryItem)
        }
    }

    return components.url!
}

let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")

//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true


问:
Can We Calculate The DOM Length of Each Steps in jQuery UI Slider
Using jquery UI Slider I just wonder if there is a way to calculate the CSS length(width) of between steps in UI Slider? For example at following code I need to calculate the actual width between step1 (min) and step2 and so on!

```<code> $( function() {
 $('#slider').slider({
      min: 1,
      max: 5,
      range: "min",
      animate:"slow",
      value: 0
    });
  } );
</code>```

答:
Not sure why you'd need this detail. It can be calculated.

http://api.jqueryui.com/slider/#option-step

step

Type: Number

Default: 1

Determines the size or amount of each interval or step the slider takes between the min and max. The full specified value range of the slider (max - min) should be evenly divisible by the step.

JavaScript

```<code>$(function() {
  $('#slider').slider({
    min: 1,
    max: 5,
    range: "min",
    animate:"slow",
    value: 0
  });
  // Collect full width
  var slideWidth = $("#slider").width();
  // Collect number of steps in slider
  var sliderSteps = $("#slider").slider("option", "step");
  var stepWidth = slideWidth / sliderSteps;
  console.log("The Slider Width: " + slideWidth + "px, with " + sliderSteps + " steps, and each steps is " + stepWidth + "px wide.");
});
</code>```

Body:
Using jquery UI Slider I just wonder if there is a way to calculate the CSS length(width) of between steps in UI Slider? For example at following code I need to calculate the actual width between step1 (min) and step2 and so on!

 $( function() {
 $('#slider').slider({
      min: 1,
      max: 5,
      range: "min",
      animate:"slow",
      value: 0
    });
  } );

Body:
Not sure why you'd need this detail. It can be calculated.

http://api.jqueryui.com/slider/#option-step

step

Type: Number

Default: 1

Determines the size or amount of each interval or step the slider takes between the min and max. The full specified value range of the slider (max - min) should be evenly divisible by the step.

JavaScript

$(function() {
  $('#slider').slider({
    min: 1,
    max: 5,
    range: "min",
    animate:"slow",
    value: 0
  });
  // Collect full width
  var slideWidth = $("#slider").width();
  // Collect number of steps in slider
  var sliderSteps = $("#slider").slider("option", "step");
  var stepWidth = slideWidth / sliderSteps;
  console.log("The Slider Width: " + slideWidth + "px, with " + sliderSteps + " steps, and each steps is " + stepWidth + "px wide.");
});


问:
jQuery plugin which lets users draw rectangles in a div works in basic setup, but not when implemented in my page?
I'm using this Boxer plugin to allow the user to draw rectangles in a div. I've got it working in this jsFiddle.

But I can't get it working in this one, which is how I would be using it. I think it may be because of the CSS styling? Can anyone tell why it doesn't work?

Thanks for reading.

答:
The reason is that the plug-in was using jQueryUI 1.7.2, and in the second example you were using the jQueryUI 1.8 Framework, some things are incompatible, see this document on how to update the plug-in to match the new framework

http://jqueryui.com/docs/Upgrade_Guide


问:
JPQL - how to select all entities not referred to by any row from other entity set
I have entity Parent and Child with unilateral relation Child n -> 1 Parent. In other words Parent does not know about its children.

How to write an JPQL query which would select all instances of Parent which are not referred to by a particular subset of Child which meet certain predicate?

Example:
select all parents which are not referred to by children who are younger than 8 years

答:
You can try a LEFT OUTER JOIN on the parent/child relationship, e.g.:

```<code>SELECT c, p.name FROM Country c LEFT OUTER JOIN c.capital p
</code>```

If the nulls are a problem, you can get rid of them by adding something like:

```<code>... WHERE p.id IS NOT NULL
</code>```

For further detailed explanation, see this guide: http://www.objectdb.com/java/jpa/query/jpql/from#LEFT_OUTER_JOIN_

If the parent does not know about the children, then you can achieve similar results by using a subquery to filter parent, e.g.:

```<code>SELECT e.parent_id
    FROM ParentEntity e
    WHERE e.parent_id NOT IN (
    SELECT c.parent_id FROM ChildEntity c) ...
</code>```

Body:
You can try a LEFT OUTER JOIN on the parent/child relationship, e.g.:

SELECT c, p.name FROM Country c LEFT OUTER JOIN c.capital p

If the nulls are a problem, you can get rid of them by adding something like:

... WHERE p.id IS NOT NULL

For further detailed explanation, see this guide: http://www.objectdb.com/java/jpa/query/jpql/from#LEFT_OUTER_JOIN_

If the parent does not know about the children, then you can achieve similar results by using a subquery to filter parent, e.g.:

SELECT e.parent_id
    FROM ParentEntity e
    WHERE e.parent_id NOT IN (
    SELECT c.parent_id FROM ChildEntity c) ...


问:
convert form application to wpf application makes an error
Hi i have an application that is programmed by c# windows form and works great .i move all codes of this application to wpf project but a function in wpf have an error

I declare this function as you ca see :

```<code> [System.Runtime.InteropServices.DllImport("MNPR.dll")]
 unsafe private static extern int LP_Initialize(char* security_code, byte log_level, IntPtr hwndMsg);
</code>```

and call this here

```<code> public MainForm()
        {
            InitializeComponent();
            unsafe
            {
                string security_code = "TSF";
                char[] security_code_p = new char[40];
                for (int i = 0; i < security_code.Length; i++)
                    security_code_p[i] = security_code[i];
                fixed (char* p = &security_code_p[0])
                {
                    LP_Initialize(p, 1, Handle);
                }
            }

            LP_SetParams(10, 7, 20, 15, 1100, show_car_image ? (byte)2 : (byte)1, 0);

        }
</code>```

I move all these code to wpf project as you can see:

```<code>  public MainViewModel()
        {

            string publicKey = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<RSAParameters xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Exponent>AQAB</Exponent>\r\n  <Modulus>x2U1misu3xXuLCAf79dVzUc8b1XcRJUL24gSSc41i2sY5c7nI7s5XUceuMU0o7YwHaLEp2upRI9B8PWAQzIeumFGxnui4sdJBTcY9loP7/+N85PL5MWuxBn6e3ejjwTQUEZ0QS7CgJk8jyF4Ae2M/bpWED6ZHmNs2PgYnHNQEqv3Zb5kuof4JL1C+rK9qnT5HNreF/N322uE7HbazZIPGqCnO4bO4RQupd15ztV8O4S7g5dtSucG7AxYbRl+RpxXZA1GQy2dA29wA8kaFtFoe0D4DCF+Ohfg+ySMdgZSw2BRqkOQc+r5I4ETo4KA+/9Yrm4IdHk++KxWQ5CwapRgIQ==</Modulus>\r\n</RSAParameters>";
            secureString = Utility.ConvertToSecureString(publicKey);
            publicKey = string.Empty;
            timerCallWS = new System.Timers.Timer(30000);
            this.timerCallWS.Elapsed += new ElapsedEventHandler(this.timerCallWS_Tick);

            NewCarReceiption = new MainModel();
            SaveCommand = new MCR.Commands.RelayCommand(Save, CanSave);
            ClearCommand = new MCR.Commands.RelayCommand(Clear);
            CaptureCommand = new MCR.Commands.RelayCommand(Capture);
            PreviewCommand = new Commands.RelayCommand(Preview);
            WindowLoadEvent = new DelegateCommand<object>(Load);
            CancelAsyncCommand = new MCR.Commands.RelayCommand(CancelAsync);
            IncorrectRecognitionCommand = new MCR.Commands.RelayCommand(IncorrectRecognition);
            CorrectRecognitionCommand = new MCR.Commands.RelayCommand(CorrectRecognition);
            cmbVehicleTypeChangedEvent = new DelegateCommand<object>(VehicleTypeChangedEvent);
            cmbVehicleSystemChangedEvent = new DelegateCommand<object>(VehicleSystemChangedEvent);
            controlGotFocusEvent = new DelegateCommand<object>(ControlGotFocusEvent);

            this.PLQRecognitionBtnVisibilityStatus = false;
            CancelAsyncVisibility = false;
            MainWrapPanel = false;

            unsafe
            {
                //MessageBox.Show("HID = " + LP_GetHID().ToString());
                string security_code = "TSF";
                char[] security_code_p = new char[40];
                for (int i = 0; i < security_code.Length; i++)
                    security_code_p[i] = security_code[i];
                fixed (char* p = &security_code_p[0])
                {
                    LP_Initialize(p, 1,Handle);
                }
            }
            //it is not required to call LP_SetParams with default params, but if you want to change them, you must call it
            LP_SetParams(10, 7, 20, 15, 1100, show_car_image ? (byte)2 : (byte)1, 0);
            string info = "آستانهی تشخیص ورود خودرو\n" +
    "برای تصاویر شب، مقدار 7 و برای روز مقدار 20 مناسب است\n" +
"مقدار بزرگتر حساسیت کمتری دارد و خودروی کمتری تشخیص می دهد";

        }
</code>```

As you can see this part LP_Initialize(p, 1,Handle); Handle.what should i use instead of Handle in wpf?

答:
WPF doesn't provide direct access to the HWND like WinForms does. Getting it is not hard, though. From within your Window subclass, you can do something like:

```<code>IntPtr handle = new WindowInteropHelper(this).Handle;
</code>```

From within UserControl subclasses, you can do something like:

```<code>Window window = Window.GetWindow(this);
if (window == null)
{
    // The user control is not on a window.
    // Handle this situation as appropriate.
}
IntPtr handle = new WindowInteropHelper(window).Handle;
</code>```

Body:
Hi i have an application that is programmed by c# windows form and works great .i move all codes of this application to wpf project but a function in wpf have an error

I declare this function as you ca see :

 [System.Runtime.InteropServices.DllImport("MNPR.dll")]
 unsafe private static extern int LP_Initialize(char* security_code, byte log_level, IntPtr hwndMsg);

and call this here

 public MainForm()
        {
            InitializeComponent();
            unsafe
            {
                string security_code = "TSF";
                char[] security_code_p = new char[40];
                for (int i = 0; i < security_code.Length; i++)
                    security_code_p[i] = security_code[i];
                fixed (char* p = &security_code_p[0])
                {
                    LP_Initialize(p, 1, Handle);
                }
            }

            LP_SetParams(10, 7, 20, 15, 1100, show_car_image ? (byte)2 : (byte)1, 0);

        }

I move all these code to wpf project as you can see:

  public MainViewModel()
        {

            string publicKey = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<RSAParameters xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Exponent>AQAB</Exponent>\r\n  <Modulus>x2U1misu3xXuLCAf79dVzUc8b1XcRJUL24gSSc41i2sY5c7nI7s5XUceuMU0o7YwHaLEp2upRI9B8PWAQzIeumFGxnui4sdJBTcY9loP7/+N85PL5MWuxBn6e3ejjwTQUEZ0QS7CgJk8jyF4Ae2M/bpWED6ZHmNs2PgYnHNQEqv3Zb5kuof4JL1C+rK9qnT5HNreF/N322uE7HbazZIPGqCnO4bO4RQupd15ztV8O4S7g5dtSucG7AxYbRl+RpxXZA1GQy2dA29wA8kaFtFoe0D4DCF+Ohfg+ySMdgZSw2BRqkOQc+r5I4ETo4KA+/9Yrm4IdHk++KxWQ5CwapRgIQ==</Modulus>\r\n</RSAParameters>";
            secureString = Utility.ConvertToSecureString(publicKey);
            publicKey = string.Empty;
            timerCallWS = new System.Timers.Timer(30000);
            this.timerCallWS.Elapsed += new ElapsedEventHandler(this.timerCallWS_Tick);

            NewCarReceiption = new MainModel();
            SaveCommand = new MCR.Commands.RelayCommand(Save, CanSave);
            ClearCommand = new MCR.Commands.RelayCommand(Clear);
            CaptureCommand = new MCR.Commands.RelayCommand(Capture);
            PreviewCommand = new Commands.RelayCommand(Preview);
            WindowLoadEvent = new DelegateCommand<object>(Load);
            CancelAsyncCommand = new MCR.Commands.RelayCommand(CancelAsync);
            IncorrectRecognitionCommand = new MCR.Commands.RelayCommand(IncorrectRecognition);
            CorrectRecognitionCommand = new MCR.Commands.RelayCommand(CorrectRecognition);
            cmbVehicleTypeChangedEvent = new DelegateCommand<object>(VehicleTypeChangedEvent);
            cmbVehicleSystemChangedEvent = new DelegateCommand<object>(VehicleSystemChangedEvent);
            controlGotFocusEvent = new DelegateCommand<object>(ControlGotFocusEvent);

            this.PLQRecognitionBtnVisibilityStatus = false;
            CancelAsyncVisibility = false;
            MainWrapPanel = false;

            unsafe
            {
                //MessageBox.Show("HID = " + LP_GetHID().ToString());
                string security_code = "TSF";
                char[] security_code_p = new char[40];
                for (int i = 0; i < security_code.Length; i++)
                    security_code_p[i] = security_code[i];
                fixed (char* p = &security_code_p[0])
                {
                    LP_Initialize(p, 1,Handle);
                }
            }
            //it is not required to call LP_SetParams with default params, but if you want to change them, you must call it
            LP_SetParams(10, 7, 20, 15, 1100, show_car_image ? (byte)2 : (byte)1, 0);
            string info = "آستانهی تشخیص ورود خودرو\n" +
    "برای تصاویر شب، مقدار 7 و برای روز مقدار 20 مناسب است\n" +
"مقدار بزرگتر حساسیت کمتری دارد و خودروی کمتری تشخیص می دهد";

        }

As you can see this part LP_Initialize(p, 1,Handle); Handle.what should i use instead of Handle in wpf?

Body:
WPF doesn't provide direct access to the HWND like WinForms does. Getting it is not hard, though. From within your Window subclass, you can do something like:

IntPtr handle = new WindowInteropHelper(this).Handle;

From within UserControl subclasses, you can do something like:

Window window = Window.GetWindow(this);
if (window == null)
{
    // The user control is not on a window.
    // Handle this situation as appropriate.
}
IntPtr handle = new WindowInteropHelper(window).Handle;


问:
How to access an array of dictionaries?
I want to use an array of dictionaries to store all the content of an Excel workbook to later process it and make operations in memory.

I have defined that the first row of the Excel workbook is the key and the rest of rows are content. As I have one key for many values, I need to store them in a different container (this would be the array).

A sample of the content

```
Code Name Surname
1    a     b
2    c     d
```

The code:

```<code>For Each rcell In ws.UsedRange.Cells
   If rcell.Row > 1 Then
        ReDim Preserve aRows(rcell.Row - 2)
        'Set aRows(rcell.Row - 2) = CreateObject("scripting.dictionary")
        Set pInfo = New Scripting.Dictionary
        pInfo.Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        'aRows(rcell.Row - 2).Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        Set aRows(rcell.Row - 2) = pInfo
    End If
Next rcell
</code>```

This code creates an array of dictionaries.

When I try to access the data I get an error.

I know that at least it is storing values because when I use:

```<code>debug.print(ubound(aRows))
</code>```

I am getting the value (1) in this case.

I tried accessing the content with

```<code>for each row in aRows
    debug.print(row.key)
next row
</code>```

However, this is not accepted. How do I access the data?

An alternative or something more simple would be great.

答:
you could use</p>

```<code>Dim myRow as Variant, key as variant
For Each myRow In aRows
    With myRow
        For Each key In .Keys
            Debug.Print key, .Item(key)
        Next
    End With
Next
</code>```

Title: How to access an array of dictionaries?

Body:
I want to use an array of dictionaries to store all the content of an Excel workbook to later process it and make operations in memory.

I have defined that the first row of the Excel workbook is the key and the rest of rows are content. As I have one key for many values, I need to store them in a different container (this would be the array).

A sample of the content

Code Name Surname
1    a     b
2    c     d

The code:

For Each rcell In ws.UsedRange.Cells
   If rcell.Row > 1 Then
        ReDim Preserve aRows(rcell.Row - 2)
        'Set aRows(rcell.Row - 2) = CreateObject("scripting.dictionary")
        Set pInfo = New Scripting.Dictionary
        pInfo.Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        'aRows(rcell.Row - 2).Add Key:=Cells(1, rcell.Column).Value, Item:=rcell.Value
        Set aRows(rcell.Row - 2) = pInfo
    End If
Next rcell

This code creates an array of dictionaries.

When I try to access the data I get an error.

I know that at least it is storing values because when I use:

debug.print(ubound(aRows))

I am getting the value (1) in this case.

I tried accessing the content with

for each row in aRows
    debug.print(row.key)
next row

However, this is not accepted. How do I access the data?

An alternative or something more simple would be great.

Body:
you could use

Dim myRow as Variant, key as variant
For Each myRow In aRows
    With myRow
        For Each key In .Keys
            Debug.Print key, .Item(key)
        Next
    End With
Next


问:
Convert Observable<Single<Object>> to Single<List<Object>>
Is there a possibility to convert Observable<Single<Object>> to Single<List<Object>>? I'd also like to know whether it's possible to make the observable to wait for all the underlying singles to complete.

答:
I imagine you could do it with something like this (untested):</p>

```<code>myObservable
    .flatMap(x -> x)    // Flatten to Observable<Object>
    .toList()           // Collect in an Observable<List<Object>>
    .single();          // Convert to Single
</code>```

Body:
I imagine you could do it with something like this (untested):

myObservable
    .flatMap(x -> x)    // Flatten to Observable<Object>
    .toList()           // Collect in an Observable<List<Object>>
    .single();          // Convert to Single


问:
How to rotate a table left margin name with knitr and xtable?
I'm trying to get the results of the table command nicely printed on a pdf by using knitr and xtable.

As a toy example let's say I want to get the table created with

table(c(2,5,5,5,5,7,7,7,7,NA),c(1,5,2,2,2,2,7,7,NA,NA))

I would like to get something like this:

As you can see var1 is rotated 90 degrees counterclockwise.

How can I get it?
Similar results, with less or more lines are OK too.

I've being trying different methods I've found.

I've created this Rnw file,

```<code>\documentclass{article}
\usepackage{booktabs}
\usepackage{rotating}
\begin{document}

<<r table, results='asis', echo=FALSE>>=
library(knitr)
library(xtable)
var1 <- c(2,5,5,5,5,7,7,7,7,NA)
var2 <- c(1,5,2,2,2,2,7,7,NA,NA)

print(xtable(table(var1,var2)))

print.xtableFtable(xtableFtable(ftable(var1,var2),
       method = "row.compact"))

print.xtableFtable(xtableFtable(ftable(var1,var2),
       method = "row.compact"), rotate.rownames = TRUE)

print.xtable(xtable(table(var1,var2)), include.rownames=T,include.colnames=T)

@

\end{document}
</code>```

You can see below the result of the three methods I've tried.

I can't get the expected result.

Any solution with other common package or kable it's OK too.

I guess it could be done with \rotatebox{90} but I don't know how to force xtable to use it nor how to tell xtable to place the left title on the left instead of just being on the top-right.

答:
Here's one possibility. Disclaimer: I am the package author.

```<code>library(huxtable)
var1 <- c(2,5,5,5,5,7,7,7,7,NA)
var2 <- c(1,5,2,2,2,2,7,7,NA,NA)
tbl <- table(var1 = var1, var2 = var2)

ht <- as_hux(tbl)
ht <- cbind(rep('', 4), ht)

ht[2,1] <- 'var1'

ht <- rbind(rep('', 6), ht)
ht[2,2] <- '' # get rid of "rownames"
ht[1,3] <- 'var2'
colspan(ht)[1,3] <- 4
rowspan(ht)[3, 1] <- 3
rotation(ht)[3, 1] <- 90
right_border(ht)[,2] <- 1
bottom_border(ht)[5, -1] <- 1
bottom_border(ht)[2, -1] <- 1
ht
</code>```

When used in an rmarkdown PDF document, this produces:

Body:
I'm trying to get the results of the table command nicely printed on a pdf by using knitr and xtable.

As a toy example let's say I want to get the table created with

table(c(2,5,5,5,5,7,7,7,7,NA),c(1,5,2,2,2,2,7,7,NA,NA))

I would like to get something like this:

As you can see var1 is rotated 90 degrees counterclockwise.

How can I get it?
Similar results, with less or more lines are OK too.

I've being trying different methods I've found.

I've created this Rnw file,

\documentclass{article}
\usepackage{booktabs}
\usepackage{rotating}
\begin{document}

<<r table, results='asis', echo=FALSE>>=
library(knitr)
library(xtable)
var1 <- c(2,5,5,5,5,7,7,7,7,NA)
var2 <- c(1,5,2,2,2,2,7,7,NA,NA)

print(xtable(table(var1,var2)))

print.xtableFtable(xtableFtable(ftable(var1,var2),
       method = "row.compact"))

print.xtableFtable(xtableFtable(ftable(var1,var2),
       method = "row.compact"), rotate.rownames = TRUE)

print.xtable(xtable(table(var1,var2)), include.rownames=T,include.colnames=T)

@

\end{document}

You can see below the result of the three methods I've tried.

I can't get the expected result.

Any solution with other common package or kable it's OK too.

I guess it could be done with \rotatebox{90} but I don't know how to force xtable to use it nor how to tell xtable to place the left title on the left instead of just being on the top-right.

Body:
Here's one possibility. Disclaimer: I am the package author.

library(huxtable)
var1 <- c(2,5,5,5,5,7,7,7,7,NA)
var2 <- c(1,5,2,2,2,2,7,7,NA,NA)
tbl <- table(var1 = var1, var2 = var2)

ht <- as_hux(tbl)
ht <- cbind(rep('', 4), ht)

ht[2,1] <- 'var1'

ht <- rbind(rep('', 6), ht)
ht[2,2] <- '' # get rid of "rownames"
ht[1,3] <- 'var2'
colspan(ht)[1,3] <- 4
rowspan(ht)[3, 1] <- 3
rotation(ht)[3, 1] <- 90
right_border(ht)[,2] <- 1
bottom_border(ht)[5, -1] <- 1
bottom_border(ht)[2, -1] <- 1
ht

When used in an rmarkdown PDF document, this produces:


问:
Change the size of a JTextField inside a JBorderLayout
When I use the code below it doesn't alter the size at all, it still fills the area in the grid.</p>

```<code>JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);
</code>```

答:
Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:</p>

```<code>JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);
</code>```

Body:
When I use the code below it doesn't alter the size at all, it still fills the area in the grid.

JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);

Body:
Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:

JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);


问:
MySQL REGEXP query - accent insensitive search
I'm looking to query a database of wine names, many of which contain accents (but not in a uniform way, and so similar wines may be entered with or without accents)

The basic query looks like this:

```<code>SELECT * FROM `table` WHERE `wine_name` REGEXP '[[:<:]]Faugères[[:>:]]'
</code>```

which will return entries with 'Faugères' in the title, but not 'Faugeres'

```<code>SELECT * FROM `table` WHERE `wine_name` REGEXP '[[:<:]]Faugeres[[:>:]]'
</code>```

does the opposite.

I had thought something like:

```<code>SELECT *
FROM `table`
WHERE `wine_name` REGEXP '[[:<:]]Faug[eèêéë]r[eèêéë]s[[:>:]]'
</code>```

might do the trick, but this only returns the results without the accents.

The field is collated as utf8_unicode_ci, which from what I've read is how it should be.

Any suggestions?!

答:
I had the same problem trying to find every record matching one of the following patterns: 'copropriété', 'copropriete', 'COPROPRIÉTÉ', 'Copropri?t?'

REGEXP 'copropri.{1,2}t.{1,2} worked for me.
Basically, .{1,2} will should work in every case wether the character is 1 or 2 byte encoded.

Explanation: https://dev.mysql.com/doc/refman/5.7/en/regexp.html

Warning

The REGEXP and RLIKE operators work in byte-wise fashion, so they are not multibyte safe and may produce unexpected results with multibyte character sets. In addition, these operators compare characters by their byte values and accented characters may not compare as equal even if a given collation treats them as equal.

Body:
I'm looking to query a database of wine names, many of which contain accents (but not in a uniform way, and so similar wines may be entered with or without accents)

The basic query looks like this:

SELECT * FROM `table` WHERE `wine_name` REGEXP '[[:<:]]Faugères[[:>:]]'

which will return entries with 'Faugères' in the title, but not 'Faugeres'

SELECT * FROM `table` WHERE `wine_name` REGEXP '[[:<:]]Faugeres[[:>:]]'

does the opposite.

I had thought something like:

SELECT *
FROM `table`
WHERE `wine_name` REGEXP '[[:<:]]Faug[eèêéë]r[eèêéë]s[[:>:]]'

might do the trick, but this only returns the results without the accents.

The field is collated as utf8_unicode_ci, which from what I've read is how it should be.

Any suggestions?!


问:
node red function and export to CSV
I have the raspberry pi and sense hat.  I wish to extract acceleration z,y,x,Temperature and Pressure and time to csv.  However, the code I've written does not do what i want it to do.  I was expecting the data to leave the function in an array but the debug window shows them as separate objects.  How do i get acceleration z,y,x and time to leave as one array so i can export to CSV?

```<code>    29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.9487
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.2781
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.1491
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Date
"Wed Mar 29 2017 16:17:25 GMT+0000 (UTC)
</code>```

Here's the function code :

```<code>var msgAccelZ,msgAccelX,msgAccelY,msgTemperature,msgPressure,msgCurrentTime;
if (msg.topic === 'motion') {
    msgAccelZ = { payload: msg.payload.acceleration.z, };
    msgAccelX = { payload: msg.payload.acceleration.x, };
    msgAccelY = { payload: msg.payload.acceleration.y, };
} else if (msg.topic === 'environment') {
    msgTemperature = { payload: msg.payload.temperature };
    msgPressure = { payload: msg.payload.pressure };
}
msgCurrentTime = new Date();
return [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];
</code>```

答:
A Function needs to return a message object, not just a raw value.

By convention, you'd put the data you want to return under msg.payload:

```<code>msg.payload = [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];
return msg;
</code>```

The documentation for the Function node explains in more detail: http://nodered.org/docs/writing-functions

Title: node red function and export to CSV

Body:
I have the raspberry pi and sense hat.  I wish to extract acceleration z,y,x,Temperature and Pressure and time to csv.  However, the code I've written does not do what i want it to do.  I was expecting the data to leave the function in an array but the debug window shows them as separate objects.  How do i get acceleration z,y,x and time to leave as one array so i can export to CSV?

    29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.9487
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.2781
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.1491
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Date
"Wed Mar 29 2017 16:17:25 GMT+0000 (UTC)

Here's the function code :

var msgAccelZ,msgAccelX,msgAccelY,msgTemperature,msgPressure,msgCurrentTime;
if (msg.topic === 'motion') {
    msgAccelZ = { payload: msg.payload.acceleration.z, };
    msgAccelX = { payload: msg.payload.acceleration.x, };
    msgAccelY = { payload: msg.payload.acceleration.y, };
} else if (msg.topic === 'environment') {
    msgTemperature = { payload: msg.payload.temperature };
    msgPressure = { payload: msg.payload.pressure };
}
msgCurrentTime = new Date();
return [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];

Body:
A Function needs to return a message object, not just a raw value.

By convention, you'd put the data you want to return under msg.payload:

msg.payload = [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];
return msg;

The documentation for the Function node explains in more detail: http://nodered.org/docs/writing-functions


问:
extract only one part from xpath scrapy
I want to extract from a web page information with xpath, but I'm getting the wrong information. In this code below I want to get 100 :

```<code><div class="pricing">
 <p class="pricePerUnit">
  <p class="pricePerMeasure">
  £0.64
  <abbr title="per">/</abbr>
  100
</code>```

I want to only get 100, I tried this but it returns £0.64 100.  But,  I just want to retrieve the 100 :

```<code>`prices_mesure3 = `response.xpath('//p[@class="pricePerMeasure"]/text()').extract()`
</code>```

Any help please ?

答:
Xpath support node indexing, so you can just add [last()] or [2] to your xpath:

```<code>In: response.xpath('//p[@class="pricePerMeasure"]/text()[last()]').extract_first()
Out: u'\n  100 '
</code>```

Title: extract only one part from xpath scrapy

Body:
I want to extract from a web page information with xpath, but I'm getting the wrong information. In this code below I want to get 100 :

  £0.64
  /
  100

I want to only get 100, I tried this but it returns £0.64 100.  But,  I just want to retrieve the 100 :

`prices_mesure3 = `response.xpath('//p[@class="pricePerMeasure"]/text()').extract()`

Any help please ?

Body:
Xpath support node indexing, so you can just add [last()] or [2] to your xpath:

In: response.xpath('//p[@class="pricePerMeasure"]/text()[last()]').extract_first()
Out: u'\n  100 '


问:
Not receiving the JSON object on onClick
I have very small UseCase. The user enters the ISBN of a book and is shown a book with that particular ISBN. However, only half of the functionality is working.

For some reason, I am not able to receive the JSON containing the book in the ejs so I can populate the table with only one book.

Here I am calling the search function and then i populate the table with the book

```<code>function searchISBN() {
        var input = $('#IdSearchISBN').val();
        $(document).ready(function () {
            $.get('/searchISBN/' + input, function (data, status) {
                var trJSON = '';
                $.each(data, function (i, item) {
                    trJSON += '<tbody><tr><td>' +
                        data[i].ISBN +
                        '</td><td>' +
                        data[i].BookTitle +
                        '</td><td>' +
                        data[i].BookAuthors +
                        '</td><td>'
                        + data[i].Publisher +
                        '</td><td>' +
                        data[i].Description +
                        '</td><td>' +
                        data[i].CallNumber +
                        '</td></tr></tbody>';
                });
                $('#booksTable').append(trJSON);
            });
        });
    }
</code>```

This is the function that does the searching and returns backs the book

```<code>app.get('/searchISBN/:searchID', function (req, res) {
    console.log(req.params.searchID);
    if (req.params.searchID != "" && req.params.searchID) {
        BookTable.find({ISBN: req.params.searchID}, function (err, booksList) {
            if (err) {
                res.status(500);
                return console.error(err);
            }
            console.log("I have sent data");
            console.log(booksList);
            res.send(booksList);
        });
    }
});
</code>```

I did put logs to see if the search function was really sending the book or not and yes it does. However, I am not able to receive it
Below are the logs I got.

9780730324218
I have sent data
[ { _id: 58c7d0694172ab199c6de78e,
    ISBN: '9780730324218',
    BookTitle: 'The Barefoot Investor : The Only Money Guide You\'ll Ever Need',
    BookAuthors: 'Scott Pape',
    Publisher: 'John Wiley & Sons Australia Ltd',
    Description: 'This is the only money guide you\'ll ever need That\'s a bold claim, given there are already thousands of finance books on the shelves.',
    CallNumber: ' 0730324214',
    __v: 0 } ]

Any suggestions?

答:
Your returned data is not valid JSON, as the _id property is a string but it's not quoted correctly. Fix that and the code works:

var data = [{
  _id: '58c7d0694172ab199c6de78e',
  ISBN: '9780730324218',
  BookTitle: 'The Barefoot Investor : The Only Money Guide You\'ll Ever Need',
  BookAuthors: 'Scott Pape',
  Publisher: 'John Wiley & Sons Australia Ltd',
  Description: 'This is the only money guide you\'ll ever need That\'s a bold claim, given there are already thousands of finance books on the shelves.',
  CallNumber: ' 0730324214',
  __v: 0
}]

var trJSON = '';
$.each(data, function(i, item) {
  trJSON += '

' +
    data[i].ISBN +
    '	' +
    data[i].BookTitle +
    '	' +
    data[i].BookAuthors +
    '	' + data[i].Publisher +
    '	' +
    data[i].Description +
    '	' +
    data[i].CallNumber +
    '

';
});
$('#booksTable').append(trJSON);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="booksTable"></table></code>```

Body:
I have very small UseCase. The user enters the ISBN of a book and is shown a book with that particular ISBN. However, only half of the functionality is working.

For some reason, I am not able to receive the JSON containing the book in the ejs so I can populate the table with only one book.

Here I am calling the search function and then i populate the table with the book

function searchISBN() {
        var input = $('#IdSearchISBN').val();
        $(document).ready(function () {
            $.get('/searchISBN/' + input, function (data, status) {
                var trJSON = '';
                $.each(data, function (i, item) {
                    trJSON += '

' +
                        data[i].ISBN +
                        '	' +
                        data[i].BookTitle +
                        '	' +
                        data[i].BookAuthors +
                        '	'
                        + data[i].Publisher +
                        '	' +
                        data[i].Description +
                        '	' +
                        data[i].CallNumber +
                        '

';
                });
                $('#booksTable').append(trJSON);
            });
        });
    }

This is the function that does the searching and returns backs the book

app.get('/searchISBN/:searchID', function (req, res) {
    console.log(req.params.searchID);
    if (req.params.searchID != "" && req.params.searchID) {
        BookTable.find({ISBN: req.params.searchID}, function (err, booksList) {
            if (err) {
                res.status(500);
                return console.error(err);
            }
            console.log("I have sent data");
            console.log(booksList);
            res.send(booksList);
        });
    }
});

I did put logs to see if the search function was really sending the book or not and yes it does. However, I am not able to receive it
Below are the logs I got.

9780730324218
I have sent data
[ { _id: 58c7d0694172ab199c6de78e,
    ISBN: '9780730324218',
    BookTitle: 'The Barefoot Investor : The Only Money Guide You\'ll Ever Need',
    BookAuthors: 'Scott Pape',
    Publisher: 'John Wiley & Sons Australia Ltd',
    Description: 'This is the only money guide you\'ll ever need That\'s a bold claim, given there are already thousands of finance books on the shelves.',
    CallNumber: ' 0730324214',
    __v: 0 } ]

Any suggestions?

Body:
Your returned data is not valid JSON, as the _id property is a string but it's not quoted correctly. Fix that and the code works:

var data = [{
  _id: '58c7d0694172ab199c6de78e',
  ISBN: '9780730324218',
  BookTitle: 'The Barefoot Investor : The Only Money Guide You\'ll Ever Need',
  BookAuthors: 'Scott Pape',
  Publisher: 'John Wiley & Sons Australia Ltd',
  Description: 'This is the only money guide you\'ll ever need That\'s a bold claim, given there are already thousands of finance books on the shelves.',
  CallNumber: ' 0730324214',
  __v: 0
}]

var trJSON = '';
$.each(data, function(i, item) {
  trJSON += '<tbody><tr><td>' +
    data[i].ISBN +
    '</td><td>' +
    data[i].BookTitle +
    '</td><td>' +
    data[i].BookAuthors +
    '</td><td>' + data[i].Publisher +
    '</td><td>' +
    data[i].Description +
    '</td><td>' +
    data[i].CallNumber +
    '</td></tr></tbody>';
});
$('#booksTable').append(trJSON);

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


问:
How to route Matlab input to specific DOS cmd input?
I have a Matlab script that uses the dos command to open an exe.  This exe pauses awaiting user input.  For this project I need everything to be scripted and dynamic, so matlab has to be able to continue running its script, dynamically determine what to input to the running exe, and then input it.

So far, I have been able to get the exe to run in the background and let the matlab script continue by using dos('test.exe &'), but I cant get then get matlab to send inputs to the running exe.  I have tried batch files and I still run into the same issue, which is how do I automate the sending of inputs to the cmd line when the cmd line exe running is paused awaiting user input?

My best guess would be that I need to reroute the standard output of matlab to the standard input of a specific, already open instance of cmd, but I have no idea how to do that and have been unable to find anything so far on the internet.  Any insight would be greatly appreciated, thanks.

答:
Thanks to the wonderful explanation by Luis Mendo, I have quickly put together a function that takes a string input and outputs the proper robot commands.  It works for me!    </p>

```<code>function typeStringOut(robot,text)

keyMatch = {};
keyMatch(1,:) = {'`','-','=',',','.','/',';','[',']','\'};
keyMatch(2,:) = {'~','_','+','<','>','?',':','{','}','|'};
keyMatch(3,:) = {'BACK_QUOTE','MINUS','EQUALS','COMMA','PERIOD','SLASH','SEMICOLON','OPEN_BRACKET','CLOSE_BRACKET','BACK_SLASH'};
numKeyMatch = {};
numKeyMatch(1,:) = {'1','2','3','4','5','6','7','8','9','0'};
numKeyMatch(2,:) = {'!','@','#','$','%','^','&','*','(',')'};

for i=1:length(text)
    if isstrprop(text(i),'alpha')
        if isstrprop(text(i),'upper')
            robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
        end
        eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',upper(text(i)),');']);
        if isstrprop(text(i),'upper')
            robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
        end
    elseif isstrprop(text(i),'digit')
        eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',text(i),');']);
    elseif isstrprop(text(i),'wspace')&&strcmp(text(i),' ')
        eval('robot.keyPress(java.awt.event.KeyEvent.VK_SPACE);');
    elseif isstrprop(text(i),'punct')||isstrprop(text(i),'graphic')
        switch text(i)
            case {'`','-','=',',','.','/',';','[',']','\'}
                matchIdx = strcmp(keyMatch(1,:),text(i));
                eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',keyMatch{3,matchIdx},');']);
            case {'~','_','+','<','>','?',':','{','}','|'}
                robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
                matchIdx = strcmp(keyMatch(2,:),text(i));
                eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',keyMatch{3,matchIdx},');']);
                robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
            case {'!','@','#','$','%','^','&','*','(',')'}
                robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
                matchIdx = strcmp(numKeyMatch(2,:),text(i));
                eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',numKeyMatch{3,matchIdx},');']);
                robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
            otherwise
                error([text(i),' is unknown character']);
        end

    elseif strcmp(text(i),'<')||strcmp(text(i),'>')
        robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
        matchIdx = strcmp(keyMatch(2,:),text(i));
        eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',keyMatch{1,matchIdx},');']);
        robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
    else
        error([text(i),' is unknown character']);
    end
end

robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);

end
</code>```

Body:
Thanks to the wonderful explanation by Luis Mendo, I have quickly put together a function that takes a string input and outputs the proper robot commands.  It works for me!

function typeStringOut(robot,text)

keyMatch = {};
keyMatch(1,:) = {'`','-','=',',','.','/',';','[',']','\'};
keyMatch(2,:) = {'~','_','+','<','>','?',':','{','}','|'};
keyMatch(3,:) = {'BACK_QUOTE','MINUS','EQUALS','COMMA','PERIOD','SLASH','SEMICOLON','OPEN_BRACKET','CLOSE_BRACKET','BACK_SLASH'};
numKeyMatch = {};
numKeyMatch(1,:) = {'1','2','3','4','5','6','7','8','9','0'};
numKeyMatch(2,:) = {'!','@','#','$','%','^','&','*','(',')'};

for i=1:length(text)
    if isstrprop(text(i),'alpha')
        if isstrprop(text(i),'upper')
            robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
        end
        eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',upper(text(i)),');']);
        if isstrprop(text(i),'upper')
            robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
        end
    elseif isstrprop(text(i),'digit')
        eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',text(i),');']);
    elseif isstrprop(text(i),'wspace')&&strcmp(text(i),' ')
        eval('robot.keyPress(java.awt.event.KeyEvent.VK_SPACE);');
    elseif isstrprop(text(i),'punct')||isstrprop(text(i),'graphic')
        switch text(i)
            case {'`','-','=',',','.','/',';','[',']','\'}
                matchIdx = strcmp(keyMatch(1,:),text(i));
                eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',keyMatch{3,matchIdx},');']);
            case {'~','_','+','<','>','?',':','{','}','|'}
                robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
                matchIdx = strcmp(keyMatch(2,:),text(i));
                eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',keyMatch{3,matchIdx},');']);
                robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
            case {'!','@','#','$','%','^','&','*','(',')'}
                robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
                matchIdx = strcmp(numKeyMatch(2,:),text(i));
                eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',numKeyMatch{3,matchIdx},');']);
                robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
            otherwise
                error([text(i),' is unknown character']);
        end

    elseif strcmp(text(i),'<')||strcmp(text(i),'>')
        robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
        matchIdx = strcmp(keyMatch(2,:),text(i));
        eval(['robot.keyPress(java.awt.event.KeyEvent.VK_',keyMatch{1,matchIdx},');']);
        robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
    else
        error([text(i),' is unknown character']);
    end
end

robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);

end