问:
Reading value from app/web.config in Asp.net Core
Created asp.net core web application. In this existing class library converted nuget package and installed.
how to assign appsettings key value to class library from asp.net core app.</p>

答:
From the asp.net docs:
https://learn.microsoft.com/de-de/aspnet/core/fundamentals/configuration

Write a Constructor in your StartUp.cs, just like you would do with the 'older' versions of asp.net core.

```<code>public class Startup
{
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();
 ...
</code>```

Create a appsettings.json if not already exist.

Just for Example:
    {
      "key1" : "value1"
    }

Read it with
    Configuration["key1"]

If you need the Configuration in any of your Controller, have a look at the DI in ASP:

https://learn.microsoft.com/de-de/aspnet/core/fundamentals/dependency-injection

Body:
From the asp.net docs:
https://learn.microsoft.com/de-de/aspnet/core/fundamentals/configuration

Write a Constructor in your StartUp.cs, just like you would do with the 'older' versions of asp.net core.

public class Startup
{
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();
 ...

Create a appsettings.json if not already exist.

Just for Example:
    {
      "key1" : "value1"
    }

Read it with
    Configuration["key1"]

If you need the Configuration in any of your Controller, have a look at the DI in ASP:

https://learn.microsoft.com/de-de/aspnet/core/fundamentals/dependency-injection


来源: stackexchange

问:
Kubernetes services communication by REST: Stream ended unexpectedly
There are two services deployed into Kubernetes cluster. Service_1 exposes REST API, and one part of it is the method for file content uploading, so POST request with "Content-Type: multipart/form-data" is used.
The sample of real request, which is sending from Service_2 is:

```<code>Request DefaultFullHttpRequest(decodeResult: success, version: HTTP/1.1,
content: UnpooledHeapByteBuf(freed))
POST /engine-rest/deployment/create HTTP/1.1
Accept: application/json
User-Agent: process
Content-Type: multipart/form-data; boundary=28319d96a8c54b529aa9159ad75edef9
Content-Length: 4028
Host: service.cluster.ip:8080
</code>```

The request cannot be processed and failed with an exception:

```<code>30-Mar-2017 18:17:29.623 WARNING [http-nio-8080-exec-2] org.camunda.bpm.engine.rest.exception.RestExceptionHandler.toResponse org.camunda.bpm.engine.rest.exception.RestException: multipart/form-data cannot be processed
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.parseRequest(MultipartPayloadProvider.java:93)
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.readFrom(MultipartPayloadProvider.java:71)
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.readFrom(MultipartPayloadProvider.java:49)
    at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:105)
    at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.read(GZIPDecodingInterceptor.java:63)
    at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:108)
    at org.jboss.resteasy.core.MessageBodyParameterInjector.inject(MessageBodyParameterInjector.java:169)
    at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:136)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:159)
    at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:257)
    at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:222)
    at org.jboss.resteasy.core.ResourceLocator.invokeOnTargetObject(ResourceLocator.java:159)
    at org.jboss.resteasy.core.ResourceLocator.invoke(ResourceLocator.java:92)
    at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
    at org.jboss.resteasy.core.SynchronousDispatcher.invokePropagateNotFound(SynchronousDispatcher.java:169)
    at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:212)
    at org.jboss.resteasy.plugins.server.servlet.FilterDispatcher.doFilter(FilterDispatcher.java:59)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.camunda.bpm.engine.rest.filter.CacheControlFilter.doFilter(CacheControlFilter.java:41)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.commons.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly
    at org.apache.commons.fileupload.MultipartStream.readHeaders(MultipartStream.java:538)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:999)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
    at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.parseRequest(MultipartPayloadProvider.java:87)
    ... 38 more
</code>```

What might be the reason of this error? I understand that the question doesn't have the direct answer, but I hope someone is able point me into the right way for additional investigation.

P.S. GET type requests of this API work fine.

答: Sorted out! If someone is interested or acccidentaly faced the exatly same problem, the root cause was in CLRF, which are required for multi-part requests, when we were using System.lineSeparator() and thus it hadn't worked under Linux. Yeah, so simple. </p>

ContentLicense: CC BY-SA 3.0

Body:
There are two services deployed into Kubernetes cluster. Service_1 exposes REST API, and one part of it is the method for file content uploading, so POST request with "Content-Type: multipart/form-data" is used.
The sample of real request, which is sending from Service_2 is:

Request DefaultFullHttpRequest(decodeResult: success, version: HTTP/1.1,
content: UnpooledHeapByteBuf(freed))
POST /engine-rest/deployment/create HTTP/1.1
Accept: application/json
User-Agent: process
Content-Type: multipart/form-data; boundary=28319d96a8c54b529aa9159ad75edef9
Content-Length: 4028
Host: service.cluster.ip:8080

The request cannot be processed and failed with an exception:

30-Mar-2017 18:17:29.623 WARNING [http-nio-8080-exec-2] org.camunda.bpm.engine.rest.exception.RestExceptionHandler.toResponse org.camunda.bpm.engine.rest.exception.RestException: multipart/form-data cannot be processed
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.parseRequest(MultipartPayloadProvider.java:93)
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.readFrom(MultipartPayloadProvider.java:71)
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.readFrom(MultipartPayloadProvider.java:49)
    at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:105)
    at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.read(GZIPDecodingInterceptor.java:63)
    at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:108)
    at org.jboss.resteasy.core.MessageBodyParameterInjector.inject(MessageBodyParameterInjector.java:169)
    at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:136)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:159)
    at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:257)
    at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:222)
    at org.jboss.resteasy.core.ResourceLocator.invokeOnTargetObject(ResourceLocator.java:159)
    at org.jboss.resteasy.core.ResourceLocator.invoke(ResourceLocator.java:92)
    at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
    at org.jboss.resteasy.core.SynchronousDispatcher.invokePropagateNotFound(SynchronousDispatcher.java:169)
    at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:212)
    at org.jboss.resteasy.plugins.server.servlet.FilterDispatcher.doFilter(FilterDispatcher.java:59)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.camunda.bpm.engine.rest.filter.CacheControlFilter.doFilter(CacheControlFilter.java:41)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.commons.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly
    at org.apache.commons.fileupload.MultipartStream.readHeaders(MultipartStream.java:538)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:999)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
    at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
    at org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.parseRequest(MultipartPayloadProvider.java:87)
    ... 38 more

What might be the reason of this error? I understand that the question doesn't have the direct answer, but I hope someone is able point me into the right way for additional investigation.

P.S. GET type requests of this API work fine.


问:
Python 3.6 / my function changes my global variables
I am trying really hard for my function not to mess my global 'b' value because I wish to re-use that list in another similar function using sets but it seems that even not using the same name (y), they (b and y) are still bound together...

most of the print lines are for debugging only as I was not understanding what was happening.

What am I doing wrong?

```<code>import random

a = random.sample(range(1,25),8)
b = random.sample(range(1,25),11)
a.sort()
b.sort()

def list_rdup(x,y):
    print('Loop remove duplicates:')
    print('x:',x)
    print('y:',y)
    for i in x:
        y.append(i)
    y.sort()
    print('y modified:',y)
    c = []
    for i in y:
        if i in c:
            pass
        else:
            c.append(i)
    return c

print('a:',a)
print('b:',b)

print(list_rdup(a,b))

print('a:',a)
print('b:',b)
</code>```

Output: we see a and b in their original state.. then I run the function and
print a and b again to show that b was modified in the process...

a: [1, 6, 10, 11, 12, 13, 17, 22]

b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

Loop remove duplicates:

x: [1, 6, 10, 11, 12, 13, 17, 22]

y: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

y modified: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]

[1, 2, 3, 6, 7, 10, 11, 12, 13, 16, 17, 19, 20, 21, 22, 24]

a: [1, 6, 10, 11, 12, 13, 17, 22]

b: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]

答: The call list_rdup(a,b) simply passes the reference of a and b which are stored in x and y. So, any change in x and y will change a and b. If you do not want a and b to change make a copy by using b_copy = b.copy().

Body:
I am trying really hard for my function not to mess my global 'b' value because I wish to re-use that list in another similar function using sets but it seems that even not using the same name (y), they (b and y) are still bound together...

most of the print lines are for debugging only as I was not understanding what was happening.

What am I doing wrong?

import random

a = random.sample(range(1,25),8)
b = random.sample(range(1,25),11)
a.sort()
b.sort()

def list_rdup(x,y):
    print('Loop remove duplicates:')
    print('x:',x)
    print('y:',y)
    for i in x:
        y.append(i)
    y.sort()
    print('y modified:',y)
    c = []
    for i in y:
        if i in c:
            pass
        else:
            c.append(i)
    return c

print('a:',a)
print('b:',b)

print(list_rdup(a,b))

print('a:',a)
print('b:',b)

Output: we see a and b in their original state.. then I run the function and
print a and b again to show that b was modified in the process...

a: [1, 6, 10, 11, 12, 13, 17, 22]

b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

Loop remove duplicates:

x: [1, 6, 10, 11, 12, 13, 17, 22]

y: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

y modified: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]

[1, 2, 3, 6, 7, 10, 11, 12, 13, 16, 17, 19, 20, 21, 22, 24]

a: [1, 6, 10, 11, 12, 13, 17, 22]

b: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]


问:
Catching JSON response form web post request in android
I have been working with WebView in android for loading HTML files in android. On my way, I am trying to test an API service that will let me access the services if I provide required parameter and responds in JSON.
My question is, How can I parse the obtained JSON from the FORM POST request in android and reuse the resultants.

My HTML for form with post method is provided below:

```<code>     <form method="post" action="htts://www.ipay.com.np/api/v2/recharge">
    <div class="col-md-6">

    <div class="form-group">
      <label for="email">Username:</label>
      <input type="email" name="username" class="form-control" id="username" placeholder="Enter username">
    </div>
  </div>

  <div class="col-md-6">

    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password" name="password" class="form-control" id="pwd" placeholder="Enter password">
    </div>
  </div>

  <div class="col-md-12">

  <div class="form-group">
    <label for="choose">Amount:</label>
    <select name="mid"  class="form-control" id="mid" placeholder="Query">
      <option value="null">what-would-you-like-to-do</option>
      <option value="37">NTC-POSTPAID RECHARGE</option>
      <option value="35">NTC LANDLINE PSTN</option>
      <option value="20">NCELL AIRTIME</option>
      <option value="36">NTC PREPAID</option>
      <option value="33">ADSL UNLIMITED</option>
      <option value="39">ADSL VOLUME</option>
      <option value="46">UTL TOPUP</option>

  </select>
  </div>
</div>

  <div class="col-md-6">

    <div class="form-group">
      <label for="phone">Phone Number:</label>
      <input type="text" name="phone" min="1" class="form-control" id="phone" placeholder="Enter phone number">
    </div>
  </div>
  <div class="col-md-6">

    <div class="form-group">
      <label for="amount">Amount:</label>
      <select name="amount"  class="form-control" id="email" placeholder="Enter email">
        <option value="null">select-amount</option>
        <option value="Rs.10">10</option>
        <option value="Rs.20">20</option>
        <option value="Rs.30">30</option>
        <option value="Rs.40">40</option>
        <option value="Rs.50">50</option>
        <option value="Rs.100">100</option>
        <option value="Rs.100+">100+</option>
    </select>
    </div>
  </div>

  <div class="col-md-6">

    <div class="checkbox">
      <label><input type="checkbox"> Remember me</label>
    </div>
  </div>
</div>

    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>
</code>```

And the responce example i get from the following POST method is:

```<code>    {

"txn_no" : 12343,

"ord_no" : 1222,

"status" : "paid",

"merchant" : "Ncell Air time",

"description" : "recharge of...",

"amount" : 20.00, "reward" : 0.02

}
</code>```

It would be very helpfull, if i only get idea to catch the json response in my android application.

答:
There is no need to use webview for its, you can achieve its by HttpPost in activity,  </p>

```<code>public boolean validateLogin()
            {
                try {
                    progressBar.setVisibility(View.VISIBLE);
    //call webservice and get json response
                    String JSONStr = PostData();
                    jsonObject = new JSONObject(JSONStr);
                    String status = jsonObject.get("success").toString();
                    return status.equals("1");
                }
                catch (Exception e)
                {
                    return false;
                }
            }
             public String PostData() {
                    String jsonResponse = "";
                    String URL = "https://example.com/Login.php?Email=" + str_email + "&Password=" + str_password;
                    try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(URL);

                        HttpResponse httpResponse = httpClient.execute(httpPost);

                        HttpEntity httpEntity = httpResponse.getEntity();
                        jsonResponse = readResponse(httpResponse);
                    } catch (Exception exception) {
                    }
                    return jsonResponse;
                }

                public String readResponse(HttpResponse res) {
                    InputStream is = null;
                    String return_text = "";
                    try {
                        is = res.getEntity().getContent();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                        String line = "";
                        StringBuffer sb = new StringBuffer();
                        while ((line = bufferedReader.readLine()) != null) {
                            sb.append(line);
                        }
                        return_text = sb.toString();
                    } catch (Exception e) {

                    }
                    return return_text;

                }
</code>```

Body:
I have been working with WebView in android for loading HTML files in android. On my way, I am trying to test an API service that will let me access the services if I provide required parameter and responds in JSON.
My question is, How can I parse the obtained JSON from the FORM POST request in android and reuse the resultants.

My HTML for form with post method is provided below:

     <form method="post" action="htts://www.ipay.com.np/api/v2/recharge">

      Username:
      <input type="email" name="username" class="form-control" id="username" placeholder="Enter username">

      Password:
      <input type="password" name="password" class="form-control" id="pwd" placeholder="Enter password">

    Amount:
    <select name="mid"  class="form-control" id="mid" placeholder="Query">
      <option value="null">what-would-you-like-to-do</option>
      <option value="37">NTC-POSTPAID RECHARGE</option>
      <option value="35">NTC LANDLINE PSTN</option>
      <option value="20">NCELL AIRTIME</option>
      <option value="36">NTC PREPAID</option>
      <option value="33">ADSL UNLIMITED</option>
      <option value="39">ADSL VOLUME</option>
      <option value="46">UTL TOPUP</option>

  </select>

      Phone Number:
      <input type="text" name="phone" min="1" class="form-control" id="phone" placeholder="Enter phone number">

      Amount:
      <select name="amount"  class="form-control" id="email" placeholder="Enter email">
        <option value="null">select-amount</option>
        <option value="Rs.10">10</option>
        <option value="Rs.20">20</option>
        <option value="Rs.30">30</option>
        <option value="Rs.40">40</option>
        <option value="Rs.50">50</option>
        <option value="Rs.100">100</option>
        <option value="Rs.100+">100+</option>
    </select>

      <input type="checkbox"> Remember me

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

And the responce example i get from the following POST method is:

    {

"txn_no" : 12343,

"ord_no" : 1222,

"status" : "paid",

"merchant" : "Ncell Air time",

"description" : "recharge of...",

"amount" : 20.00, "reward" : 0.02

}

It would be very helpfull, if i only get idea to catch the json response in my android application.

Body:
There is no need to use webview for its, you can achieve its by HttpPost in activity,

public boolean validateLogin()
            {
                try {
                    progressBar.setVisibility(View.VISIBLE);
    //call webservice and get json response
                    String JSONStr = PostData();
                    jsonObject = new JSONObject(JSONStr);
                    String status = jsonObject.get("success").toString();
                    return status.equals("1");
                }
                catch (Exception e)
                {
                    return false;
                }
            }
             public String PostData() {
                    String jsonResponse = "";
                    String URL = "https://example.com/Login.php?Email=" + str_email + "&Password=" + str_password;
                    try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(URL);

                        HttpResponse httpResponse = httpClient.execute(httpPost);

                        HttpEntity httpEntity = httpResponse.getEntity();
                        jsonResponse = readResponse(httpResponse);
                    } catch (Exception exception) {
                    }
                    return jsonResponse;
                }

                public String readResponse(HttpResponse res) {
                    InputStream is = null;
                    String return_text = "";
                    try {
                        is = res.getEntity().getContent();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                        String line = "";
                        StringBuffer sb = new StringBuffer();
                        while ((line = bufferedReader.readLine()) != null) {
                            sb.append(line);
                        }
                        return_text = sb.toString();
                    } catch (Exception e) {

                    }
                    return return_text;

                }


问:
Want to route one component to another component
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>
      </div>
    );
  }
}

export default App;
</code>```

code for index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

Respective i have also component class for Login.js and Register.js

答:
you can use the Link component import from 'react-router', then you should write something like this:

```<code>import { Link, Router, RouterContext, browserHistory } from 'react-router';
</code>```

// inside the component inser the component:

```<code>                        <Link to={'/login'}>clikc to login</Link>
</code>```

so the button should be like this:

```<code>  <Link to={'/login'} class="Button ">Login</Link>
</code>```

if it help you please vote
Thanks Hod

Body:
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (

Welcome to React

        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>

    );
  }
}

export default App;

code for index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Respective i have also component class for Login.js and Register.js

Body:
you can use the Link component import from 'react-router', then you should write something like this:

import { Link, Router, RouterContext, browserHistory } from 'react-router';

// inside the component inser the component:

                        <Link to={'/login'}>clikc to login</Link>

so the button should be like this:

  <Link to={'/login'} class="Button ">Login</Link>

if it help you please vote
Thanks Hod


问:
AngularJS "#!" on url
someone knows what "#!" Means. on the url?

I was working until then this appears,I had a "#" always in the url and would like to keep it that way.
Currently routing is not working anymore,probably because of this url change.

It's part of a business project, i don`t want to change to html5Mode.

I tried to use:

```<code>$locationProvider.hashPrefix("");
</code>```

Even correcting the url in this way routing is having problems

答:
Thats called hash-bang.

To fix this use :

```<code>    angular.module('yourApp', [])
    .config(['$locationProvider', function($locationProvider) {
        $locationProvider.hashPrefix('');
    }]);
</code>```

Adding html5Mode would even get rid of the '#' in the url but if you refresh the page, then you would get a 404 error. This can be fixed by configuring your server a bit. For that you might want to check the nice little tutorials :

https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag

https://www.theodo.fr/blog/2017/01/pretty-url-in-angularjs-and-loopback-drop-the/

There is another answer to the hashbang issue in stackoverlow :

Doing links like Twitter, Hash-Bang #! URL's

Title: AngularJS "#!" on url

Body:
someone knows what "#!" Means. on the url?

I was working until then this appears,I had a "#" always in the url and would like to keep it that way.
Currently routing is not working anymore,probably because of this url change.

It's part of a business project, i don`t want to change to html5Mode.

I tried to use:

$locationProvider.hashPrefix("");

Even correcting the url in this way routing is having problems

Body:
Thats called hash-bang.

To fix this use :

    angular.module('yourApp', [])
    .config(['$locationProvider', function($locationProvider) {
        $locationProvider.hashPrefix('');
    }]);

Adding html5Mode would even get rid of the '#' in the url but if you refresh the page, then you would get a 404 error. This can be fixed by configuring your server a bit. For that you might want to check the nice little tutorials :

https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag

https://www.theodo.fr/blog/2017/01/pretty-url-in-angularjs-and-loopback-drop-the/

There is another answer to the hashbang issue in stackoverlow :

Doing links like Twitter, Hash-Bang #! URL's


问:
Can servlet's doGet method returns value back to java class?
I am calling servlet from simple java class. The servlet doGet method is getting called properly and some logic is written in doGet to get the result as String.

Can I return that string from servlet's doGet method back to calling function from simple java class? If possible, could you please provide the example?

Any help is aprreciated. Thanks in advance.

Below is the ContactServlet simple java class which call the servlet:-

public class ContactServlet {

```<code>public static void main(String[] args) throws IOException {

     String param = "username=YOURSTRING";
        String request = "http://localhost:8080/TestServlet/post";
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" +  Integer.toString(param.getBytes().length));
        connection.setUseCaches (false);

        System.out.println(connection);
        System.out.println(param);

        DataOutputStream out = new DataOutputStream(connection.getOutputStream ());
        out.writeBytes(param);
        out.flush();
        out.close();

        for(int i=1;i<=8;i++){
            System.out.println(connection.getHeaderFieldKey(i)+" = "+connection.getHeaderField(i));
            }

        connection.disconnect();

}
</code>```

}

Below is servlets doGet method:-

```<code>    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String username = request.getParameter( _USERNAME );
    response.setContentType("text/html");
    out.println("");
    out.println("");
    out.println("HelloWorld");
    out.println("");
    out.println("");
    out.println("");
    out.println("Hello " + username + "!");
    out.println("");
    out.println("");
}
</code>```

Instead of writing it to web page, I want the String "Hello Username!" to be returned to ContactServlet class. How can we do that??

答:
Servlet methods are meant to be called by the servlet container, not manually by the programmer),
 so you should not be calling doPost() or doGet() methods by yourself, rather you need a servlet container which will handle those methods for you.

In summary, you need to deploy your Servlet in a Servlet container like Tomcat, Jetty, etc. and when you make HttpURLConnection call, then
 the container delegates the call to the respective Servlet's doPost() or doGet() method.

What happens is that under the hood is that the Servlet container is responsible for instantiating the HttpServletRequest and HttpServletResponse objects and then it delegates the request to the respective servlet methods.

Body:
I am calling servlet from simple java class. The servlet doGet method is getting called properly and some logic is written in doGet to get the result as String.

Can I return that string from servlet's doGet method back to calling function from simple java class? If possible, could you please provide the example?

Any help is aprreciated. Thanks in advance.

Below is the ContactServlet simple java class which call the servlet:-

public class ContactServlet {

public static void main(String[] args) throws IOException {

     String param = "username=YOURSTRING";
        String request = "http://localhost:8080/TestServlet/post";
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" +  Integer.toString(param.getBytes().length));
        connection.setUseCaches (false);

        System.out.println(connection);
        System.out.println(param);

        DataOutputStream out = new DataOutputStream(connection.getOutputStream ());
        out.writeBytes(param);
        out.flush();
        out.close();

        for(int i=1;i<=8;i++){
            System.out.println(connection.getHeaderFieldKey(i)+" = "+connection.getHeaderField(i));
            }

        connection.disconnect();

}

}

Below is servlets doGet method:-

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String username = request.getParameter( _USERNAME );
    response.setContentType("text/html");
    out.println("");
    out.println("");
    out.println("HelloWorld");
    out.println("");
    out.println("");
    out.println("");
    out.println("Hello " + username + "!");
    out.println("");
    out.println("");
}

Instead of writing it to web page, I want the String "Hello Username!" to be returned to ContactServlet class. How can we do that??


问:
How to get inference using Jena command line tool 'sparql'?
A
|_P(p1,p2)
|  |_M(m1,m2)
|
B

I want to get the A's all instances.

my query is

```<code>SELECT ?x
    WHERE {
            ?x rdf:type :A .}
</code>```

Output:
A(p1,p2,m1,m2)

How to get this result using command line tool 'sparql'?.  Means I want to get inference here.

My OWL file is here:

```<code><rdf:RDF xmlns="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    <owl:Ontology rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11"/>

    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#A">
    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#B">
    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#M">
        <rdfs:subClassOf rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P"/>
    </owl:Class>

    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P">
        <rdfs:subClassOf rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#A"/>
    </owl:Class>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#m1">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#M"/>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#m2">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#M"/>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#p1">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P"/>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#p2">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P"/>
    </owl:NamedIndividual>
</rdf:RDF>
</code>```

答:
Maybe this is still useful to some reader.

Jena line commands accept assembler description files as input. 'tarql' supports this with the --desc option, so it should be possible to describe a data set backed by an inference model and your data, and then run your query against it.

Another alternative, which is more general and can be applied to any existing endpoint, might be to run Fuseki on top of your data and with inference enabled (or any other triple store). Then use the SPARQL syntax to do federated queries.

Body:
A
|_P(p1,p2)
|  |_M(m1,m2)
|
B

I want to get the A's all instances.

my query is

SELECT ?x
    WHERE {
            ?x rdf:type :A .}

Output:
A(p1,p2,m1,m2)

How to get this result using command line tool 'sparql'?.  Means I want to get inference here.

My OWL file is here:

<rdf:RDF xmlns="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    <owl:Ontology rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11"/>

    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#A">
    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#B">
    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#M">
        <rdfs:subClassOf rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P"/>
    </owl:Class>

    <owl:Class rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P">
        <rdfs:subClassOf rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#A"/>
    </owl:Class>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#m1">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#M"/>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#m2">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#M"/>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#p1">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P"/>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#p2">
        <rdf:type rdf:resource="http://www.semanticweb.org/chetan/ontologies/2014/5/untitled-ontology-11#P"/>
    </owl:NamedIndividual>
</rdf:RDF>


问:
How can i get output like this in swift
{ length = 30, contents = "something", count = 32.3 }

I need exact output in this bracket {  } not in() or []

```<code>var array:Array<Any> = Array<Any>();
array.append(NSDictionary(object: singleItem.name, forKey: "name" as NSCopying));
array.append(NSDictionary(object: singleItem.planned_revenue, forKey: "planned_revenue" as NSCopying));
array.append(NSDictionary(object: singleItem.phone, forKey: "phone" as NSCopying));
array.append(NSDictionary(object: singleItem.description, forKey: "description" as NSCopying));
array.append(NSDictionary(object: singleItem.email_from, forKey: "email_from" as NSCopying));
 array.append(NSDictionary(object: singleItem.probability, forKey: "probability" as NSCopying));
</code>```

output

```<code>[{
    name = "this is another";
}, {
    "planned_revenue" = "0.0";
}, {
    phone = "";
}, {
    description = "Internal Notes";
}, {
    "email_from" = "thomas.passot@agrolait.example.com";
}, {
    probability = "20.0";
}]
</code>```

I need like

```<code>[{ name = "this is another", "planned_revenue" = "0.0", phone = "", description = "Internal Notes", ..... }]
</code>```

答:
First, you need a dictionary, not an array of dictionaries. Using Swift, you can use Dictionary instead of NSDictionary (Dictionary<String, Any> or [String: Any]):

```<code>let dict: [String: Any] = [
    "name": singleItem.name,
    "planned_revenue": singleItem.planned_revenue,
    "phone": singleItem.phone,
    "description": singleItem.description,
    "email_from": singleItem.email_from,
    "probability": singleItem.probability
]

// If you need a NSDictionary, you can cast it
let nsDict = dict as NSDictionary
</code>```

Take a look at Collection Types in the Swift guide and the Dictionary class reference for more information.

Title: How can i get output like this in swift

Body:
{ length = 30, contents = "something", count = 32.3 }

I need exact output in this bracket {  } not in() or []

var array:Array<Any> = Array<Any>();
array.append(NSDictionary(object: singleItem.name, forKey: "name" as NSCopying));
array.append(NSDictionary(object: singleItem.planned_revenue, forKey: "planned_revenue" as NSCopying));
array.append(NSDictionary(object: singleItem.phone, forKey: "phone" as NSCopying));
array.append(NSDictionary(object: singleItem.description, forKey: "description" as NSCopying));
array.append(NSDictionary(object: singleItem.email_from, forKey: "email_from" as NSCopying));
 array.append(NSDictionary(object: singleItem.probability, forKey: "probability" as NSCopying));

output

[{
    name = "this is another";
}, {
    "planned_revenue" = "0.0";
}, {
    phone = "";
}, {
    description = "Internal Notes";
}, {
    "email_from" = "thomas.passot@agrolait.example.com";
}, {
    probability = "20.0";
}]

I need like

[{ name = "this is another", "planned_revenue" = "0.0", phone = "", description = "Internal Notes", ..... }]

Body:
First, you need a dictionary, not an array of dictionaries. Using Swift, you can use Dictionary instead of NSDictionary (Dictionary<String, Any> or [String: Any]):

let dict: [String: Any] = [
    "name": singleItem.name,
    "planned_revenue": singleItem.planned_revenue,
    "phone": singleItem.phone,
    "description": singleItem.description,
    "email_from": singleItem.email_from,
    "probability": singleItem.probability
]

// If you need a NSDictionary, you can cast it
let nsDict = dict as NSDictionary

Take a look at Collection Types in the Swift guide and the Dictionary class reference for more information.


问:
Publish subscribe doesn't seem to work
I'm new to meteor and I saw that it's better to remove autopublish.
So I try to publish and subscribe a collection to get two different values.
In my meteor side I have :

```<code>Meteor.publish('channelUser',
    function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
        console.log(user);
       var test = Channels.find({
            '_id': {$in : user.profile.channelIds}
        });
        return test;
    }
);

Meteor.publish('channelToJoin',
function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
    console.log(user);

    var test = Channels.find({'_id': {$nin: user.profile.channelIds}});
    console.log(test);
    return test;
});
</code>```

And in my client side in a first component I have :

```<code>this.channelSub = MeteorObservable.subscribe('channelUser').subscribe();
   this.channels = Channels.find({});
</code>```

And on a second component :

```<code> Meteor.subscribe("channelToJoin");
this.channels = Channels.find({}).zone();
</code>```

But on my client side on both of the component, I have the same data.
Is there some kind of conflict in the subscribe ?

I hope I was clear to describe my problem !

答:
You cannot move a document between collections via a subscription. If you subscribe to get a document that's in Pages collection, defined as new Meteor.Collection("pages"), then no matter how your pub channels look like, on the client the document will be found in the collection defined as new </p>

```<code>> Meteor.Collection("pages")
</code>```

<p>. So remove all traces of MyPages and use Pages on the client as well. </p>

Title: Publish subscribe doesn't seem to work

Body:
I'm new to meteor and I saw that it's better to remove autopublish.
So I try to publish and subscribe a collection to get two different values.
In my meteor side I have :

Meteor.publish('channelUser',
    function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
        console.log(user);
       var test = Channels.find({
            '_id': {$in : user.profile.channelIds}
        });
        return test;
    }
);

Meteor.publish('channelToJoin',
function(){
    var user = Meteor.users.findOne({
        '_id':this.userId
    });
    console.log(user);

    var test = Channels.find({'_id': {$nin: user.profile.channelIds}});
    console.log(test);
    return test;
});

And in my client side in a first component I have :

this.channelSub = MeteorObservable.subscribe('channelUser').subscribe();
   this.channels = Channels.find({});

And on a second component :

 Meteor.subscribe("channelToJoin");
this.channels = Channels.find({}).zone();

But on my client side on both of the component, I have the same data.
Is there some kind of conflict in the subscribe ?

I hope I was clear to describe my problem !

Body:
You cannot move a document between collections via a subscription. If you subscribe to get a document that's in Pages collection, defined as new Meteor.Collection("pages"), then no matter how your pub channels look like, on the client the document will be found in the collection defined as new

> Meteor.Collection("pages")

. So remove all traces of MyPages and use Pages on the client as well.


问:
How to drop and recreate Indexes inside PLSQL Stored Procedure
In PLSQL stored procedure, I would like to drop indexes and truncate the table
before inserting data into the table. Then I want to recreate the indexes afterwards . What is the best way of achieving this?

I need something similar like this

```<code>Begin:

Truncate Table
Drop index1
Drop  index2

loop
--- other code
Insert data
commit;
end loop;

Create index1
Create index2

End;
</code>```

答:
We can't run DDL directly in PL/SQL.

The best approach is to use the Oracle built-in DBMS_UTILITY.EXEC_DDL_STATEMENT(). It's covered in the docs Find out more. But basically:

```<code>begin
    DBMS_UTILITY.EXEC_DDL_STATEMENT('drop index index1')
    DBMS_UTILITY.EXEC_DDL_STATEMENT('drop index index2')
    DBMS_UTILITY.EXEC_DDL_STATEMENT('truncate table your_table')
    ....
</code>```

Note that the commands are strings not SQL.

If you're inserting enough data to make it worthwhile dropping and re-creating the indexes then you probably want set operations rather than doing it in a loop. Set operations work on chunks of data rather then individual rows. Quite what approach is appropriate depends on how much data you have.

"I want to insert data from staging table and then joining with other table"

So the most efficient route is likely to be

```<code> insert into your_table
 select /*+ append */  ....
 from staging_table
      join other_table
      on ...
</code>```

However, depending on your definition of "huge" you may need to use a PL/SQL bulk operation, with a FORALL insertion. That would require reading from your staging table in chunks, so it would entail a loop. Find out more

Body:
In PLSQL stored procedure, I would like to drop indexes and truncate the table
before inserting data into the table. Then I want to recreate the indexes afterwards . What is the best way of achieving this?

I need something similar like this

Begin:

Truncate Table
Drop index1
Drop  index2

loop
--- other code
Insert data
commit;
end loop;

Create index1
Create index2

End;

Body:
We can't run DDL directly in PL/SQL.

The best approach is to use the Oracle built-in DBMS_UTILITY.EXEC_DDL_STATEMENT(). It's covered in the docs Find out more. But basically:

begin
    DBMS_UTILITY.EXEC_DDL_STATEMENT('drop index index1')
    DBMS_UTILITY.EXEC_DDL_STATEMENT('drop index index2')
    DBMS_UTILITY.EXEC_DDL_STATEMENT('truncate table your_table')
    ....

Note that the commands are strings not SQL.

If you're inserting enough data to make it worthwhile dropping and re-creating the indexes then you probably want set operations rather than doing it in a loop. Set operations work on chunks of data rather then individual rows. Quite what approach is appropriate depends on how much data you have.

"I want to insert data from staging table and then joining with other table"

So the most efficient route is likely to be

 insert into your_table
 select /*+ append */  ....
 from staging_table
      join other_table
      on ...

However, depending on your definition of "huge" you may need to use a PL/SQL bulk operation, with a FORALL insertion. That would require reading from your staging table in chunks, so it would entail a loop. Find out more


问:
C# Array.Resize Passing a Ref instead of a Value
Title might be a bit misleading

I have a string array. That I would like to pass by reference.

I know it can be accomplished simply by

```<code>public class test{
    string[] content = {"abc", "abd"};
    ViewContent vc = new ViewContent();

    public static void Main()
    {
        vc.InitView(content);
    }
}

public class ViewContent{
     string[] contentToView;

     public void InitView(ref string[] contentToShow)
     {
         contentToView = contentToShow;
         View();
     }

     public void View()
     {
         //Do whatever with contentToView
         //Example
         Array.Resize<string> (ref contentToView, someInt);
     }
}
</code>```

If I were to resize the array with

```<code>Array.Resize()
</code>```

The reference breaks and any further edits upon the resized array is not reflected on the main array from test class.

My question is:

How do I prevent the reference to the main array from breaking when the need arises for me to resize it?

Rephrase

How do I resize contentToView while also resizing content in test class?

Yes, I know it would be simpler to use Lists but I am experimenting with Arrays.

Yes, I know my problems would be solved if I pass in the test object instead of just an array. I am avoiding this method because I have other objects that have string arrays as well. You might ask that if I have other objects, that serve similar functions I could use inheritance and take in the base class to ensure that all my content can be shown. This is something I would like to avoid.

答: There is no way to resize array itself. Array.Resize method creates new array. So in anyway your old reference will not work. Also there is no sense to use ref keyword in your code. It can be useful only if you will reassign contentToShow inside InitView method. You have to use some class (List or your own class) if you want to "resize" your array (reassign it to the new array).

Body:
Title might be a bit misleading

I have a string array. That I would like to pass by reference.

I know it can be accomplished simply by

public class test{
    string[] content = {"abc", "abd"};
    ViewContent vc = new ViewContent();

    public static void Main()
    {
        vc.InitView(content);
    }
}

public class ViewContent{
     string[] contentToView;

     public void InitView(ref string[] contentToShow)
     {
         contentToView = contentToShow;
         View();
     }

     public void View()
     {
         //Do whatever with contentToView
         //Example
         Array.Resize<string> (ref contentToView, someInt);
     }
}

If I were to resize the array with

Array.Resize()

The reference breaks and any further edits upon the resized array is not reflected on the main array from test class.

My question is:

How do I prevent the reference to the main array from breaking when the need arises for me to resize it?

Rephrase

How do I resize contentToView while also resizing content in test class?

Yes, I know it would be simpler to use Lists but I am experimenting with Arrays.

Yes, I know my problems would be solved if I pass in the test object instead of just an array. I am avoiding this method because I have other objects that have string arrays as well. You might ask that if I have other objects, that serve similar functions I could use inheritance and take in the base class to ensure that all my content can be shown. This is something I would like to avoid.


问:
Android app with fragments and listviews
I am developing an android app and I have multiple fragments with a listview  in each fragment.

I fill my listviews with data from an api.

I am wondering how can I cache my data so when a user changes the fragment(slide left - right) the data will not be loaded again.

答:
You can use AsyncTask for downloading data while the UI thread is running.

Create an inner class in an Activity extending AsyncTask.

```<code> private class MyTask extends AsyncTask<Void, Void, Void> { ... }
</code>```

The class provides methods like doInBackground(Params... params)where you can download the data and pass it on to other fragments/Activities after it has been downloaded by using onPostExecute(Result result)

The official documentation for the same: https://developer.android.com/reference/android/os/AsyncTask.html

Body:
You can use AsyncTask for downloading data while the UI thread is running.

Create an inner class in an Activity extending AsyncTask.

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

The class provides methods like doInBackground(Params... params)where you can download the data and pass it on to other fragments/Activities after it has been downloaded by using onPostExecute(Result result)

The official documentation for the same: https://developer.android.com/reference/android/os/AsyncTask.html


问:
How to install cherrytree on mac os?
Cherrytree is really a good tool for me, but there is no versions for mac.I have tried all ways I know, but with no lucky.Is there someone who installed cherrytree on macOS successfully?</p>

答:
You need to download the Windows version of CherryTree and install it using PlayOnMac. It is a wine implementation and can be used to run a lot of Windows applications.

I hope there will be a native Mac OS X client in the future.

Hope this helps, let me know.

Regards,

Title: How to install cherrytree on mac os?


问:
How to draw shapes like circles, oval, ractangles dynamically in iOS?
I have a UICollectionView of showing shapes like circles, oval, ractangles. So when I clicked on Cell I need to draw same shape on UIView and after I need to move and resize that view which was drawn by clicking in Cell. How it can achieve in iOS ? Thanks in advance. </p>

答:
You can use CAShapeLayer. eg. Draw a circle.

```<code>shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = aFrame;
UIBezierPath *spath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:12 startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shapeLayer.strokeColor = [UIColor colorWithRed:71/255.0 green:157/255.0 blue:252/255.0 alpha:1].CGColor;
shapeLayer.path = spath.CGPath;
shapeLayer.strokeStart = 0;
shapeLayer.strokeEnd = 0;
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 2;
[self.layer addSublayer:shapeLayer];
</code>```

I hope it help you

Body:
You can use CAShapeLayer. eg. Draw a circle.

shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = aFrame;
UIBezierPath *spath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:12 startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shapeLayer.strokeColor = [UIColor colorWithRed:71/255.0 green:157/255.0 blue:252/255.0 alpha:1].CGColor;
shapeLayer.path = spath.CGPath;
shapeLayer.strokeStart = 0;
shapeLayer.strokeEnd = 0;
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 2;
[self.layer addSublayer:shapeLayer];

I hope it help you


Title: Python 3.6 / my function changes my global variables

Body:
I am trying really hard for my function not to mess my global 'b' value because I wish to re-use that list in another similar function using sets but it seems that even not using the same name (y), they (b and y) are still bound together...

most of the print lines are for debugging only as I was not understanding what was happening.

What am I doing wrong?

import random

a = random.sample(range(1,25),8)
b = random.sample(range(1,25),11)
a.sort()
b.sort()

def list_rdup(x,y):
    print('Loop remove duplicates:')
    print('x:',x)
    print('y:',y)
    for i in x:
        y.append(i)
    y.sort()
    print('y modified:',y)
    c = []
    for i in y:
        if i in c:
            pass
        else:
            c.append(i)
    return c

print('a:',a)
print('b:',b)

print(list_rdup(a,b))

print('a:',a)
print('b:',b)

Output: we see a and b in their original state.. then I run the function and
print a and b again to show that b was modified in the process...

a: [1, 6, 10, 11, 12, 13, 17, 22]

b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

Loop remove duplicates:

x: [1, 6, 10, 11, 12, 13, 17, 22]

y: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

y modified: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]

[1, 2, 3, 6, 7, 10, 11, 12, 13, 16, 17, 19, 20, 21, 22, 24]

a: [1, 6, 10, 11, 12, 13, 17, 22]

b: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]

Body:
To avoid altering the elements, copy the array.

import random

a=[1, 6, 10, 11, 12, 13, 17, 22]
b=[1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]
#a.sort()
#b.sort()

def list_rdup(x,y):
    print('Loop remove duplicates:')
    print('x:',x)
    print('y:',y)
    for i in x:
        y.append(i)
    y.sort()
    print('y modified:',y)
    c = []
    for i in y:
        if i in c:
            pass
        else:
            c.append(i)
    return c

print('a:',a)
print('b:',b)

print(list_rdup(a[:], b[:]))

print('a:',a)
print('b:',b)

a: [1, 6, 10, 11, 12, 13, 17, 22]
b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]
Loop remove duplicates:
x: [1, 6, 10, 11, 12, 13, 17, 22]
y: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]
y modified: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]
[1, 2, 3, 6, 7, 10, 11, 12, 13, 16, 17, 19, 20, 21, 22, 24]
a: [1, 6, 10, 11, 12, 13, 17, 22]
b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

Also consider deep copying if you have non-primitive values in the array.


问:
MySQL: index a field that contains only distinct values?
Is it useful for SELECT performance to set an index on a field that contains only distinct values?

eg:

```<code>order_id
--------
98317490
10928343
82931376
93438473
...
</code>```

答:
Of course it is useful, as with all indexes - it is useful if you have select statements where you have this field on the WHERE clause.

Whether this field has distinct values or not doesn't really matter.

Note that if your field is marked as UNIQUE or PRIMARY KEY in the database, the database will technically already have an index for this field, so adding another index for it will not change anything.

Body:
Is it useful for SELECT performance to set an index on a field that contains only distinct values?

eg:

order_id
--------
98317490
10928343
82931376
93438473
...


问:
angular $watch is not work with d3.js
look, click the button, $scope.optionis change, but $watch is not work, can`t console.log the option value , why?

I am sorry , it is my mistake , but it still is a problem in I use width d3.js

I use d3.js append a rect into page, and I want to when I click the rect can chagne the option value, but $watch is not work, why?

```<code>angular.module('myapp',[]).controller('myCtrl', function($scope){
$scope.option = '123';
$scope.d3TreeDraw = {
    source : {
        name: 'myTree'
    },
    updata: function(){
        var _self = this;

        var tree = d3.layout.tree().nodeSize([90, 60]);

        var nodes = tree.nodes(_self.source).reverse();
        nodes.forEach(function(d) { d.y = d.depth * 90; });

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

        var node = svg.selectAll("g.node")
        .data(nodes)

        var nodeEnter = node.enter().append("g")
        .attr("class", "node")
        .style('cursor','pointer')
        .on('click', function(d){
            console.log('click'); // can console.log
            $scope.option = '456';
            console.log($scope.option) //is change
              })

        nodeEnter.append("rect")
        .attr('width',150)
        .attr('height', 30)
        .style('fill', '#000')
    }
}
$scope.d3TreeDraw.updata();

$scope.$watch('option', function(){
    console.log('change:' + $scope.option); // when option is change,can not console.log
})
})
</code>```

答:
you have a upper case letter in the function name

change this

```<code> <button ng-click="myTree.onClick()">456</button>
</code>```

to this

```<code> <button ng-click="myTree.onclick()">456</button>
</code>```

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.data = '123';
    $scope.$watch('data', function(){
        console.log($scope.data);
    })

    $scope.myTree = {

        onclick: function() {
            $scope.data = '456';
        }
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code> </code>```

 <button ng-click="myTree.onclick()">456</button>

 ```

Title: angular $watch is not work with d3.js

Body:
look, click the button, $scope.optionis change, but $watch is not work, can`t console.log the option value , why?

I am sorry , it is my mistake , but it still is a problem in I use width d3.js

I use d3.js append a rect into page, and I want to when I click the rect can chagne the option value, but $watch is not work, why?

angular.module('myapp',[]).controller('myCtrl', function($scope){
$scope.option = '123';
$scope.d3TreeDraw = {
    source : {
        name: 'myTree'
    },
    updata: function(){
        var _self = this;

        var tree = d3.layout.tree().nodeSize([90, 60]);

        var nodes = tree.nodes(_self.source).reverse();
        nodes.forEach(function(d) { d.y = d.depth * 90; });

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

        var node = svg.selectAll("g.node")
        .data(nodes)

        var nodeEnter = node.enter().append("g")
        .attr("class", "node")
        .style('cursor','pointer')
        .on('click', function(d){
            console.log('click'); // can console.log
            $scope.option = '456';
            console.log($scope.option) //is change
              })

        nodeEnter.append("rect")
        .attr('width',150)
        .attr('height', 30)
        .style('fill', '#000')
    }
}
$scope.d3TreeDraw.updata();

$scope.$watch('option', function(){
    console.log('change:' + $scope.option); // when option is change,can not console.log
})
})

Body:
you have a upper case letter in the function name

change this

 <button ng-click="myTree.onClick()">456</button>

to this

 <button ng-click="myTree.onclick()">456</button>

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.data = '123';
    $scope.$watch('data', function(){
        console.log($scope.data);
    })

    $scope.myTree = {

        onclick: function() {
            $scope.data = '456';
        }
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <button ng-click="myTree.onclick()">456</button>
</div>


问:
Checking a nested hash key
I have a hash yaml, which is sometimes like:

```<code>{"foo" => {"bar" => 10}}
</code>```

and sometimes like:

```<code>{"foo" => nil}
</code>```

I want to do a certain action depending on whether "bar" is present.

I write this code:

```<code>if yaml["foo"] && yaml["foo"].key?["bar"]
...
</code>```

I'd like to know if there's an idiomatic way to deal with that conditional, especially the first part where I have to check the existence of the parent key.

答:
Hash#dig comes in very handy for cases like yours:

```<code>hash = {"foo" => {"bar" =>  { "baz" => 10}}}
hash.dig('foo', 'bar', 'baz')
#=> 10
</code>```

Note, that if at any point of digging it returns nil, the method won't blow up but just return nil as result:

```<code>hash.dig('foo', 'baz')
#=> nil
</code>```

Title: Checking a nested hash key

Body:
I have a hash yaml, which is sometimes like:

{"foo" => {"bar" => 10}}

and sometimes like:

{"foo" => nil}

I want to do a certain action depending on whether "bar" is present.

I write this code:

if yaml["foo"] && yaml["foo"].key?["bar"]
...

I'd like to know if there's an idiomatic way to deal with that conditional, especially the first part where I have to check the existence of the parent key.

Body:
Hash#dig comes in very handy for cases like yours:

hash = {"foo" => {"bar" =>  { "baz" => 10}}}
hash.dig('foo', 'bar', 'baz')
#=> 10

Note, that if at any point of digging it returns nil, the method won't blow up but just return nil as result:

hash.dig('foo', 'baz')
#=> nil


问:
MongoDB: Retrieving an entire array from a specific document
I have set up some test data in mongoDB that has the following form:

```<code>{
    "_id" : ObjectId("579ab44c0f9f0dc3aeec42ab"),
    "name" : "Bob",
    "references" : [ 1, 2, 3, 4, 5, 6 ]
}

{
    "_id" : ObjectId("579ab7a20f9f0dc3aeec42ac"),
    "name" : "Jeff",
    "references" : [ 11, 12, 13, 14, 15 ]
}
</code>```

I want to be able to return the references array only for Bob. Currently I am able to return the complete Document for Bob with the following query:

```<code>  db.test_2.find({"name" : "Bob"}, bob).pretty()
</code>```

Basically the general question is how to return an array for a single document in a collection in MongoDB? If I could get any help for this that would be much appreciated!

答: db.test_2.find({ "name": "Bob" }, { "references": 1 });

Body:
I have set up some test data in mongoDB that has the following form:

{
    "_id" : ObjectId("579ab44c0f9f0dc3aeec42ab"),
    "name" : "Bob",
    "references" : [ 1, 2, 3, 4, 5, 6 ]
}

{
    "_id" : ObjectId("579ab7a20f9f0dc3aeec42ac"),
    "name" : "Jeff",
    "references" : [ 11, 12, 13, 14, 15 ]
}

I want to be able to return the references array only for Bob. Currently I am able to return the complete Document for Bob with the following query:

  db.test_2.find({"name" : "Bob"}, bob).pretty()

Basically the general question is how to return an array for a single document in a collection in MongoDB? If I could get any help for this that would be much appreciated!


问:
Looking to emulate the functionality of robocopy in a .NET application
Robocopy is a great command line tool for mirroring two folders. We have a requirement to wrap up the same functionality in a bigger .NET application. It's part of our archiving system for the file server which identifies which folders haven't been modified for a year and moves them to another folder location.

I know I could shell out to robocopy but it would be neater if we could do it all from within the .NET app, e.g. for error trapping.

The .NET framework has all the basics for this but I wondered if anyone knew of a 3rd party library that offered more powerful synchronisation functions? To save us re-inventing the wheel. It also needs to be robust so chances are a more well established library would fair better that our own 1st version attempt.

Thanks, Rob.

答:
Robocopy is somewhat similar to rsync. It looks like there's been a couple of attempts to either call librsync from C#, or build a C# replacement:

Technical Hurdles for Win32 rsync port

Is there any .NET API using rsync?

This looks promising (there's recent activity), but I couldn't vouch for it:

https://github.com/MatthewSteeples/rsync.net

ContentLicense: CC BY-SA 2.5


问:
Call an autocomplete function on document ready
after a long search i can't find a way to call an autocomplete function when the document is ready passing a specific variable.

So i got this function that works fine when i select element from autocomplete:

```<code>var option_row = <?php echo $option_row; ?>;

    $('input[name=\'option\']').autocomplete({
        'source': function(request, response) {
            $.ajax({
                url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(request),
                dataType: 'json',
                success: function(json) {
                    response($.map(json, function(item) {
                        return {
                            category: item['category'],
                            label: item['name'],
                            value: item['option_id'],
                            type: item['type'],
                            option_value: item['option_value']
                        }
                    }));
                }
            });
        },
        'select': function(item) {

            html  = '<div class="tab-pane" id="tab-option' + option_row + '">';
            html += '   <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
            html += '   <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';

    etc etc......
</code>```

after many research i'm thinking to switch to another possible solution...

I wish to call this directly without select item but passing a variable to the function...

i'm trying doing this:

```<code>    $(document).ready(function(e){

    var option_row = <?php echo $option_row; ?>;
    var req = 'item';
    setOptions(req);

    });

    function setOptions(req){

                $.ajax({
                    url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(req),
                    dataType: 'json',
                    success: function(json) {
                        response($.map(json, function(item) {
                            return {
                                category: item['category'],
                                label: item['name'],
                                value: item['option_id'],
                                type: item['type'],
                                option_value: item['option_value']
                            }
                        }));
                    }
                });

           'select': function(item) {

                html  = '<div class="tab-pane" id="tab-option' + option_row + '">';
                html += '   <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
                html += '   <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';

           etc, etc...

    }
</code>```

Now, i don't know what i should use instead of 'select': function(item) { to make it works.

Thanks in advance, any help is appreciated.

答:
Well, i have finally make it... it was more simple than i thought

this is the code:

```<code>$(document).ready(function(e) {
    var data = 'Adulti';
    addOptions(data);

});

var option_row = <?php echo $option_row; ?>;

function addOptions(data){

var base_url = 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(data);
var n='';
    $.ajax({

        url: base_url,

        dataType: 'json',
        success: function(json) {

                $.map(json, function(item) {

                     category = item['category'];
                        label = item['name'];
                        value = item['option_id'];
                         type = item['type'];
                 option_value = item['option_value'];

        html  = '<div class="tab-pane" id="tab-option' + option_row + '">';
        html += '   <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
        html += '   <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['name'] + '" />';
        html += '   <input type="hidden" name="product_option[' + option_row + '][option_id]" value="' + item['value'] + '" />';
        html += '   <input type="hidden" name="product_option[' + option_row + '][type]" value="' + item['type'] + '" />';

etc, etc....
</code>```

Body:
after a long search i can't find a way to call an autocomplete function when the document is ready passing a specific variable.

So i got this function that works fine when i select element from autocomplete:

var option_row = <?php echo $option_row; ?>;

    $('input[name=\'option\']').autocomplete({
        'source': function(request, response) {
            $.ajax({
                url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(request),
                dataType: 'json',
                success: function(json) {
                    response($.map(json, function(item) {
                        return {
                            category: item['category'],
                            label: item['name'],
                            value: item['option_id'],
                            type: item['type'],
                            option_value: item['option_value']
                        }
                    }));
                }
            });
        },
        'select': function(item) {

            html  = '
';
            html += '   <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
            html += '   <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';

    etc etc......

after many research i'm thinking to switch to another possible solution...

I wish to call this directly without select item but passing a variable to the function...

i'm trying doing this:

    $(document).ready(function(e){

    var option_row = <?php echo $option_row; ?>;
    var req = 'item';
    setOptions(req);

    });

    function setOptions(req){

                $.ajax({
                    url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(req),
                    dataType: 'json',
                    success: function(json) {
                        response($.map(json, function(item) {
                            return {
                                category: item['category'],
                                label: item['name'],
                                value: item['option_id'],
                                type: item['type'],
                                option_value: item['option_value']
                            }
                        }));
                    }
                });

           'select': function(item) {

                html  = '
';
                html += '   <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
                html += '   <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';

           etc, etc...

    }

Now, i don't know what i should use instead of 'select': function(item) { to make it works.

Thanks in advance, any help is appreciated.

Body:
Well, i have finally make it... it was more simple than i thought

this is the code:

$(document).ready(function(e) {
    var data = 'Adulti';
    addOptions(data);

});

var option_row = <?php echo $option_row; ?>;

function addOptions(data){

var base_url = 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(data);
var n='';
    $.ajax({

        url: base_url,

        dataType: 'json',
        success: function(json) {

                $.map(json, function(item) {

                     category = item['category'];
                        label = item['name'];
                        value = item['option_id'];
                         type = item['type'];
                 option_value = item['option_value'];

        html  = '<div class="tab-pane" id="tab-option' + option_row + '">';
        html += '   <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
        html += '   <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['name'] + '" />';
        html += '   <input type="hidden" name="product_option[' + option_row + '][option_id]" value="' + item['value'] + '" />';
        html += '   <input type="hidden" name="product_option[' + option_row + '][type]" value="' + item['type'] + '" />';

etc, etc....


问:
Filtering a MultiIndex Pandas DataFrame
I have a MultiIndex Pandas DataFrame that looks like the following:

```<code>import pandas as pd
import numpy as np

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 99, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)
</code>```

I want to filter the df for any rows where at least one of the Samples (Sample1 or Sample2 in this case) has a DP >= 50 & GQ < 4. Under these conditions all rows should be filtered out except the first row.

I have no idea where to start with this and would appreciate some help.

EDIT:

I arrived at a solution thanks to the help of jezrael's post. The code is as follows:

```<code>genotype = df.ix[:,3:]

DP = genotype.xs('DP', axis=1, level=1)
GQ = genotype.xs('GQ', axis=1, level=1)

conditions = (DP.ge(50) & GQ.le(4)).T.any()
df = df[conditions]

return df
</code>```

答:
I think you can use:

filter Samples columns

select xs DP and HQ subsets and compare with ge and lt

logical and (&) and get at least one True by any

get first True by idxmax and select by loc

```<code>#data in sample change for matching (first 99 in HQ in Sample1 was changed to 3)

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 3, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)
print (df)
  INFO       Sample1                        Sample2
    AC DEPTH      GT      AD   DP  GQ    AB      GT      AD   DP  GQ    AB
0   12   100     0/1  120,60  180   5  0.50     0/1   200,2  202  99  0.01
1   23   200     0/1  200,20   60   3  0.10     0/1  200,50  250  99  0.40
2   40    40     0/1   200,2  202  99  0.01     0/1   200,2  202  99  0.01
</code>```

```<code>df1 = df.filter(like='Sample')
df = df.loc[[(df1.xs('DP', axis=1, level=1).ge(50) &
              df1.xs('GQ', axis=1, level=1).lt(4)).any(1).idxmax()]]
print (df)
  INFO       Sample1                     Sample2
    AC DEPTH      GT      AD  DP GQ   AB      GT      AD   DP  GQ   AB
1   23   200     0/1  200,20  60  3  0.1     0/1  200,50  250  99  0.4
</code>```

EDIT:

If need return all rows by condition, remove loc and idmax:

```<code>df1 = df.filter(like='Sample')
#changed condition to lt(10) (<10)
df = df[(df1.xs('DP', axis=1, level=1).ge(50) & df1.xs('GQ', axis=1, level=1).lt(10)).any(1)]
print (df)
  INFO       Sample1                      Sample2
    AC DEPTH      GT      AD   DP GQ   AB      GT      AD   DP  GQ    AB
0   12   100     0/1  120,60  180  5  0.5     0/1   200,2  202  99  0.01
1   23   200     0/1  200,20   60  3  0.1     0/1  200,50  250  99  0.40
</code>```

Title: Filtering a MultiIndex Pandas DataFrame

Body:
I have a MultiIndex Pandas DataFrame that looks like the following:

import pandas as pd
import numpy as np

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 99, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)

I want to filter the df for any rows where at least one of the Samples (Sample1 or Sample2 in this case) has a DP >= 50 & GQ < 4. Under these conditions all rows should be filtered out except the first row.

I have no idea where to start with this and would appreciate some help.

EDIT:

I arrived at a solution thanks to the help of jezrael's post. The code is as follows:

genotype = df.ix[:,3:]

DP = genotype.xs('DP', axis=1, level=1)
GQ = genotype.xs('GQ', axis=1, level=1)

conditions = (DP.ge(50) & GQ.le(4)).T.any()
df = df[conditions]

return df

Body:
I think you can use:

filter Samples columns

select xs DP and HQ subsets and compare with ge and lt

logical and (&) and get at least one True by any

get first True by idxmax and select by loc

#data in sample change for matching (first 99 in HQ in Sample1 was changed to 3)

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 3, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)
print (df)
  INFO       Sample1                        Sample2
    AC DEPTH      GT      AD   DP  GQ    AB      GT      AD   DP  GQ    AB
0   12   100     0/1  120,60  180   5  0.50     0/1   200,2  202  99  0.01
1   23   200     0/1  200,20   60   3  0.10     0/1  200,50  250  99  0.40
2   40    40     0/1   200,2  202  99  0.01     0/1   200,2  202  99  0.01

df1 = df.filter(like='Sample')
df = df.loc[[(df1.xs('DP', axis=1, level=1).ge(50) &
              df1.xs('GQ', axis=1, level=1).lt(4)).any(1).idxmax()]]
print (df)
  INFO       Sample1                     Sample2
    AC DEPTH      GT      AD  DP GQ   AB      GT      AD   DP  GQ   AB
1   23   200     0/1  200,20  60  3  0.1     0/1  200,50  250  99  0.4

EDIT:

If need return all rows by condition, remove loc and idmax:

df1 = df.filter(like='Sample')
#changed condition to lt(10) (<10)
df = df[(df1.xs('DP', axis=1, level=1).ge(50) & df1.xs('GQ', axis=1, level=1).lt(10)).any(1)]
print (df)
  INFO       Sample1                      Sample2
    AC DEPTH      GT      AD   DP GQ   AB      GT      AD   DP  GQ    AB
0   12   100     0/1  120,60  180  5  0.5     0/1   200,2  202  99  0.01
1   23   200     0/1  200,20   60  3  0.1     0/1  200,50  250  99  0.40


问:
sql query using checkbox value
I have a html form where there are two Input fields
say Caste (options are SC, ST and OBC) and Direction (options are north, south, east and west). Users will choose the options using check box.

```<code><input name="ct" type="checkbox"  value="SC">SC
<input name="ct" type="checkbox"  value="ST">ST
<input name="ct" type="checkbox"  value="OBC">OBC

<input name="dr" type="checkbox"  value="N">North
<input name="dr" type="checkbox"  value="S">south
<input name="dr" type="checkbox"  value="E">East
<input name="dr" type="checkbox"  value="W">West
</code>```

I have also a database (name : PEOPLE) with column name Caste , Direction etc.

Now I want to run a sql query based on user's selection. For example

```<code>mysql_query("select * from PEOPLE where Caste='option/options selected by user' and Direction= 'option/options selected by user' ")
</code>```

If user choose one option from each field then it is not a problem for me,

```<code>mysql_query("select * from PEOPLE where Caste='$_POST[ct]' and Direction= '$_POST[dr]' ")
</code>```

but if they use multiple options , then how should I proceed.

答:
You can use WHERE IN</p>

```<code>$caste_string = implode('","', $_GET['ct']);
$caste_string = '"'.$caste.'"';

$dir_string = implode('","', $_GET['dr']);
$dir_string = '"'.$caste.'"';

mysql_query("select * from PEOPLE WHERE Caste IN ($caste_string) AND Direction IN ($dir_string)")
</code>```

Title: sql query using checkbox value

Body:
I have a html form where there are two Input fields
say Caste (options are SC, ST and OBC) and Direction (options are north, south, east and west). Users will choose the options using check box.

<input name="ct" type="checkbox"  value="SC">SC
<input name="ct" type="checkbox"  value="ST">ST
<input name="ct" type="checkbox"  value="OBC">OBC

<input name="dr" type="checkbox"  value="N">North
<input name="dr" type="checkbox"  value="S">south
<input name="dr" type="checkbox"  value="E">East
<input name="dr" type="checkbox"  value="W">West

I have also a database (name : PEOPLE) with column name Caste , Direction etc.

Now I want to run a sql query based on user's selection. For example

mysql_query("select * from PEOPLE where Caste='option/options selected by user' and Direction= 'option/options selected by user' ")

If user choose one option from each field then it is not a problem for me,

mysql_query("select * from PEOPLE where Caste='$_POST[ct]' and Direction= '$_POST[dr]' ")

but if they use multiple options , then how should I proceed.

Body:
You can use WHERE IN

$caste_string = implode('","', $_GET['ct']);
$caste_string = '"'.$caste.'"';

$dir_string = implode('","', $_GET['dr']);
$dir_string = '"'.$caste.'"';

mysql_query("select * from PEOPLE WHERE Caste IN ($caste_string) AND Direction IN ($dir_string)")


问:
Fix the first and the second column of dynamic table generated according to JSON file
Define empty table in HTML file, and append thead and tbody in js file, fill the td content in js file according to data read from JSON file.

Question: How to fix the 1st and 2nd column of this dynamic table?

答:
It is just an example. You can try this.</p>

```<code>var myList = [
    { "name": "abc", "age": 50 },
    { "age": "25", "hobby": "swimming" },
    { "name": "xyz", "hobby": "programming" }
];

function buildHtmlTable(selector) {
    var columns = addAllColumnHeaders(myList, selector);
    for (var i = 0; i < myList.length; i++) {
        var row$ = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = myList[i][columns[colIndex]];
            if (cellValue == null) cellValue = "";
            row$.append($('<td/>').html(cellValue));
        }
        $(selector).append(row$);
    }
}

function addAllColumnHeaders(myList, selector) {
    var columnSet = [];
    var headerTr$ = $('<tr/>');
    for (var i = 0; i < myList.length; i++) {
        var rowHash = myList[i];
        for (var key in rowHash) {
            if ($.inArray(key, columnSet) == -1) {
                columnSet.push(key);
                headerTr$.append($('<th/>').html(key));
            }
        }
    }
    $(selector).append(headerTr$);
    return columnSet;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
    <table id="excelDataTable" border="1">
    </table>
</body>
</code>```

Body:
It is just an example. You can try this.

var myList = [
    { "name": "abc", "age": 50 },
    { "age": "25", "hobby": "swimming" },
    { "name": "xyz", "hobby": "programming" }
];

function buildHtmlTable(selector) {
    var columns = addAllColumnHeaders(myList, selector);
    for (var i = 0; i < myList.length; i++) {
        var row$ = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = myList[i][columns[colIndex]];
            if (cellValue == null) cellValue = "";
            row$.append($('<td/>').html(cellValue));
        }
        $(selector).append(row$);
    }
}

function addAllColumnHeaders(myList, selector) {
    var columnSet = [];
    var headerTr$ = $('<tr/>');
    for (var i = 0; i < myList.length; i++) {
        var rowHash = myList[i];
        for (var key in rowHash) {
            if ($.inArray(key, columnSet) == -1) {
                columnSet.push(key);
                headerTr$.append($('<th/>').html(key));
            }
        }
    }
    $(selector).append(headerTr$);
    return columnSet;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
    <table id="excelDataTable" border="1">
    </table>
</body>


问:
How do i create a site that uses menus/radio buttons to extract data from MySQL Database?
I've managed to construct a webpage template that has all the elements for a home page but I want to use the data in my database to then submit to produce results coming out once submitted.

When I choose the menu (which has successfully come through from the database) when I click submit and have a second php page to make this submit work, I do not get any results from the database or at best showing what I have selected.

What code do I need to produce results on submit page that would hold all the data selected?

I really am a beginner at this and using PHP, HTML, and Dreamweaver as my builder.

答:
At first you have to understand HTML form methods and how to access form data using PHP.

For getting the values of the select box you can go to this link.

Get select box value using $_POST


问:
How can I cancel an asynchronous delegate in C# 3.5?
I have searched google up and down but I can not find nearly any proper information about that topic.

What I wanna do is this:

User types a single search-string in a textbox.

I wait 0.5 s then I start to BeginInvoke my delegate pointing to a search method.

If the user types again a char I want to cancel the Search and begin a new search with the new string typed.

The UI-Thread must not be blocked!

How can I do that using C# 3.5 ?

UPDATE:

View:

```<code>private void OnTextChanged(...)
{
   if (SearchFormatEvent != null)
   {
       ICollection<object> collection = SearchFormatEvent("MySearchString");
       // Do stuff on the returned collection
    }
}
</code>```

SearchProvider:

```<code>// This is the delegate invoked for the async search taking the searchstring typed by the user
    public delegate ICollection<object> SearchInputTextStrategy<T>(string param);

    public class SearchProvider : ISearchProvider
    {
        private ITextView _view;
        private SearchInputTextStrategy<object> searchInputDelegate;

        public SearchProvider(ITextView view)
        {
            _view = view;
            _view.SearchFormatEvent += new ConstructSearchFormatDelegate(CostructSearchFormat);
        }

        private string SearchFormat(string param)
        {
            // compute string

            return string.Empty; //...
        }

        public ICollection<object> CostructSearchFormat(string param)
        {
            var searchfilter = SearchFormat(param);

             IAsyncResult pendingOperation = searchInputDelegate.BeginInvoke("searchfilter",null,null);

            // How can I cancel the Async delegate ?

            ICollection<object> result = searchInputDelegate.EndInvoke(pendingOperation);

            return result;
        }
    }
</code>```

答: Switch  to BackGroudWorker , is supports all you need ( NoUI Blocking , Cancellation ect, Progress Reporting..)</p>

Body:
I have searched google up and down but I can not find nearly any proper information about that topic.

What I wanna do is this:

User types a single search-string in a textbox.

I wait 0.5 s then I start to BeginInvoke my delegate pointing to a search method.

If the user types again a char I want to cancel the Search and begin a new search with the new string typed.

The UI-Thread must not be blocked!

How can I do that using C# 3.5 ?

UPDATE:

View:

private void OnTextChanged(...)
{
   if (SearchFormatEvent != null)
   {
       ICollection<object> collection = SearchFormatEvent("MySearchString");
       // Do stuff on the returned collection
    }
}

SearchProvider:

// This is the delegate invoked for the async search taking the searchstring typed by the user
    public delegate ICollection<object> SearchInputTextStrategy<T>(string param);

    public class SearchProvider : ISearchProvider
    {
        private ITextView _view;
        private SearchInputTextStrategy<object> searchInputDelegate;

        public SearchProvider(ITextView view)
        {
            _view = view;
            _view.SearchFormatEvent += new ConstructSearchFormatDelegate(CostructSearchFormat);
        }

        private string SearchFormat(string param)
        {
            // compute string

            return string.Empty; //...
        }

        public ICollection<object> CostructSearchFormat(string param)
        {
            var searchfilter = SearchFormat(param);

             IAsyncResult pendingOperation = searchInputDelegate.BeginInvoke("searchfilter",null,null);

            // How can I cancel the Async delegate ?

            ICollection<object> result = searchInputDelegate.EndInvoke(pendingOperation);

            return result;
        }
    }