问:
How to pass byte data from C# to Servlet in Java
I am trying to pass byte data from C# to java servlet . The code is as follows :

```<code>byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + data;
jsonparser = new JSONParser("http://10.11.201.31:8085/FingerEnrollVerify/EnrolledFingerVerify", "POST", passingData );
</code>```

The definition of JSONParser class is as follows :

```<code>public JSONParser(string url)
        {
            // Create a request using a URL that can receive a post.
            request = WebRequest.Create(url);
        }
        public JSONParser(string url, string method) : this(url)
        {
            if (method.Equals("GET") || method.Equals("POST"))
            {
                // Set the Method property of the request to POST.
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
        }
        public JSONParser(string url, string method, string data) : this(url, method)
        {
            // Create POST data and convert it to a byte array.
            string postData = data;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
        }
</code>```

Then in java servlet I am trying to get this byte data . The code is as follows :

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("Finger Enroll Verify");

        String customerNumber = request.getParameter("cust_no");
        System.out.println("cust_no is "+customerNumber);

        String serial = request.getParameter("serial");
        int serial_no = Integer.parseInt(serial);
        System.out.println("Serial_no is "+serial_no);

        InputStream inputStream = request.getInputStream();
        byte[] fingerbytes = IOUtils.toByteArray(inputStream);
        System.out.println("fingerbytes length: "+fingerbytes.length);
}
</code>```

But I am getting "fingerbytes length: 0" . Why ? How can I pass byte data from C# to Java servlet ? Please help me .

答:
data is an array of Bytes. So, generate a string from this array and send it to servlet.

```<code>byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + System.Text.Encoding.Default.GetString(data);
</code>```

And in the servlet, receive temp from post params to a string and do getBytes() to get a byte array. Code is not tested. Just wanted to share the idea.

Body:
I am trying to pass byte data from C# to java servlet . The code is as follows :

byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + data;
jsonparser = new JSONParser("http://10.11.201.31:8085/FingerEnrollVerify/EnrolledFingerVerify", "POST", passingData );

The definition of JSONParser class is as follows :

public JSONParser(string url)
        {
            // Create a request using a URL that can receive a post.
            request = WebRequest.Create(url);
        }
        public JSONParser(string url, string method) : this(url)
        {
            if (method.Equals("GET") || method.Equals("POST"))
            {
                // Set the Method property of the request to POST.
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
        }
        public JSONParser(string url, string method, string data) : this(url, method)
        {
            // Create POST data and convert it to a byte array.
            string postData = data;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
        }

Then in java servlet I am trying to get this byte data . The code is as follows :

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("Finger Enroll Verify");

        String customerNumber = request.getParameter("cust_no");
        System.out.println("cust_no is "+customerNumber);

        String serial = request.getParameter("serial");
        int serial_no = Integer.parseInt(serial);
        System.out.println("Serial_no is "+serial_no);

        InputStream inputStream = request.getInputStream();
        byte[] fingerbytes = IOUtils.toByteArray(inputStream);
        System.out.println("fingerbytes length: "+fingerbytes.length);
}

But I am getting "fingerbytes length: 0" . Why ? How can I pass byte data from C# to Java servlet ? Please help me .

Body:
data is an array of Bytes. So, generate a string from this array and send it to servlet.

byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + System.Text.Encoding.Default.GetString(data);

And in the servlet, receive temp from post params to a string and do getBytes() to get a byte array. Code is not tested. Just wanted to share the idea.


来源: stackexchange

问:
Changing View Background Color with Soft Animation Infinitely Android
I want to create a color changing background animation that run continuously in my view, and I've been able to create the color changing animation with this code.

```<code>int prevColor = getRandomColor();
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), prevColor, getRandomColor(prevColor));
colorAnimation.setRepeatCount(ValueAnimator.INFINITE);
colorAnimation.setDuration(transitionTime); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
        backgroundBase.setBackgroundColor((int) animator.getAnimatedValue());
    }
});
colorAnimation.start();
</code>```

It run smoothly, but...

When the animation end, it abruptly goes back changing color to the first one without the soft animation like the first time

Then, what I would like to do is when the animation finishes, I want the animation to get new Random Color from my Color List so that the color constantly changing from time to time (not just reversing back and forth)

I cannot find setAnimationListener in the colorAnimation, so I cannot use the override method onAnimationEnd

What should I do to achieve that?

答:
set fillAfter to true:

```<code>colorAnimation.setFillAfter(true);
</code>```

Save the nextColor to a prevColor variable so that you can start the animation from there. Call the method that contains the ValueAnimator from the onAnimationEnd. Don't think you need setRepeatCount() for that.

you can use addListener:

```<code>colorAnimation.addListener(new Animation.AnimatorListener(){....})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create a color changing background animation that run continuously in my view, and I've been able to create the color changing animation with this code.

int prevColor = getRandomColor();
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), prevColor, getRandomColor(prevColor));
colorAnimation.setRepeatCount(ValueAnimator.INFINITE);
colorAnimation.setDuration(transitionTime); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
        backgroundBase.setBackgroundColor((int) animator.getAnimatedValue());
    }
});
colorAnimation.start();

It run smoothly, but...

When the animation end, it abruptly goes back changing color to the first one without the soft animation like the first time

Then, what I would like to do is when the animation finishes, I want the animation to get new Random Color from my Color List so that the color constantly changing from time to time (not just reversing back and forth)

I cannot find setAnimationListener in the colorAnimation, so I cannot use the override method onAnimationEnd

What should I do to achieve that?

Body:
set fillAfter to true:

colorAnimation.setFillAfter(true);

Save the nextColor to a prevColor variable so that you can start the animation from there. Call the method that contains the ValueAnimator from the onAnimationEnd. Don't think you need setRepeatCount() for that.

you can use addListener:

colorAnimation.addListener(new Animation.AnimatorListener(){....})


问:
! operator in do while loop
I'm just doing a tutorial on insertion sorting in C, and I'm struggling to understand the way the ! operator is used as the condition for a do while loop.

The condition is just while (!done) but I don't understand how it knows what is not supposed to be equal to the variable done. Something like while (done==0) would make more sense to me.

I'm only just starting to code so sorry if the answer is really obvious! I tried googling it but I found it hard to express the problem...

The code is as follows:

```<code>void insertionSortArray (int arr[])
{
    for(int i = 1; i < SIZE; i++)
    {
        int value = arr[i];
        int j = i -1;
        int done = 0;
        do
        {
            if (arr[j]>value)
            {
                arr [j+1] = arr[j];
                j - -;
                if (j<0)
                done = 1;
            }

            else
                done = 1;

        } while (!done);

        arr [j+1] = value;
    }
}
</code>```

Thanks!!

答:
They're exactly the same thing. !done and done == 0 are interchangeable. The thing about C is: it didn't have a "true" boolean type for a long time. Booleans were only introduced in C99.

All zero values are considered false, other values are true. that's why !done is true, for as long as done == 0 (done is 0 -> false, !false -> true). ! is the logical NOT operator, as always, and does what it does: negates whatever comes after. Therefore done = 0 => done is false, !done -> the opposite of false, being true.

If you find done == 0 easier to read, then by all means write it like that. Although, it is more common to see the shorter version.

False/true checks that are Very common:

```<code>type *foo = malloc(123 * sizeof *foo);
if (!foo)
    exit(1); // failed to alloc memory

void my_function(int *ptr, size_t size)
{
    if (!ptr)
        return; // a NULL pointer was passed
    // ...
}
</code>```

TL;DR

Because both statements are interchangeable, write what you find makes the most sense. Perhaps reading both statements aloud (although it may seem silly) will make you change your mind:

```<code>while done equals zero
//vs
while not done
</code>```

Which of the two sentences makes most sense now?

Title: ! operator in do while loop

Body:
I'm just doing a tutorial on insertion sorting in C, and I'm struggling to understand the way the ! operator is used as the condition for a do while loop.

The condition is just while (!done) but I don't understand how it knows what is not supposed to be equal to the variable done. Something like while (done==0) would make more sense to me.

I'm only just starting to code so sorry if the answer is really obvious! I tried googling it but I found it hard to express the problem...

The code is as follows:

void insertionSortArray (int arr[])
{
    for(int i = 1; i < SIZE; i++)
    {
        int value = arr[i];
        int j = i -1;
        int done = 0;
        do
        {
            if (arr[j]>value)
            {
                arr [j+1] = arr[j];
                j - -;
                if (j<0)
                done = 1;
            }

            else
                done = 1;

        } while (!done);

        arr [j+1] = value;
    }
}

Thanks!!

Body:
They're exactly the same thing. !done and done == 0 are interchangeable. The thing about C is: it didn't have a "true" boolean type for a long time. Booleans were only introduced in C99.

All zero values are considered false, other values are true. that's why !done is true, for as long as done == 0 (done is 0 -> false, !false -> true). ! is the logical NOT operator, as always, and does what it does: negates whatever comes after. Therefore done = 0 => done is false, !done -> the opposite of false, being true.

If you find done == 0 easier to read, then by all means write it like that. Although, it is more common to see the shorter version.

False/true checks that are Very common:

type *foo = malloc(123 * sizeof *foo);
if (!foo)
    exit(1); // failed to alloc memory

void my_function(int *ptr, size_t size)
{
    if (!ptr)
        return; // a NULL pointer was passed
    // ...
}

TL;DR

Because both statements are interchangeable, write what you find makes the most sense. Perhaps reading both statements aloud (although it may seem silly) will make you change your mind:

while done equals zero
//vs
while not done

Which of the two sentences makes most sense now?


问:
How to get a div to float above a jQuery UI dialog?
I have a jQuery dialog box with a form and I'd like for an autocomplete box attached to one of the form elements to float above the dialog box (so that if the list goes beyond the end of the dialog box, it won't get cut off).  I have the following CSS elements applied to the autocomplete div:

```<code>background:none repeat scroll 0 0 white;
float:left;
position:absolute;
z-index:9999;
</code>```

It still will create a scrollbar in the dialog box. What's the deal? I see the dialog box is z-index:1004; so I don't know why mine's not going ontop of it. Is what I'm trying to accomplish even possible?

答: The reason it happens is because your element is a child of the dialog's container.  z-index won't do what you want.  The element would need to be outside the dialog and positioned accordingly.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a jQuery dialog box with a form and I'd like for an autocomplete box attached to one of the form elements to float above the dialog box (so that if the list goes beyond the end of the dialog box, it won't get cut off).  I have the following CSS elements applied to the autocomplete div:

background:none repeat scroll 0 0 white;
float:left;
position:absolute;
z-index:9999;

It still will create a scrollbar in the dialog box. What's the deal? I see the dialog box is z-index:1004; so I don't know why mine's not going ontop of it. Is what I'm trying to accomplish even possible?


问:
No Java virtual machine was found (Eclipse)
When trying to run Eclipse Kepler (for the first time), I get the following error:

I am aware that this issue has been solved many times before. However, I have changed eclipse.ini to say -vm C:\Program Files (x86)\Java\jdk1.6.0_21\bin\javaw.exe but to no avail. The same error always comes up.

===UPDATE===
I added a line break after -vm and now I get this dialog box:

and the eclipse.ini file:

```<code>-vm
C:\Program Files (x86)\Java\jdk1.7.0_51\jre\bin\javaw.exe
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx512m
</code>```

答:
Two ways to work around this .

Recommended way : In your eclipse.ini file make sure you are pointing -vm to your jdk installation. More on this here .
Pass in the vm flag from command line. http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#Find_the_JVM

Note : Eclipse DOES NOT consult the JAVA_HOME environment variable.

Body:
When trying to run Eclipse Kepler (for the first time), I get the following error:

I am aware that this issue has been solved many times before. However, I have changed eclipse.ini to say -vm C:\Program Files (x86)\Java\jdk1.6.0_21\bin\javaw.exe but to no avail. The same error always comes up.

===UPDATE===
I added a line break after -vm and now I get this dialog box:

and the eclipse.ini file:

-vm
C:\Program Files (x86)\Java\jdk1.7.0_51\jre\bin\javaw.exe
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx512m


问:
Scrapy Middleware to ignore URL and prevent crawling
I have a middleware that will [raise IgnoreRequests()] if url contains "https".

```<code>class MiddlewareSkipHTTPS(object):
    def process_response(self, request, response, spider):
        if (response.url.find("https") > -1):
            raise IgnoreRequest()
        else:
            return response
</code>```

Is there a way to completely prevent scrapy from performing a GET request to the HTTPS url? I get the same values for response_bytes/response_count without [IgnoreRequests()] and with it my code snippet. I'm looking for zero values and skip crawling the url. I don't want scrapy to crawl/download all the bytes from the https page, just move on to the next url.

Notes: MUST be a middleware, do not want to use rules embedded in spider. Have hundreds of spiders and want to consolidate the logic.

答:
In your settings doing this should work fine</p>

```<code>DOWNLOAD_HANDLERS = {
    'https': None
}
</code>```

Body:
I have a middleware that will [raise IgnoreRequests()] if url contains "https".

class MiddlewareSkipHTTPS(object):
    def process_response(self, request, response, spider):
        if (response.url.find("https") > -1):
            raise IgnoreRequest()
        else:
            return response

Is there a way to completely prevent scrapy from performing a GET request to the HTTPS url? I get the same values for response_bytes/response_count without [IgnoreRequests()] and with it my code snippet. I'm looking for zero values and skip crawling the url. I don't want scrapy to crawl/download all the bytes from the https page, just move on to the next url.

Notes: MUST be a middleware, do not want to use rules embedded in spider. Have hundreds of spiders and want to consolidate the logic.

Body:
In your settings doing this should work fine

DOWNLOAD_HANDLERS = {
    'https': None
}


问:
How to generalize this C# code?
I have this code which initializes winforms textboxes.

```<code>txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];
</code>```

I'd like to generalize it like this:

```<code>for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}
</code>```

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

答:
Since it's WinForms you can use Name property of your TextBox.

```<code>for( int i = 0; i < steps.Length; i++ )
{
    TextBox tBox = this.Controls.OfType<TextBox>().FirstOrDefault(t => t.Name == "txt" + i);
    if(tBox == null) break;

    tBox.Text = steps[i];
}
</code>```

Name property of your Control corresponds with the variable name you use meaning that if you call your TextBox as txt0 it's name is "txt0" which makes it really easy to retrieve from it's parent Control using this name.

Title: How to generalize this C# code?

Body:
I have this code which initializes winforms textboxes.

txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];

I'd like to generalize it like this:

for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

Body:
Since it's WinForms you can use Name property of your TextBox.

for( int i = 0; i < steps.Length; i++ )
{
    TextBox tBox = this.Controls.OfType<TextBox>().FirstOrDefault(t => t.Name == "txt" + i);
    if(tBox == null) break;

    tBox.Text = steps[i];
}

Name property of your Control corresponds with the variable name you use meaning that if you call your TextBox as txt0 it's name is "txt0" which makes it really easy to retrieve from it's parent Control using this name.


问:
Data input for K means clustering with Scipy, Python?
I have a point dataset with two attributes and I would like to cluster these points based on the attribute values. I want to use K means clustering but I am unsure on how my input data should look like when using Scipy's implementation. </p>

<p>For example should I make a numpy array with each row containing: FID, attribute 1, attribute 2, x-coord, y-coord, or an array of just the attribute values? The attributes are integers and floats. </p>

答:
Each row in your data should be descrete observations and columns should correspond to features or dimensions of your data. For your case: FID, attribute 1, attribute 2, x-coord, y-coord should be on columns and each row should represent observations at different time steps.

```<code>from scipy.cluster.vq import kmeans,vq
nbStates = 4
Centers, _ = kmeans(Data, nbStates)
Data_id, _ = vq(Data, Centers)
</code>```

where Data should be Nx5 matrix where 5 columns should correspond to your 5 features FID, attribute 1, attribute 2, x-coord, y-coord, and N rows corresponding to N observations. In other words reshape your FID data array as column vector and same for other features and horizontally concatenate them and put it as an argument for kmeans function. nbStates represents number of clusters which you expect to see, it should be set up beforehand. What you will get as a result is Centers which is NxM matrix where N corresponds to clusters and M corresponds to number of features in your data. Data_id matrix is a column vector which represents the labels of your data points corresponding to each cluster. It is Nx1 matrix where N is a number of data points.

Body:
I have a point dataset with two attributes and I would like to cluster these points based on the attribute values. I want to use K means clustering but I am unsure on how my input data should look like when using Scipy's implementation.

For example should I make a numpy array with each row containing: FID, attribute 1, attribute 2, x-coord, y-coord, or an array of just the attribute values? The attributes are integers and floats.

Body:
Each row in your data should be descrete observations and columns should correspond to features or dimensions of your data. For your case: FID, attribute 1, attribute 2, x-coord, y-coord should be on columns and each row should represent observations at different time steps.

from scipy.cluster.vq import kmeans,vq
nbStates = 4
Centers, _ = kmeans(Data, nbStates)
Data_id, _ = vq(Data, Centers)

where Data should be Nx5 matrix where 5 columns should correspond to your 5 features FID, attribute 1, attribute 2, x-coord, y-coord, and N rows corresponding to N observations. In other words reshape your FID data array as column vector and same for other features and horizontally concatenate them and put it as an argument for kmeans function. nbStates represents number of clusters which you expect to see, it should be set up beforehand. What you will get as a result is Centers which is NxM matrix where N corresponds to clusters and M corresponds to number of features in your data. Data_id matrix is a column vector which represents the labels of your data points corresponding to each cluster. It is Nx1 matrix where N is a number of data points.


问:
rabbitmqctl Error: unable to connect to node rabbit@myserver nodedown
I am running RabbitMQ v3.3.5 with Erlang OTP 17.1 on Windows 2008 R2.  My Dev and QA environments are stand-alone.  My staging and production environments are clustered.

I am finding this one problem happening often where the RabbitMQ service is running, the RabbitMQ management console is seeing everything, but when I try running rabbitmqctl from the command line it fails with an error saying that the node is down (tried locally and on a remote server).

This problem is resolved if I restart the Windows service.

I see no error message in the RabbitMQ error log.  The last message indicated that the node was up.

Below is an example output of the issue that I recently experienced on node 2 of our staging windows cluster:

```<code>PS C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.5\sbin> .\rabbitmqctl.bat status
Status of node rabbit@MYSERVER2 ...
Error: unable to connect to node rabbit@MYSERVER2: nodedown

DIAGNOSTICS
===========

attempted to contact: [rabbit@MYSERVER2]

rabbit@MYSERVER2:
  * connected to epmd (port 4369) on MYSERVER2
  * epmd reports: node 'rabbit' not running at all
                  no other nodes on MYSERVER2
  * suggestion: start the node

current node details:
- node name: rabbitmqctl2199771@MYSERVER2
- home dir: C:\Users\RabbitMQ
- cookie hash: mn6OaTX9mS4DnZaiOzg8pA==
</code>```

at this point I restart the RabbitMQ service and then try again

```<code>PS C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.5\sbin> .\rabbitmqctl.bat status
Status of node rabbit@MYSERVER2...
[{pid,3784},
 {running_applications,
     [{rabbitmq_management_agent,"RabbitMQ Management Agent","3.3.5"},
      {rabbit,"RabbitMQ","3.3.5"},
      {os_mon,"CPO  CXC 138 46","2.2.15"},
      {mnesia,"MNESIA  CXC 138 12","4.12.1"},
      {xmerl,"XML parser","1.3.7"},
      {sasl,"SASL  CXC 138 11","2.4"},
      {stdlib,"ERTS  CXC 138 10","2.1"},
      {kernel,"ERTS  CXC 138 10","3.0.1"}]},
 {os,{win32,nt}},
 {erlang_version,
     "Erlang/OTP 17 [erts-6.1] [64-bit] [smp:4:4] [async-threads:30]\n"},
 {memory,
     [{total,35960208},
      {connection_procs,2704},
      {queue_procs,5408},
      {plugins,111936},
      {other_proc,13695792},
      {mnesia,102296},
      {mgmt_db,0},
      {msg_index,21816},
      {other_ets,884704},
      {binary,25776},
      {code,16672826},
      {atom,602729},
      {other_system,3834221}]},
 {alarms,[]},
 {listeners,[{clustering,25672,"::"},{amqp,5672,"::"},{amqp,5672,"0.0.0.0"}]},
 {vm_memory_high_watermark,0.4},
 {vm_memory_limit,3435787059},
 {disk_free_limit,50000000},
 {disk_free,74911649792},
 {file_descriptors,
     [{total_limit,8092},
      {total_used,4},
      {sockets_limit,7280},
      {sockets_used,2}]},
 {processes,[{limit,1048576},{used,139}]},
 {run_queue,0},
 {uptime,5}]
...done.
</code>```

Any idea as to what causes this and how to automatically detect the situation?

Is this specifically a problem with running RabbitMQ on Windows?

答: If you are using linux try to change permission of /var/lib/rabbitmq/mnesia folder.</p>

Body:
I am running RabbitMQ v3.3.5 with Erlang OTP 17.1 on Windows 2008 R2.  My Dev and QA environments are stand-alone.  My staging and production environments are clustered.

I am finding this one problem happening often where the RabbitMQ service is running, the RabbitMQ management console is seeing everything, but when I try running rabbitmqctl from the command line it fails with an error saying that the node is down (tried locally and on a remote server).

This problem is resolved if I restart the Windows service.

I see no error message in the RabbitMQ error log.  The last message indicated that the node was up.

Below is an example output of the issue that I recently experienced on node 2 of our staging windows cluster:

PS C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.5\sbin> .\rabbitmqctl.bat status
Status of node rabbit@MYSERVER2 ...
Error: unable to connect to node rabbit@MYSERVER2: nodedown

DIAGNOSTICS
===========

attempted to contact: [rabbit@MYSERVER2]

rabbit@MYSERVER2:
  * connected to epmd (port 4369) on MYSERVER2
  * epmd reports: node 'rabbit' not running at all
                  no other nodes on MYSERVER2
  * suggestion: start the node

current node details:
- node name: rabbitmqctl2199771@MYSERVER2
- home dir: C:\Users\RabbitMQ
- cookie hash: mn6OaTX9mS4DnZaiOzg8pA==

at this point I restart the RabbitMQ service and then try again

PS C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.5\sbin> .\rabbitmqctl.bat status
Status of node rabbit@MYSERVER2...
[{pid,3784},
 {running_applications,
     [{rabbitmq_management_agent,"RabbitMQ Management Agent","3.3.5"},
      {rabbit,"RabbitMQ","3.3.5"},
      {os_mon,"CPO  CXC 138 46","2.2.15"},
      {mnesia,"MNESIA  CXC 138 12","4.12.1"},
      {xmerl,"XML parser","1.3.7"},
      {sasl,"SASL  CXC 138 11","2.4"},
      {stdlib,"ERTS  CXC 138 10","2.1"},
      {kernel,"ERTS  CXC 138 10","3.0.1"}]},
 {os,{win32,nt}},
 {erlang_version,
     "Erlang/OTP 17 [erts-6.1] [64-bit] [smp:4:4] [async-threads:30]\n"},
 {memory,
     [{total,35960208},
      {connection_procs,2704},
      {queue_procs,5408},
      {plugins,111936},
      {other_proc,13695792},
      {mnesia,102296},
      {mgmt_db,0},
      {msg_index,21816},
      {other_ets,884704},
      {binary,25776},
      {code,16672826},
      {atom,602729},
      {other_system,3834221}]},
 {alarms,[]},
 {listeners,[{clustering,25672,"::"},{amqp,5672,"::"},{amqp,5672,"0.0.0.0"}]},
 {vm_memory_high_watermark,0.4},
 {vm_memory_limit,3435787059},
 {disk_free_limit,50000000},
 {disk_free,74911649792},
 {file_descriptors,
     [{total_limit,8092},
      {total_used,4},
      {sockets_limit,7280},
      {sockets_used,2}]},
 {processes,[{limit,1048576},{used,139}]},
 {run_queue,0},
 {uptime,5}]
...done.

Any idea as to what causes this and how to automatically detect the situation?

Is this specifically a problem with running RabbitMQ on Windows?


答:
To complete a single language, you can use a left join

```<code>insert into ps_feature_lang
select  f.id_feature, 1, 'N/A'
from    ps_feature f
left join
        ps_feature_lang fl
on      f.id_feature = fl.id_feature and
        fl.id_lang = 1
where   fl.id_feature is null
</code>```

Title: MySQL compare two tables and add missing values

Body:
I have a table ps_feature with:

-------------
|id_feature |
-------------
|1          |
|2          |
|3          |
|4          |
|5          |
|6          |
-------------

and a table ps_feature_lang with:

--------------------------------
|id_feature | id_lang  | name  |
--------------------------------
|1          | 1        | text1 |
|2          | 1        | text2 |
|4          | 1        | text3 |
|5          | 1        | text4 |
--------------------------------

Is there a MySQL script to run in PhPMyAdmin to compare two tables and add missing values in ps_feature_lang ?

The result should be:

--------------------------------
|id_feature | id_lang  | name  |
--------------------------------
|1          | 1        | text1 |
|2          | 1        | text2 |
|3          | 1        | N/A   |
|4          | 1        | text3 |
|5          | 1        | text4 |
|6          | 1        | N/A   |
--------------------------------

Thanks.

Body:
To complete a single language, you can use a left join

insert into ps_feature_lang
select  f.id_feature, 1, 'N/A'
from    ps_feature f
left join
        ps_feature_lang fl
on      f.id_feature = fl.id_feature and
        fl.id_lang = 1
where   fl.id_feature is null


问:
Text alignment without using table in html and css
I'm trying to learn HTML and CSS and using the old-school approach by creating a login page with three input controls (two text and one button). However, I'm using

 for the alignment issues of textboxes. But I've read somewhere that using tables is not considered a good approach. This is what I'm doing:

Home.html

```<code><div>
    <table>
        <thead>
            <tr><th><span>Login Page</span></th></tr>
        </thead>
        <tbody>
            <tr>
            <th><label>Username:</label></th>
            <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <th><label>Password:</label></th>
                <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <td><input type="button" value="Submit" /></td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

However, I'm using some beginner stuff of CSS to align input controls without using tables and this is what I'm trying:

Home.html

```<code><div class="box">
    <span>Login Page</span>
    <br />
    <span>
        <label>Username:</label>
        <input type="text" value="" />
        <br />
        <label>Password:</label>
        <input type="text" value="" />
        <br />
        <input type="button" value="Submit" />
    </span>
</div>
</code>```

style.css

```<code>.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}
</code>```

My concern is using css, I'm able to align the input controls but I have to use multiple break tags (
) and also extra code for alignment which is easier by simply using the
 tag. Can someone suggest me the standard approach and either I'm on the right path or not?

答:
As a small addition to the things that are said already, I would recommend you to consider an option to use a separate container for a single form control and its label. Like this:

```<code><form>
    <div class="input-group">
        <label for="name">Username:</label>
        <input type="text" id="name" value="" />
    </div>
    <div class="input-group">
        <label for="password">Password:</label>
      <input type="text" id="password" value="" />
    </div>
</form>
</code>```

Perhaps, one might say this is redundant, but from my perspective, it gives you more control during positioning. On the other hand, Michael Seltenreich is making a good point. I still find tables used for forms in many places, although I'd prefer to keep away from this method.

P.S. In case you want to spread labels and inputs horizontally, you would probably want to use flexboxes.

Body:
I'm trying to learn HTML and CSS and using the old-school approach by creating a login page with three input controls (two text and one button). However, I'm using

 for the alignment issues of textboxes. But I've read somewhere that using tables is not considered a good approach. This is what I'm doing:

Home.html

Login Page

            Username:
            <input type="text" value="" />

                Password:
                <input type="text" value="" />

                <input type="button" value="Submit" />

However, I'm using some beginner stuff of CSS to align input controls without using tables and this is what I'm trying:

Home.html

    Login Page

        Username:
        <input type="text" value="" />

        Password:
        <input type="text" value="" />

        <input type="button" value="Submit" />

style.css

.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}

My concern is using css, I'm able to align the input controls but I have to use multiple break tags (
) and also extra code for alignment which is easier by simply using the
 tag. Can someone suggest me the standard approach and either I'm on the right path or not?

Body:
As a small addition to the things that are said already, I would recommend you to consider an option to use a separate container for a single form control and its label. Like this:

<form>
    <div class="input-group">
        <label for="name">Username:</label>
        <input type="text" id="name" value="" />
    </div>
    <div class="input-group">
        <label for="password">Password:</label>
      <input type="text" id="password" value="" />
    </div>
</form>

Perhaps, one might say this is redundant, but from my perspective, it gives you more control during positioning. On the other hand, Michael Seltenreich is making a good point. I still find tables used for forms in many places, although I'd prefer to keep away from this method.

P.S. In case you want to spread labels and inputs horizontally, you would probably want to use flexboxes.


问:
Cannot convert value of type 'UIImage' to expected argument type 'String'
I am lost, is there any alternative?</p>

```<code>let swiftCourse = Course(buttonImage: #imageLiteral(resourceName: "cover_developer"),
                  title: "Become a Developer",
                  instructor: "Duc Tran",
                  featureImage: #imageLiteral(resourceName: "developer"),
                  introductionVideoURL: URL(String: "https://www.youtube.com/watch?v=Inn2K-V3NFI"),
                  description: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")
</code>```

答:
Replace your code and try:</p>

```<code>let swiftCourse = Course(buttonImage:"cover_developer",
                  title: "Become a Developer",
                  instructor: "Duc Tran",
                  featureImage: "developer",
                  introductionVideoURL: URL(String: "https://www.youtube.com/watch?v=Inn2K-V3NFI"),
                  description: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")
</code>```

Body:
I am lost, is there any alternative?

let swiftCourse = Course(buttonImage: #imageLiteral(resourceName: "cover_developer"),
                  title: "Become a Developer",
                  instructor: "Duc Tran",
                  featureImage: #imageLiteral(resourceName: "developer"),
                  introductionVideoURL: URL(String: "https://www.youtube.com/watch?v=Inn2K-V3NFI"),
                  description: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")

Body:
Replace your code and try:

let swiftCourse = Course(buttonImage:"cover_developer",
                  title: "Become a Developer",
                  instructor: "Duc Tran",
                  featureImage: "developer",
                  introductionVideoURL: URL(String: "https://www.youtube.com/watch?v=Inn2K-V3NFI"),
                  description: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.")


问:
merging returns odd length
I am having a problem with a relatively simple task...

I have two dataframes:
df_sample which I read from csv

```<code>+------+-----------+-------+-----------+
| key  | Full Text | Date  | Publisher |
+------+-----------+-------+-----------+
| abcd | foofoo    | date1 | a         |
| bcde | barbar    | date2 | b         |
| cdef | foobar    | date3 | c         |
+------+-----------+-------+-----------+

len(df_sample) = 20000
</code>```

df_labels which I read from excel

```<code>+------+----------+--------+--------+
| key  | relevant | other  | other2 |
+------+----------+--------+--------+
| abcd | yes      | blabla | blabla |
| bcde | no       | blabla | blabla |
| cdef | no       | blabla | blabla |
| defg | yes      | blabla | blabla |
+------+----------+--------+--------+

len(df_labels) = 219000
</code>```

I would like to join both tables on key assigning relevant value for each key from the first dataframe. The desired output would be like this:

```<code>+------+-----------+-------+-----------+----------+
| key  | Full Text | Date  | Publisher | relevant |
+------+-----------+-------+-----------+----------+
| abcd | foofoo    | date1 | a         | yes      |
| bcde | barbar    | date2 | b         | no       |
| cdef | foobar    | date3 | c         | no       |
+------+-----------+-------+-----------+----------+
</code>```

I seem to achieve that but why the following gives me 27377 results instead of 20000 (as in original left table):

```<code>df = pd.merge(left=df_sample, right=df_labels, on="key")
</code>```

答:
You're seeing additional rows because the keys are not unique across both dfs, in your case the second df. You'll need to decide whether you want repeated rows which is the current behaviour or you want to drop the duplicates in the second df:

```<code>df_labels = df_labels.drop_duplicates(subset='key')
</code>```

this will by default keep just the first duplicate, if you want alternate behaviour such as keep last, then you can pass: keep='last' see the docs

Title: merging returns odd length

Body:
I am having a problem with a relatively simple task...

I have two dataframes:
df_sample which I read from csv

+------+-----------+-------+-----------+
| key  | Full Text | Date  | Publisher |
+------+-----------+-------+-----------+
| abcd | foofoo    | date1 | a         |
| bcde | barbar    | date2 | b         |
| cdef | foobar    | date3 | c         |
+------+-----------+-------+-----------+

len(df_sample) = 20000

df_labels which I read from excel

+------+----------+--------+--------+
| key  | relevant | other  | other2 |
+------+----------+--------+--------+
| abcd | yes      | blabla | blabla |
| bcde | no       | blabla | blabla |
| cdef | no       | blabla | blabla |
| defg | yes      | blabla | blabla |
+------+----------+--------+--------+

len(df_labels) = 219000

I would like to join both tables on key assigning relevant value for each key from the first dataframe. The desired output would be like this:

+------+-----------+-------+-----------+----------+
| key  | Full Text | Date  | Publisher | relevant |
+------+-----------+-------+-----------+----------+
| abcd | foofoo    | date1 | a         | yes      |
| bcde | barbar    | date2 | b         | no       |
| cdef | foobar    | date3 | c         | no       |
+------+-----------+-------+-----------+----------+

I seem to achieve that but why the following gives me 27377 results instead of 20000 (as in original left table):

df = pd.merge(left=df_sample, right=df_labels, on="key")

Body:
You're seeing additional rows because the keys are not unique across both dfs, in your case the second df. You'll need to decide whether you want repeated rows which is the current behaviour or you want to drop the duplicates in the second df:

df_labels = df_labels.drop_duplicates(subset='key')

this will by default keep just the first duplicate, if you want alternate behaviour such as keep last, then you can pass: keep='last' see the docs


问:
Java Input from formatted file
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

```<code>The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
</code>```

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

答:
Here is a solution based on regular expressions:

```<code>import java.io.*;
import java.util.regex.*;

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

        BufferedReader br = new BufferedReader(new FileReader("data.txt"));

        Pattern p = Pattern.compile("(.+?),(.+?)(?::(.+?):(\\d+ \\d+ \\d+))?");

        String line;
        while (null != (line = br.readLine())) {
            Matcher m = p.matcher(line);
            if (m.matches()) {
                String title = m.group(1);
                String author = m.group(2);
                String borrower = m.group(3);
                String data = m.group(4);

                System.out.println("Title:  " + title);
                System.out.println("Author: " + author);
                if (borrower != null) {
                    System.out.println("    Borrower: " + borrower);
                    System.out.println("    Data:     " + data);
                }
            }
            System.out.println();
        }

        br.close();
    }
}
</code>```

Given your sample input, it prints:

```<code>Title:  The Lord of the Rings
Author:  JRR Tolkien
    Borrower: McInnes Elizabeth
    Data:     13 11 10

Title:  Crime And Punishment
Author:  Fyodor Dostoyevsky

Title:  The Clan Of The Cave Bear
Author:  Jean M Auel

Title:  The God Of Small Things
Author:  Arundhati Roy
    Borrower: Robins Joshua
    Data:     20 11 10
</code>```

Title: Java Input from formatted file

Body:
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

Body:
Here is a solution based on regular expressions:

import java.io.*;
import java.util.regex.*;

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

        BufferedReader br = new BufferedReader(new FileReader("data.txt"));

        Pattern p = Pattern.compile("(.+?),(.+?)(?::(.+?):(\\d+ \\d+ \\d+))?");

        String line;
        while (null != (line = br.readLine())) {
            Matcher m = p.matcher(line);
            if (m.matches()) {
                String title = m.group(1);
                String author = m.group(2);
                String borrower = m.group(3);
                String data = m.group(4);

                System.out.println("Title:  " + title);
                System.out.println("Author: " + author);
                if (borrower != null) {
                    System.out.println("    Borrower: " + borrower);
                    System.out.println("    Data:     " + data);
                }
            }
            System.out.println();
        }

        br.close();
    }
}

Given your sample input, it prints:

Title:  The Lord of the Rings
Author:  JRR Tolkien
    Borrower: McInnes Elizabeth
    Data:     13 11 10

Title:  Crime And Punishment
Author:  Fyodor Dostoyevsky

Title:  The Clan Of The Cave Bear
Author:  Jean M Auel

Title:  The God Of Small Things
Author:  Arundhati Roy
    Borrower: Robins Joshua
    Data:     20 11 10


问:
Replacing Class Names by Strings Reactjs
This is currently what I do

```<code>var longTextList = this.props.data.map(function(text, index){
                        return <Thumbnail key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Thumbnail>;
                      });
</code>```

Since, return returns a string, why can't we replace the class name with a user defined string.

For instance <Thumbnail> with <{this.props.type> where this.props.type=Thumbnail.

EDIT

I'm calling my class like this

```<code><CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type="Thumbnail"/>
</code>```

where type tells us to render a Thumbnail.

In CardView.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Thumbnail } from 'react-bootstrap';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
var longTextList = this.props.data.map(function(text, index){
                        return <Type key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Thumbnail>;
                      });

        return (
            <div>{longTextList}</div>
            );
    }
});

export default CardView;
</code>```

Facing Error

```<code>Expected corresponding JSX closing tag for <Type>
</code>```

答:
Can you bypass the string and just pass the type as the prop?

```<code>import { Thumbnail } from 'react-bootstrap';

<CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type={Thumbnail}/>
</code>```

Now in CardView.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
        var longTextList = this.props.data.map(function(text, index){
                               return <Type key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Type>;
                           });

        return (
            <div>{longTextList}</div>
            );
    }
});

export default CardView;
</code>```

Body:
This is currently what I do

var longTextList = this.props.data.map(function(text, index){
                        return <Thumbnail key={index} style={fontSize} >
{text.longText} and get {coinName}(s)
</Thumbnail>;
                      });

Since, return returns a string, why can't we replace the class name with a user defined string.

For instance <Thumbnail> with <{this.props.type> where this.props.type=Thumbnail.

EDIT

I'm calling my class like this

<CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type="Thumbnail"/>

where type tells us to render a Thumbnail.

In CardView.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Thumbnail } from 'react-bootstrap';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
var longTextList = this.props.data.map(function(text, index){
                        return <Type key={index} style={fontSize} >
{text.longText} and get {coinName}(s)
</Thumbnail>;
                      });

        return (

{longTextList}

            );
    }
});

export default CardView;

Facing Error

Expected corresponding JSX closing tag for <Type>

Body:
Can you bypass the string and just pass the type as the prop?

import { Thumbnail } from 'react-bootstrap';

<CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type={Thumbnail}/>

Now in CardView.js

import React from 'react';
import ReactDOM from 'react-dom';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
        var longTextList = this.props.data.map(function(text, index){
                               return <Type key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Type>;
                           });

        return (
            <div>{longTextList}</div>
            );
    }
});

export default CardView;


问:
Delete Last Row in a Table - SQL
I have the following basic SQL query:

```<code>DELETE TOP (1)
FROM dbo.userPasswordHistory
WHERE UserId IN (SELECT Id FROM dbo.user WHERE LogonId = @UserLogonId)
</code>```

I want to delete the most recent entry in the dbo.userPasswordHistory table but DELETE TOP (1) is deleting the oldest entry, not the most recent. So for instance if the dbo.userPasswordHistory table contains 5 rows for a specified user then it is the most recent entry that I want to delete.

How would I order the table based on a column called LastModifiedTime or is there a way I can specify bottom or last?

答:
You can do this with a subquery or CTE:</p>

```<code>DELETE t
FROM (SELECT TOP (1) uph.*
      FROM dbo.userPasswordHistory uph
      WHERE UserId IN (SELECT Id
                       FROM dbo.user
                       WHERE LogonId = @UserLogonId
                      )
      ORDER BY LastModifiedTime DESC
     ) t;
</code>```

Title: Delete Last Row in a Table - SQL

Body:
I have the following basic SQL query:

DELETE TOP (1)
FROM dbo.userPasswordHistory
WHERE UserId IN (SELECT Id FROM dbo.user WHERE LogonId = @UserLogonId)

I want to delete the most recent entry in the dbo.userPasswordHistory table but DELETE TOP (1) is deleting the oldest entry, not the most recent. So for instance if the dbo.userPasswordHistory table contains 5 rows for a specified user then it is the most recent entry that I want to delete.

How would I order the table based on a column called LastModifiedTime or is there a way I can specify bottom or last?

Body:
You can do this with a subquery or CTE:

DELETE t
FROM (SELECT TOP (1) uph.*
      FROM dbo.userPasswordHistory uph
      WHERE UserId IN (SELECT Id
                       FROM dbo.user
                       WHERE LogonId = @UserLogonId
                      )
      ORDER BY LastModifiedTime DESC
     ) t;


答:
Winforms has "right" controls for displaying collection data - DataGridView for example.

```<code>yourDataGridView.DataSource = steps.ToList();
</code>```

DataGridView will generate rows and one column which will contain values of steps. For automated generating column you need to be sure that yourDataGridView.AutoGenerateColumns = true - (it is true by default)

You can "style" generated cells by using DataGridView.DefaultCellStyle property or others.

If you need display images besides text then DataGridView seems "right" choice.

Create a class which represents your data structure of step

```<code>public class Step
{
    public string Name { get; set; }
    public Image StatusImage { get; set; }
}

// Create collection
var steps = new List<Step>
{
    new Step { Name = "One", StatusImage = image1 },
    new Step { Name = "Two", StatusImage = image1 },
    new Step { Name = "Three", StatusImage = image1 }
}

yourDataGridView.DataSource = steps;
</code>```

DataGridView should generate DataGridViewImageColumn for StatusImage property.

If you have an enum for StepStatus instead of image. Then you can use DataGridView.CellFormatting event to convert enum to the image.

Title: How to generalize this C# code?

Body:
I have this code which initializes winforms textboxes.

txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];

I'd like to generalize it like this:

for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

Body:
Winforms has "right" controls for displaying collection data - DataGridView for example.

yourDataGridView.DataSource = steps.ToList();

DataGridView will generate rows and one column which will contain values of steps. For automated generating column you need to be sure that yourDataGridView.AutoGenerateColumns = true - (it is true by default)

You can "style" generated cells by using DataGridView.DefaultCellStyle property or others.

If you need display images besides text then DataGridView seems "right" choice.

Create a class which represents your data structure of step

public class Step
{
    public string Name { get; set; }
    public Image StatusImage { get; set; }
}

// Create collection
var steps = new List<Step>
{
    new Step { Name = "One", StatusImage = image1 },
    new Step { Name = "Two", StatusImage = image1 },
    new Step { Name = "Three", StatusImage = image1 }
}

yourDataGridView.DataSource = steps;

DataGridView should generate DataGridViewImageColumn for StatusImage property.

If you have an enum for StepStatus instead of image. Then you can use DataGridView.CellFormatting event to convert enum to the image.


问:
Highcharts - change color of only clicked column
I have a column chart made using Highcharts.js. On click of a bar, it's color changes to orange. But when another bar is clicked, the color of previously clicked bar remains orange.

What I want is that on click of a bar, the color of all other bars should turn to default.

```<code> $('#container').highcharts({
    chart: {
        type: 'column'
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    plotOptions: {
        series: {
            point: {
                events: {
                    click: function(event) {
                        console.log(this);
                        this.update({ color: '#fe5800' }, true, false);
                        }
                }
            }
        }
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
});
</code>```

Fiddle link - Demo.

Thanks in advance.

答:
Update in 2017:

There is now a built'in way to do that:

```<code> series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2, -1, -2, -3],
        color: 'steelblue',
        negativeColor: 'indianred',
        states: {
            select: {
                color: 'blue'
            }
        },
        allowPointSelect: true
    }]
</code>```

Fiddle: http://jsfiddle.net/nk1v22du/

Body:
I have a column chart made using Highcharts.js. On click of a bar, it's color changes to orange. But when another bar is clicked, the color of previously clicked bar remains orange.

What I want is that on click of a bar, the color of all other bars should turn to default.

 $('#container').highcharts({
    chart: {
        type: 'column'
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    plotOptions: {
        series: {
            point: {
                events: {
                    click: function(event) {
                        console.log(this);
                        this.update({ color: '#fe5800' }, true, false);
                        }
                }
            }
        }
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
});

Fiddle link - Demo.

Thanks in advance.

Body:
Update in 2017:

There is now a built'in way to do that:

 series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2, -1, -2, -3],
        color: 'steelblue',
        negativeColor: 'indianred',
        states: {
            select: {
                color: 'blue'
            }
        },
        allowPointSelect: true
    }]

Fiddle: http://jsfiddle.net/nk1v22du/


Title: How to build up a backtesting program with Mathematica?

Body:
Given a stock {price,vary price} sequence like this:

lstPrice={{4.66,-0.05},{4.69,0.03},{4.78,0.09},{4.78,0.},{4.81,0.03},{4.85,0.04},{4.78,-0.07},{5.1,0.32},{5.29,0.19},{5.19,-0.1},{5.28,0.09},{5.22,-0.06},{5.18,-0.04},{5.07,-0.11},{5.08,0.01},{5.09,0.01},{5.07,-0.02},{5.1,0.03},{5.05,-0.05},{5.05,0.},{5.13,0.08},{5.1,-0.03},{5.09,-0.01},{5.21,0.12},{5.24,0.03},{5.26,0.02},{5.35,0.09},{5.19,-0.16},{5.24,0.05},{5.09,-0.15},{5.18,0.09},{5.19,0.01},{5.18,-0.01},{5.13,-0.05},{5.15,0.02},{5.06,-0.09},{5.09,0.03},{5.08,-0.01},{5.01,-0.07},{4.99,-0.02},{4.99,0.},{4.94,-0.05},{4.98,0.04},{4.92,-0.06},{4.87,-0.05},{4.91,0.04},{4.91,0.},{4.92,0.01},{4.95,0.03},{4.9,-0.05},{4.93,0.03},{4.99,0.06},{5.04,0.05},{4.98,-0.06},{5.17,0.19},{5.07,-0.1},{5.08,0.01},{5.14,0.06},{5.17,0.03},{5.07,-0.1}}

and max capital level to $500000, max position level to 100000,
When vary price is negative, buy p1 percent of capital level, when vary price posotive, sell p2 percent of position level. so as to check this simple strategy whether succeeding by the end.
How to build up a Mathematica backtesting program to test the idea, Functional programming best, or like bellow block. Thansk!

initCapital=500000;(*min to 0 *)
initPosition=0;(*max to 100000*)
p1=0.3;
p2=0.2;
BacktestDo[list_?ListQ]:=If[list[[2]]>0,Buy[p1],Sell[p2]](*Buy and Sell not implemented*)
BacktestDo/@listPrice

Body:
This assumes p1 & p2 are 30% and 20% respectively.  If you mean 0.3% and 0.2% adjust the code to p1/100 and p2/100 as indicated in the comments.

listPrice = {
   {4.66, -0.05}, {4.69, 0.03}, {4.78, 0.09}, {4.78, 0.},
   {4.81, 0.03}, {4.85, 0.04}, {4.78, -0.07}, {5.1, 0.32},
   {5.29, 0.19}, {5.19, -0.1}, {5.28, 0.09}, {5.22, -0.06},
   {5.18, -0.04}, {5.07, -0.11}, {5.08, 0.01}, {5.09, 0.01},
   {5.07, -0.02}, {5.1, 0.03}, {5.05, -0.05}, {5.05, 0.},
   {5.13, 0.08}, {5.1, -0.03}, {5.09, -0.01}, {5.21, 0.12},
   {5.24, 0.03}, {5.26, 0.02}, {5.35, 0.09}, {5.19, -0.16},
   {5.24, 0.05}, {5.09, -0.15}, {5.18, 0.09}, {5.19, 0.01},
   {5.18, -0.01}, {5.13, -0.05}, {5.15, 0.02}, {5.06, -0.09},
   {5.09, 0.03}, {5.08, -0.01}, {5.01, -0.07}, {4.99, -0.02},
   {4.99, 0.}, {4.94, -0.05}, {4.98, 0.04}, {4.92, -0.06},
   {4.87, -0.05}, {4.91, 0.04}, {4.91, 0.}, {4.92, 0.01},
   {4.95, 0.03}, {4.9, -0.05}, {4.93, 0.03}, {4.99, 0.06},
   {5.04, 0.05}, {4.98, -0.06}, {5.17, 0.19}, {5.07, -0.1},
   {5.08, 0.01}, {5.14, 0.06}, {5.17, 0.03}, {5.07, -0.1}};

initCapital = 500000;(* min to 0 *)
initPosition = 0;(* max to 100000 *)
p1 = 0.3;
p2 = 0.2;

capital = {initCapital};
position = {initPosition};
totalassets = {initCapital};

buy[p1_, price_] := Module[{value},
  value = Last[capital] p1 (* or use p1/100 *);
  (* check limits *)
  If[Last[position] + value/price > 100000 ||
    Last[capital] - value < 0,
   (* skip transaction *)
   AppendTo[position, Last[position]];
   AppendTo[capital, Last[capital]];
   AppendTo[totalassets, Last[totalassets]],
   (* or make transaction *)
   AppendTo[position, Last[position] + value/price];
   AppendTo[capital, Last[capital] - value];
   AppendTo[totalassets, price Last[position] + Last[capital]];
   {"buy", p1, value, Last[capital]}]]

sell[p2_, price_] := Module[{quantity},
  quantity = Last[position] p2 (* or use p2/100 *);
  (* make transaction *)
  AppendTo[position, Last[position] - quantity];
  AppendTo[capital, Last[capital] + quantity*price];
  AppendTo[totalassets, price Last[position] + Last[capital]];
  {"sell", p2, quantity*price, Last[capital]}]

backtestDo[list_List] := If[list[[2]] < 0,
  buy[p1, First[list]],
  sell[p2, First[list]]
  ]

backtestDo /@ listPrice;

GraphicsColumn[Map[ListLinePlot[ToExpression[#],
    DataRange -> Length[listPrice] + 1,
    PlotLabel -> #,
    ImagePadding -> {{40, 10}, {Automatic, Automatic}}] &,
  {"capital", "position", "totalassets"}], ImageSize -> 400]


问:
Enable a single warning in Visual Studio
Is there a compiler switch to enable a single warning in Visual Studio?

The reason I ask is I want to enable warning C4265 which is off by default. My searching has only turned up ways to turn warnings off.

Even Microsoft pages called How to: Enable or Disable Compiler Warnings still only mention disabling.

答:
To make the comment of Matthäus Brandl regarding #pragma warning more visible:

If you're compiling with a warning level lower than 3, you have to use this syntax:

```<code>#pragma warning (<warning level>: 4265)
</code>```

Only if you compile with level 3 or higher you can do

```<code>#pragma warning (default: 4265)
</code>```

because for warning 4265, default means level 3 (see MSDN).

The documentation for #pragma warning reads:

warning-specifier   Meaning

1, 2, 3, 4 Apply the given level to the specified warning(s). This also turns on a specified warning that is off by default.

default Reset warning behavior to its default value. This also turns on a specified warning that is off by default. The warning will be generated at its default, documented, level.

Body:
To make the comment of Matthäus Brandl regarding #pragma warning more visible:

If you're compiling with a warning level lower than 3, you have to use this syntax:

#pragma warning (<warning level>: 4265)

Only if you compile with level 3 or higher you can do

#pragma warning (default: 4265)

because for warning 4265, default means level 3 (see MSDN).

The documentation for #pragma warning reads:

warning-specifier   Meaning

1, 2, 3, 4 Apply the given level to the specified warning(s). This also turns on a specified warning that is off by default.

default Reset warning behavior to its default value. This also turns on a specified warning that is off by default. The warning will be generated at its default, documented, level.


问:
How to split these strings into an array
I'm looking for a method to split the following line of text into an array.

Here is some text\r\n"here is another line"\r\nAnd another line

Such that the resultant array is:

Here is some text

\r\n

"

here is another line

"

\r\n

And another line

Note there are essentially two delimeters here, " and \r\n.

I need to do this in C++ and there could be additional delimeters in the future.

Any ideas?

Thanks in advance.

Edit: No, this is not homework.

Here's what I have so far:

```<code>const RWCString crLF = "\r\n";
const RWCString doubleQuote = "\"";

    RWTValOrderedVector<RWCString> Split(const RWCString &value, const RWCString &specialContent)
    {
        RWTValOrderedVector<RWCString> result;

        unsigned index = 0;

        RWCString str = value;

        while ( ( index = str.index( specialContent, 0, RWCString::ignoreCase ) ) != RW_NPOS )
        {
            RWCString line = str(0, index);

            result.append(line);
            result.append(specialContent);

            str = str(index, str.length() - index);
            str = str(specialContent.length(), str.length() - specialContent.length());
        }

        if (str.length() > 0)
        {
            result.append(str);
        }

        return result;
    }

        void replaceSpecialContents(const RWCString &value)
        {

            RWTValOrderedVector<RWCString> allStrings;

            RWTValOrderedVector<RWCString> crLFStrings = Split(value, crLF);

            for (unsigned i=0; i<crLFStrings.entries(); i++)
            {
            RWTValOrderedVector<RWCString> dqStrings = Split(crLFStrings[i], doubleQuote);

                if (dqStrings.entries() == 1)
                {
                    allStrings.append(crLFStrings[i]);
                }
                else
                {
                    for (unsigned j=0; j<dqStrings.entries(); j++)
                    {
                        allStrings.append(dqStrings[j]);
                    }
                }
            }

    }
</code>```

答:
Bissect the problem as follows:

I have a pointer to substring. How to find the next substring?

I have a pointer to substring. How do I add it as the next element to array?

Now, solve 1 and 2. If any problem, ask again.

Body:
I'm looking for a method to split the following line of text into an array.

Here is some text\r\n"here is another line"\r\nAnd another line

Such that the resultant array is:

Here is some text

\r\n

"

here is another line

"

\r\n

And another line

Note there are essentially two delimeters here, " and \r\n.

I need to do this in C++ and there could be additional delimeters in the future.

Any ideas?

Thanks in advance.

Edit: No, this is not homework.

Here's what I have so far:

const RWCString crLF = "\r\n";
const RWCString doubleQuote = "\"";

    RWTValOrderedVector<RWCString> Split(const RWCString &value, const RWCString &specialContent)
    {
        RWTValOrderedVector<RWCString> result;

        unsigned index = 0;

        RWCString str = value;

        while ( ( index = str.index( specialContent, 0, RWCString::ignoreCase ) ) != RW_NPOS )
        {
            RWCString line = str(0, index);

            result.append(line);
            result.append(specialContent);

            str = str(index, str.length() - index);
            str = str(specialContent.length(), str.length() - specialContent.length());
        }

        if (str.length() > 0)
        {
            result.append(str);
        }

        return result;
    }

        void replaceSpecialContents(const RWCString &value)
        {

            RWTValOrderedVector<RWCString> allStrings;

            RWTValOrderedVector<RWCString> crLFStrings = Split(value, crLF);

            for (unsigned i=0; i<crLFStrings.entries(); i++)
            {
            RWTValOrderedVector<RWCString> dqStrings = Split(crLFStrings[i], doubleQuote);

                if (dqStrings.entries() == 1)
                {
                    allStrings.append(crLFStrings[i]);
                }
                else
                {
                    for (unsigned j=0; j<dqStrings.entries(); j++)
                    {
                        allStrings.append(dqStrings[j]);
                    }
                }
            }

    }


问:
Detect is user has scrolled on iOS and then change colour of view
I am looking for a way in Xcode and Swift to detect if my user has scrolled down the app.

If they have I would like to turn the view at the top of the app from transparent to black. If the user scrolls back to the top again, the view changes from black back to transparent.

Is this something which is achievable in Swift and Xcode?

Thanks in advance! :)

UPDATE Sorry I forgot to mention, I am using uiwebview, with my view overlaying above it. At the top of the app it will be transparent and when I scroll down the webview it will change to black. Can I still detect the scroll the same way?

答:
You can catch the scroll event by having your controller or some other class listen to the UISCrollViewDelegate protocol.

Particularly, look for scrollViewDidScroll (when scrolling starts) and scrollViewDidEndDecelerating (when scrolling ends).

The latter needs some time, so you could also check the contentOffset in scrollViewDidScroll to catch this condition instantly.

If you do not know how to change the backgroundColor of a view, ask another question.


问:
pack() in php. Illegal hex digit warning
i am having some problems using pack() in php

```<code>$currencypair = "EUR/USD";
$buy_sell = "buy";
$alert_device_token =array("a","a","b");
$message = "Your " . $currencypair . " " . $buy_sell . " alert price has been reached!";
$payload['aps'] = array (
  'alert' => $message,
  'badge' => 1,
  'sound' => 'default'
);
$payload = json_encode($payload);

foreach ($alert_device_token as $alert_device)
{
  $apnsMessage = chr(0) . chr(0) . chr(32) .
                 pack('H*', str_replace(' ', '', $alert_device)) .
                 chr(0) . chr(strlen($payload)) . $payload;
  echo $apnsMessage;
}
</code>```

Now sometimes i get following warnings running the same code -

```<code>Warning: pack() [function.pack]: Type H: illegal hex digit g in /code/FR2BVl
</code>```

the illegal hex digit keeps varying though. Any ideas about this warning and ways to remove it.

check it live here

答: I was having the same issue when developing a hybrid app using Ionic/Cordova/PhoneGap. As the same code is run in Android and iOS devices, I had made a mistake of storing Google FCM token as APNS token. The APNS token is purely hexadecimal but Google FCM token can have non-hexadecimal characters. So, packing a Google FCM token using PHP's pack() function will result in the illegal hex digit error.

Body:
i am having some problems using pack() in php

$currencypair = "EUR/USD";
$buy_sell = "buy";
$alert_device_token =array("a","a","b");
$message = "Your " . $currencypair . " " . $buy_sell . " alert price has been reached!";
$payload['aps'] = array (
  'alert' => $message,
  'badge' => 1,
  'sound' => 'default'
);
$payload = json_encode($payload);

foreach ($alert_device_token as $alert_device)
{
  $apnsMessage = chr(0) . chr(0) . chr(32) .
                 pack('H*', str_replace(' ', '', $alert_device)) .
                 chr(0) . chr(strlen($payload)) . $payload;
  echo $apnsMessage;
}

Now sometimes i get following warnings running the same code -

Warning: pack() [function.pack]: Type H: illegal hex digit g in /code/FR2BVl

the illegal hex digit keeps varying though. Any ideas about this warning and ways to remove it.

check it live here


问:
UNWIND is not returning in neo4j
Consider the follwing CQL Query

```<code>MATCH (n:Label1) WITH n
OPTIONAL MATCH (n)-[r:REL_1]-(:Label2 {id: 5})
WHERE r is NULL OR r.d < 12345 OR (r.d = 12345 OR r.c < 2)
WITH n,r LIMIT 100
WITH COLLECT({n: n, r: r}) AS rows
MERGE (c:Label2 {id: 5})
WITH c,
[b IN rows WHERE  b.r.d IS NULL OR b.r.d < 12345] AS null_less_rows,
[c IN rows WHERE (c.r.d = 12345 AND c.r.c < 2)] AS other_rows
WITH null_less_rows, other_rows, c, null_less_rows+other_rows AS rows, size(null_less_rows+other_rows) AS count
UNWIND null_less_rows AS null_less_row
MERGE(s:Label1 {id: null_less_row.n.id})
MERGE(s)-[:REL_1 {d: 12345, c: 1}]->(c)
WITH DISTINCT other_rows, c, rows, count
UNWIND other_rows AS other_row
MATCH(s:Label1 {id: other_row.n.id})-[str:REL_1]->(c) SET str.c = str.c + 1
WITH rows, count
RETURN rows, count
</code>```

When I excute the query, It should return rows and count (according to query). But instead of returning rows, count it's giving result statement.

```<code>Set 200 properties, created 100 relationships, statement completed in 13 ms.
</code>```

Is there any problem with query structure or problem with improper use of UNWIND clause.

答:
If other_rows is null or empty, UNWIND will not produce any rows.

You could solve it with:

```<code>UNWIND case coalesce(size(other_rows),0) when 0 then [null] else other_rows end
   as other_row
</code>```

Title: UNWIND is not returning in neo4j

Body:
Consider the follwing CQL Query

MATCH (n:Label1) WITH n
OPTIONAL MATCH (n)-[r:REL_1]-(:Label2 {id: 5})
WHERE r is NULL OR r.d < 12345 OR (r.d = 12345 OR r.c < 2)
WITH n,r LIMIT 100
WITH COLLECT({n: n, r: r}) AS rows
MERGE (c:Label2 {id: 5})
WITH c,
[b IN rows WHERE  b.r.d IS NULL OR b.r.d < 12345] AS null_less_rows,
[c IN rows WHERE (c.r.d = 12345 AND c.r.c < 2)] AS other_rows
WITH null_less_rows, other_rows, c, null_less_rows+other_rows AS rows, size(null_less_rows+other_rows) AS count
UNWIND null_less_rows AS null_less_row
MERGE(s:Label1 {id: null_less_row.n.id})
MERGE(s)-[:REL_1 {d: 12345, c: 1}]->(c)
WITH DISTINCT other_rows, c, rows, count
UNWIND other_rows AS other_row
MATCH(s:Label1 {id: other_row.n.id})-[str:REL_1]->(c) SET str.c = str.c + 1
WITH rows, count
RETURN rows, count

When I excute the query, It should return rows and count (according to query). But instead of returning rows, count it's giving result statement.

Set 200 properties, created 100 relationships, statement completed in 13 ms.

Is there any problem with query structure or problem with improper use of UNWIND clause.

Body:
If other_rows is null or empty, UNWIND will not produce any rows.

You could solve it with:

UNWIND case coalesce(size(other_rows),0) when 0 then [null] else other_rows end
   as other_row


问:
Writing UTF-8 String to MySQL with Python
I am trying to push user account data from an Active Directory to our MySQL-Server. This works flawlessly but somehow the strings end up showing an encoded version of umlauts and other special characters.

The Active Directory returns a string using this sample format: M\xc3\xbcller

This actually is the UTF-8 encoding for Müller, but I want to write Müller to my database not M\xc3\xbcller.

I tried converting the string with this line, but it results in the same string in the database:
tempEntry[1] = tempEntry[1].decode("utf-8")

If I run print "M\xc3\xbcller".decode("utf-8") in the python console the output is correct.

Is there any way to insert this string the right way? I need this specific format for a web developer who wants to have this exact format, I don't know why he is not able to convert the string using PHP directly.

Additional info: I am using MySQLdb; The table and column encoding is utf8_general_ci

答:
there is another situation maybe a little rare.

if you create a schema in mysqlworkbench firstly,you will get the encoding error and can't solve it by add charset configuration.

it is because mysqlworkbench create schema by latin1 by default, so you should set the charset at first!


问:
Running a diffent code for each block of file
I have an output file from some numeric calculation. The output file looks like

aa ab ac ad ae   ┐

  ba bb bc bd be   ┘  Block of 5 strings

  0.5 1.2 0.3 aaa bbb  ┐

  0.2 8.2 3.3 ccc ddd  ┃ Block of 3 float + 2 string

  0.5 1.3 0.6 eee ggg  ┘

  0.11  0.444  0.333 0.777 0.88  ┐

  0.41  0.544  0.313 0.797 0.01 ┃

  0.11  0.447  0.333 0.777 0.88 ┃  Block of 6 float

  0.17  0.444  0.333 0.787 0.03 ┃

  0.11  0.444  0.333 0.777 0.88 ┘

which means, it forms block of some patterns. What I want to do is to read this file, and do some stuff for each block seperately.

For the simplest approach, I wrote the code like

```<code>file = open("myfile", "r")
for i, line in enumerate(file):
    if i <= 1:
        # do some stuff 1.
    elif 1< i <=4 :
        # do some stuff 2
    elif 4 < i :
        # do some stuff 3
file.close()
</code>```

and specify the line number manually whenever I run the program. The problem is that the line number of output file varies from file to file (but the pattern is same), and before I check it manually by eye, I don't know how long each block will be. What is the efficient approach handling this problem?

The size of each file is about 100~1000MB, and each contains about 500000~ 5000000 lines.

答:
You can use regular expressions to check which pattern each line matches and then execute the respective code block for each line.</p>

```<code>import re

for x in lines:
    ## matches any number of floats
    if re.match("^([0-9\.]+\s?)+$", x):
        print "do stuff 3"

    ## matches 3 floats and 2 strings
    elif re.match("^([0-9\.]+\s?){3}(\w+\s?){2}$", x):
        print "do stuff 2"

    ## matches 5 strings
    elif re.match("^(\w+\s?){5}$", x):
        print "do stuff 1"
</code>```

Body:
I have an output file from some numeric calculation. The output file looks like

aa ab ac ad ae   ┐

  ba bb bc bd be   ┘  Block of 5 strings

  0.5 1.2 0.3 aaa bbb  ┐

  0.2 8.2 3.3 ccc ddd  ┃ Block of 3 float + 2 string

  0.5 1.3 0.6 eee ggg  ┘

  0.11  0.444  0.333 0.777 0.88  ┐

  0.41  0.544  0.313 0.797 0.01 ┃

  0.11  0.447  0.333 0.777 0.88 ┃  Block of 6 float

  0.17  0.444  0.333 0.787 0.03 ┃

  0.11  0.444  0.333 0.777 0.88 ┘

which means, it forms block of some patterns. What I want to do is to read this file, and do some stuff for each block seperately.

For the simplest approach, I wrote the code like

file = open("myfile", "r")
for i, line in enumerate(file):
    if i <= 1:
        # do some stuff 1.
    elif 1< i <=4 :
        # do some stuff 2
    elif 4 < i :
        # do some stuff 3
file.close()

and specify the line number manually whenever I run the program. The problem is that the line number of output file varies from file to file (but the pattern is same), and before I check it manually by eye, I don't know how long each block will be. What is the efficient approach handling this problem?

The size of each file is about 100~1000MB, and each contains about 500000~ 5000000 lines.

Body:
You can use regular expressions to check which pattern each line matches and then execute the respective code block for each line.

import re

for x in lines:
    ## matches any number of floats
    if re.match("^([0-9\.]+\s?)+$", x):
        print "do stuff 3"

    ## matches 3 floats and 2 strings
    elif re.match("^([0-9\.]+\s?){3}(\w+\s?){2}$", x):
        print "do stuff 2"

    ## matches 5 strings
    elif re.match("^(\w+\s?){5}$", x):
        print "do stuff 1"


问:
How to exit a function in jQuery .on() function when a certain condition is met
I have the following javascript/jquery code.

I am a javascript newbie, so I apologize if this question is extremely easy to solve.
I'd like to exit this .on('click') function if there is an error or if there is no key found on the server. This on click bind fires a post request on a form, so I'd like to continue running it if those two conditions are not met. I checked other examples and I tried numerous things like return, .stopPropagation etc.

How should I do that? I tried return; and return false; but it still refreshes the page and fires the post request on the form.

What am I doing wrong?

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

    var validation = false;
    $('#submitform').on('click', function(e) {

        if (validation === true) {
            validation = false; // reset flag
            return;// let the event bubble away
        }

        if ($('#street_number') == "" && $('#route') == "" && $('#lat') == "" && $('#lon') == ""
                && $('#administrative_area_level_1') == "") {
            alert("Unknown Address");
            validation = false;
            e.preventDefault();
            return false;
        }
        else {
            var data_dict = {
                // Number
                'street_number': $('#street_number').val(),
                // Address
                'address': $('#route').val(),
                // City
                'city': $('#locality').val(),
                // postal code
                'postal_code': $('#postal_code').val(),
                // State
                'state': $('#administrative_area_level_1').val(),
                // Country
                'country': $('#country').val()
            };
            $.ajax({
                url: '/zillow_check/',
                data: data_dict,
                method: 'POST'
            }).then(function (response) {
                console.log("Checking for Zillow ID...");
                if (response.error) {
                    console.error("There was an error " + response.error);
                    $('.dashboard-main__appartment--input').addClass('serverError');
                    validation = false;
                    e.stopImmediatePropagation();
                    return;
                } else {
                    console.log("Zillow key: " + response);
                    if (response == 'No zillow ID found.') {
                        // You can change this to whatever you like.
                        alert("Can't add this object. It does not exist on Zillow. Check the Address and try again.");
                        validation = false;
                        e.stopImmediatePropagation();
                        return;

                    }
                    else if (isNaN(response) == false ) {
                        validation = true;
                        $('#propertyform').submit()
                    }
                }

            });

        }
    });
});
</code>```

答:
You need to prevent the default for all cases right away. </p>

<p>Ajax is asynchronous so you can't wait for it to complete to try to prevent the default then...it's too late. </p>

```<code>$('#submitform').on('click', function(e) {
    e.preventDefault();
    // no need for other instances of preventDefault() beyond here or for `stopImmediatePropagation()`

    // your other code

})
</code>```

Body:
I have the following javascript/jquery code.

I am a javascript newbie, so I apologize if this question is extremely easy to solve.
I'd like to exit this .on('click') function if there is an error or if there is no key found on the server. This on click bind fires a post request on a form, so I'd like to continue running it if those two conditions are not met. I checked other examples and I tried numerous things like return, .stopPropagation etc.

How should I do that? I tried return; and return false; but it still refreshes the page and fires the post request on the form.

What am I doing wrong?

$( document ).ready(function() {

    var validation = false;
    $('#submitform').on('click', function(e) {

        if (validation === true) {
            validation = false; // reset flag
            return;// let the event bubble away
        }

        if ($('#street_number') == "" && $('#route') == "" && $('#lat') == "" && $('#lon') == ""
                && $('#administrative_area_level_1') == "") {
            alert("Unknown Address");
            validation = false;
            e.preventDefault();
            return false;
        }
        else {
            var data_dict = {
                // Number
                'street_number': $('#street_number').val(),
                // Address
                'address': $('#route').val(),
                // City
                'city': $('#locality').val(),
                // postal code
                'postal_code': $('#postal_code').val(),
                // State
                'state': $('#administrative_area_level_1').val(),
                // Country
                'country': $('#country').val()
            };
            $.ajax({
                url: '/zillow_check/',
                data: data_dict,
                method: 'POST'
            }).then(function (response) {
                console.log("Checking for Zillow ID...");
                if (response.error) {
                    console.error("There was an error " + response.error);
                    $('.dashboard-main__appartment--input').addClass('serverError');
                    validation = false;
                    e.stopImmediatePropagation();
                    return;
                } else {
                    console.log("Zillow key: " + response);
                    if (response == 'No zillow ID found.') {
                        // You can change this to whatever you like.
                        alert("Can't add this object. It does not exist on Zillow. Check the Address and try again.");
                        validation = false;
                        e.stopImmediatePropagation();
                        return;

                    }
                    else if (isNaN(response) == false ) {
                        validation = true;
                        $('#propertyform').submit()
                    }
                }

            });

        }
    });
});

Body:
You need to prevent the default for all cases right away.

Ajax is asynchronous so you can't wait for it to complete to try to prevent the default then...it's too late.

$('#submitform').on('click', function(e) {
    e.preventDefault();
    // no need for other instances of preventDefault() beyond here or for `stopImmediatePropagation()`

    // your other code

})


问:
stopping the css animation process
first of all sorry for my English. I am new in css. i have given this effect to text.
    i just want to stop this animation once its done for all the sentences,
    there are 6 sentences with 3sec delay between each two,after last sentence completion
    i want to display all sentences together and wants to keep as it is,but it   will again
     start animation from first sentence.how can i stop this?
     please help me if anyone knows.thanks in advance.this is my css code

.rw-words-1 span{
  font-size: 150%;
  line-height: 120%;
  -webkit-animation: rotateWordsFirst 18s linear infinite 0s;
  -ms-animation: rotateWordsFirst 18s linear infinite 0s;
  animation: rotateWordsFirst 18s linear infinite 0s;
}
.rw-words span:nth-child(2) {
  -webkit-animation-delay: 3s;
  -ms-animation-delay: 3s;
  animation-delay: 3s;
}
.rw-words span:nth-child(3) {
  -webkit-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}
.rw-words span:nth-child(4) {
  -webkit-animation-delay: 9s;
  -ms-animation-delay: 9s;
  animation-delay: 9s;
}
.rw-words span:nth-child(5) {
  -webkit-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}
.rw-words span:nth-child(6) {
  -webkit-animation-delay: 15s;
  -ms-animation-delay: 15s;
  animation-delay: 15s;
}
@-webkit-keyframes rotateWordsFirst {
  0% { opacity: 0; -webkit-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -webkit-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@-ms-keyframes rotateWordsFirst {
  0% { opacity: 0; -ms-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -ms-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@keyframes rotateWordsFirst {
  0% { opacity: 0;   animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1;   animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="rw-wrapper">
  <h2 class="rw-sentence">
    <div class="rw-words rw-words-1">
        <span>beautiful websites</span>
        <span>interesting apps</span>
        <span>impactful identities</span>
        <span>working strategies</span>
        <span>incredible gadgets</span>
        <span>intelligent systems</span>
    </div>
  </h2>
</section></code>```

答:
That is due to infinite in animation inside .rw-words-1 span.Just remove that and it works fine.

.rw-words-1 span{
  font-size: 150%;
  line-height: 120%;
  -webkit-animation: rotateWordsFirst 18s linear;
  -ms-animation: rotateWordsFirst 18s linear;
  animation: rotateWordsFirst 18s linear;
}
.rw-words span:nth-child(2) {
  -webkit-animation-delay: 3s;
  -ms-animation-delay: 3s;
  animation-delay: 3s;
}
.rw-words span:nth-child(3) {
  -webkit-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}
.rw-words span:nth-child(4) {
  -webkit-animation-delay: 9s;
  -ms-animation-delay: 9s;
  animation-delay: 9s;
}
.rw-words span:nth-child(5) {
  -webkit-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}
.rw-words span:nth-child(6) {
  -webkit-animation-delay: 15s;
  -ms-animation-delay: 15s;
  animation-delay: 15s;
}
@-webkit-keyframes rotateWordsFirst {
  0% { opacity: 0; -webkit-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -webkit-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@-ms-keyframes rotateWordsFirst {
  0% { opacity: 0; -ms-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -ms-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@keyframes rotateWordsFirst {
  0% { opacity: 0;   animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1;   animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="rw-wrapper">
  <h2 class="rw-sentence">
    <div class="rw-words rw-words-1">
        <span>beautiful websites</span>
        <span>interesting apps</span>
        <span>impactful identities</span>
        <span>working strategies</span>
        <span>incredible gadgets</span>
        <span>intelligent systems</span>
    </div>
  </h2>
</section></code>```

Title: stopping the css animation process

Body:
first of all sorry for my English. I am new in css. i have given this effect to text.
    i just want to stop this animation once its done for all the sentences,
    there are 6 sentences with 3sec delay between each two,after last sentence completion
    i want to display all sentences together and wants to keep as it is,but it   will again
     start animation from first sentence.how can i stop this?
     please help me if anyone knows.thanks in advance.this is my css code

.rw-words-1 span{
  font-size: 150%;
  line-height: 120%;
  -webkit-animation: rotateWordsFirst 18s linear infinite 0s;
  -ms-animation: rotateWordsFirst 18s linear infinite 0s;
  animation: rotateWordsFirst 18s linear infinite 0s;
}
.rw-words span:nth-child(2) {
  -webkit-animation-delay: 3s;
  -ms-animation-delay: 3s;
  animation-delay: 3s;
}
.rw-words span:nth-child(3) {
  -webkit-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}
.rw-words span:nth-child(4) {
  -webkit-animation-delay: 9s;
  -ms-animation-delay: 9s;
  animation-delay: 9s;
}
.rw-words span:nth-child(5) {
  -webkit-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}
.rw-words span:nth-child(6) {
  -webkit-animation-delay: 15s;
  -ms-animation-delay: 15s;
  animation-delay: 15s;
}
@-webkit-keyframes rotateWordsFirst {
  0% { opacity: 0; -webkit-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -webkit-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@-ms-keyframes rotateWordsFirst {
  0% { opacity: 0; -ms-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -ms-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@keyframes rotateWordsFirst {
  0% { opacity: 0;   animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1;   animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}

        beautiful websites
        interesting apps
        impactful identities
        working strategies
        incredible gadgets
        intelligent systems

Body:
That is due to infinite in animation inside .rw-words-1 span.Just remove that and it works fine.

.rw-words-1 span{
  font-size: 150%;
  line-height: 120%;
  -webkit-animation: rotateWordsFirst 18s linear;
  -ms-animation: rotateWordsFirst 18s linear;
  animation: rotateWordsFirst 18s linear;
}
.rw-words span:nth-child(2) {
  -webkit-animation-delay: 3s;
  -ms-animation-delay: 3s;
  animation-delay: 3s;
}
.rw-words span:nth-child(3) {
  -webkit-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}
.rw-words span:nth-child(4) {
  -webkit-animation-delay: 9s;
  -ms-animation-delay: 9s;
  animation-delay: 9s;
}
.rw-words span:nth-child(5) {
  -webkit-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}
.rw-words span:nth-child(6) {
  -webkit-animation-delay: 15s;
  -ms-animation-delay: 15s;
  animation-delay: 15s;
}
@-webkit-keyframes rotateWordsFirst {
  0% { opacity: 0; -webkit-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -webkit-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@-ms-keyframes rotateWordsFirst {
  0% { opacity: 0; -ms-animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1; -ms-animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}
@keyframes rotateWordsFirst {
  0% { opacity: 0;   animation-timing-function: ease-in; width: 0px;}
  5% { opacity: 1;   animation-timing-function: ease-out; width: 100%;}
  17% { opacity: 1; }
  20% { opacity: 0; }
  100% { opacity: 0; }
}

<section class="rw-wrapper">
  <h2 class="rw-sentence">
    <div class="rw-words rw-words-1">
        <span>beautiful websites</span>
        <span>interesting apps</span>
        <span>impactful identities</span>
        <span>working strategies</span>
        <span>incredible gadgets</span>
        <span>intelligent systems</span>
    </div>
  </h2>
</section>