问:
Elasticsearch installation : Error missing 'server' JVM at ...jvm.dll
After having downloaded elasticsearch and unzipped it following the steps in this link:

Install Elastic Search on Windows

I am receiving the following error:

```<code>Error: missing 'server' JVM at 'C:\Program Files (x86)\Java\jre1.8.0_131\bin\server\jvm.dll'.
Please install or use the JRE or JDK that contains these missing components.
</code>```

Note: I also had to install the JDK8 as suggested in this resolution

Should I change something in the .config file? Maybe this line?

```<code> # force the server VM (remove on 32-bit client JVMs)
 -server
</code>```

答:
Set your JAVA_HOME environment variable to point to the path of your JDK 8 installation.

You can do this on the command line as the example below illustrates:

```<code>SET JAVA_HOME="C:\Program Files (x86)\Java\jdk1.8.0_131"
SET PATH=%JAVA_HOME%\bin;%PATH%
</code>```

Confirm that the correct version of the JDK is in your PATH with:

javac -version

Body:
After having downloaded elasticsearch and unzipped it following the steps in this link:

Install Elastic Search on Windows

I am receiving the following error:

Error: missing 'server' JVM at 'C:\Program Files (x86)\Java\jre1.8.0_131\bin\server\jvm.dll'.
Please install or use the JRE or JDK that contains these missing components.

Note: I also had to install the JDK8 as suggested in this resolution

Should I change something in the .config file? Maybe this line?

 # force the server VM (remove on 32-bit client JVMs)
 -server

Body:
Set your JAVA_HOME environment variable to point to the path of your JDK 8 installation.

You can do this on the command line as the example below illustrates:

SET JAVA_HOME="C:\Program Files (x86)\Java\jdk1.8.0_131"
SET PATH=%JAVA_HOME%\bin;%PATH%

Confirm that the correct version of the JDK is in your PATH with:

javac -version


来源: stackexchange

问:
python load OpenDap to NetcdfFile
I am opening netcdf data from an opendap server (a subset of the data) using an URL. When I open it the data is (as far as I can see) not actually loaded until the variable is requested. I would like to save the data to a file on disk, how would I do this?

I currently have:

```<code>import numpy as np
import netCDF4 as NC

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
set = NC.Dataset(url) # I think data is not yet loaded here, only the "layout"
varData = set.variables['varname'][:,:] # I think data is loaded here

# now i want to save this data to a file (for example test.nc), set.close() obviously wont work
</code>```

Hope someone can help, thanks!

答:
It's quite simple; create a new NetCDF file, and copy whatever you want :) Luckily this can be automated for a large part, in copying the correct dimensions, NetCDF attributes, ... from the input file. I quickly coded this example, the input file is also a local file, but if the reading with OPenDAP already works, it should work in a similar way.

```<code>import netCDF4 as nc4

# Open input file in read (r), and output file in write (w) mode:
nc_in = nc4.Dataset('drycblles.default.0000000.nc', 'r')
nc_out = nc4.Dataset('local_copy.nc', 'w')

# For simplicity; copy all dimensions (with correct size) to output file
for dim in nc_in.dimensions:
    nc_out.createDimension(dim, nc_in.dimensions[dim].size)

# List of variables to copy (they have to be in nc_in...):
# If you want all vaiables, this could be replaced with nc_in.variables
vars_out = ['z', 'zh', 't', 'th', 'thgrad']

for var in vars_out:
    # Create variable in new file:
    var_in  = nc_in.variables[var]
    var_out = nc_out.createVariable(var, datatype=var_in.dtype, dimensions=var_in.dimensions)

    # Copy NetCDF attributes:
    for attr in var_in.ncattrs():
        var_out.setncattr(attr, var_in.getncattr(attr))

    # Copy data:
    var_out[:] = var_in[:]

nc_out.close()
</code>```

Hope it helps, if not let me know.

ContentLicense: CC BY-SA 3.0

Title: python load OpenDap to NetcdfFile

Body:
I am opening netcdf data from an opendap server (a subset of the data) using an URL. When I open it the data is (as far as I can see) not actually loaded until the variable is requested. I would like to save the data to a file on disk, how would I do this?

I currently have:

import numpy as np
import netCDF4 as NC

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
set = NC.Dataset(url) # I think data is not yet loaded here, only the "layout"
varData = set.variables['varname'][:,:] # I think data is loaded here

# now i want to save this data to a file (for example test.nc), set.close() obviously wont work

Hope someone can help, thanks!

Body:
It's quite simple; create a new NetCDF file, and copy whatever you want :) Luckily this can be automated for a large part, in copying the correct dimensions, NetCDF attributes, ... from the input file. I quickly coded this example, the input file is also a local file, but if the reading with OPenDAP already works, it should work in a similar way.

import netCDF4 as nc4

# Open input file in read (r), and output file in write (w) mode:
nc_in = nc4.Dataset('drycblles.default.0000000.nc', 'r')
nc_out = nc4.Dataset('local_copy.nc', 'w')

# For simplicity; copy all dimensions (with correct size) to output file
for dim in nc_in.dimensions:
    nc_out.createDimension(dim, nc_in.dimensions[dim].size)

# List of variables to copy (they have to be in nc_in...):
# If you want all vaiables, this could be replaced with nc_in.variables
vars_out = ['z', 'zh', 't', 'th', 'thgrad']

for var in vars_out:
    # Create variable in new file:
    var_in  = nc_in.variables[var]
    var_out = nc_out.createVariable(var, datatype=var_in.dtype, dimensions=var_in.dimensions)

    # Copy NetCDF attributes:
    for attr in var_in.ncattrs():
        var_out.setncattr(attr, var_in.getncattr(attr))

    # Copy data:
    var_out[:] = var_in[:]

nc_out.close()

Hope it helps, if not let me know.


问:
How to send data from custom sp adapter to target application in ping federate
I have searched entire documentation of ping federate but in vain.
I have an application running on localhost:8080.I have implemented a custom service provider adapter and deployed in ping federate server.I have configured the sp adapter to work with ssocircle idp.I am able to log the attributes from the idp in sp adapter in createAuthN method.I am initiating sso using /sp/ssostart.ping and sending a target resource.Now I want to send the attributes from the custom sp adapter to the target resource using post.</p>

答:
I have configured the sp adapter to work with ssocircle idp.I am able
  to log the attributes from the idp in sp adapter in createAuthN
  method.

There may be a disconnect in what adapters do, versus connections, in PingFederate. A connection is a carrier of attributes to/from a partner outside your local "domain", while an adapter is a carrier of attributes between PingFederate and applications. That is, an IdP adapter is a method to get user attributes to PingFederate (after authentication), and an SP adapter is a method to get attributes from PingFed to an application (after SSO).

Now I want to send the attributes from the custom sp adapter to the
  target resource using post.

This is precisely the role of an adapter. What kind of adapter have you created? One that uses OpenToken? Reference adapter? Something else? If you have created something else, then your adapter is fully responsible for communicating the attributes to the SP Application (Target Resource). If you are using one of the integration kits we provide (like the Java Integration Kit, or the Agentless Integration Kit), we provide comprehensive examples of their use within their SDK directories.

If you are doing it from scratch, your code will be responsible for the entirety. We do have the standard sdk directory in the server install, along with the doc. Sending the attributes received via POST would be done with standard Java methods... You could consider reviewing this method here on StackOverflow:
How to send post form with java?

I would recommend using one of our adapters, frankly, because Ping has done the heavy lifting for you already. Personally, I am a big fan of the agentless integration kit (using the reference adapter), as I feel it is more secure. It captures the attributes sent in by the IdP connection, and then provides the target resource with a "reference". The application then retrieves the attributes from PingFederate by sending that reference to a special endpoint, and gets the attributes in a JSON format. Here is a link to sample Java code for our agentless integration.


问:
Simulink & Masks: Dynamic access to parameters "evaluate" and "tunable"
First of all, matlab version is 2011b, so I cannot use Simulink.MaskParameters class.

I have one simulink mask and some parameters inside. I need to determine in my function for each parameter if it is "evaluable" or "tunable".

Those two things are two checkboxes in the mask parameters dialog which you can select for any parameter.

For "tunable", there's the MaskTunableValues property. For "enable", there's the "MaskEnables" property.

Do you know if there's a way to programmatically access the same property but for "evaluate" ?
Thanks

答:
@Phil Goddard's answer shows you how to find the parameter. To complete the answer, the actual parameter is MaskVariables. Evaluate flag is embedded into the MaskVariables string. It is not straightforward to modify this. For example for two parameters MaskVariables string contains something like this:

```<code>"a=@1;b=&2;"
</code>```

In this string the @ sign indicates evaluation. Based on that, parameter a is evaluated and parameter b is not. If you want to change the evaluate flag, you need to set this string for MaskVariables parameter exactly how it was except for @ or & signs.

For more information see R2011b documentation for mask parameters at https://www.mathworks.com/help/releases/R2011b/toolbox/simulink/slref/f23-18517.html. Towards the bottom of the page there is more detail about MaskVariables parameter.

Body:
@Phil Goddard's answer shows you how to find the parameter. To complete the answer, the actual parameter is MaskVariables. Evaluate flag is embedded into the MaskVariables string. It is not straightforward to modify this. For example for two parameters MaskVariables string contains something like this:

"a=@1;b=&2;"

In this string the @ sign indicates evaluation. Based on that, parameter a is evaluated and parameter b is not. If you want to change the evaluate flag, you need to set this string for MaskVariables parameter exactly how it was except for @ or & signs.

For more information see R2011b documentation for mask parameters at https://www.mathworks.com/help/releases/R2011b/toolbox/simulink/slref/f23-18517.html. Towards the bottom of the page there is more detail about MaskVariables parameter.


问:
jQuery if button is not pressed
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

```<code>$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}
</code>```

Am I doing something wrong?

答:
The code doesn't execute in order like you think. You need to set a timeout to go off after 9000 ms and check if the button has been clicked at that point.

var $btmmdl = $('#btmmdl');

$btmmdl.click(function(){
    $(this).data('clicked', true);
    // Scroll down
});

//If the button hasn't been clicked after 9 seconds, scroll
setTimeout(function(){
  if(!$btmmdl.data('clicked')){
    // Show animation and scroll
  }
}, 9000);```

Title: jQuery if button is not pressed

Body:
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}

Am I doing something wrong?


问:
zone.js:344 Unhandled Promise rejection: Failed to load app.template.html in angular2
app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'cwf',
  templateUrl: './app.template.html'
})
export class AppComponent {
}
</code>```

and in app.template has some text. If add same text as template in typescript file it works. Same thing if add in html and then call the html as template URL it doesnt work.

答:
Adding moduleId: module.id to the @component declaration did the trick for me.

Example for a component located in 'app/login/login.component.ts':

```<code>@Component({
  moduleId: module.id,
  templateUrl: './login.component.html'
</code>```

Body:
app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'cwf',
  templateUrl: './app.template.html'
})
export class AppComponent {
}

and in app.template has some text. If add same text as template in typescript file it works. Same thing if add in html and then call the html as template URL it doesnt work.

Body:
Adding moduleId: module.id to the @component declaration did the trick for me.

Example for a component located in 'app/login/login.component.ts':

@Component({
  moduleId: module.id,
  templateUrl: './login.component.html'


问:
White textures with OpenGL and DevIL on some Windows systems
I'm having some problems trying to load images with DevIL and creating textures in OpenGL. When a friend of mine tested my program on his Windows, all the rects, whom were supposed to contain textures, were white, without any image (texture). The problem seems to occur only on Window XP, Windows Vista and Windows 7, but not in every Windows PC: my Windows XP runs the program without problems.

Maybe there're some missing DLLs or files (improbable), or something that don't let the image to be loaded or used as a texture. By the other hand, the program runs fine on *UNIX systems.

This is the code I'm using to load an image and generate a texture:

```<code>void Image::load(const char* filename)
{
    ILuint ilimg;

    ilGenImages(1, &ilimg);
    ilBindImage(ilimg);

    if (!ilLoadImage(filename))
        throw ImageLoadError;

    glGenTextures(1, &image);
    glBindTexture(GL_TEXTURE_2D, image);

    bpp = ilGetInteger(IL_IMAGE_BPP);
    width = ilGetInteger(IL_IMAGE_WIDTH);
    height = ilGetInteger(IL_IMAGE_HEIGHT);
    format = ilGetInteger(IL_IMAGE_FORMAT);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, bpp, width, height, 0, format,
        GL_UNSIGNED_BYTE, ilGetData());

    ilDeleteImages(1, &ilimg);
}
</code>```

This is the code that draws a rect with the texture applied:

```<code>void Rect::show()
{
    glPushAttrib(GL_CURRENT_BIT);

    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0, 1.0, 1.0, opacity);
    glBindTexture(GL_TEXTURE_2D, texture->get_image());

    glBegin(GL_POLYGON);
        glTexCoord2i(0, 0); glVertex2f(x, y);
        glTexCoord2i(1, 0); glVertex2f(x+width, y);
        glTexCoord2i(1, 1); glVertex2f(x+width, y+height);
        glTexCoord2i(0, 1); glVertex2f(x, y+height);
    glEnd();

    glDisable(GL_TEXTURE_2D);

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

If you need some other code that I don't  mentioned, ask me and i'll post it.

答:
The issue you are experiencing sounds like an implementation version issue. Probably a "correct" but less "nice" implementation isn't letting you get away with something subtly incorrect. Or on the other hand the implementation may have a subtle bug and isn't accepting your valid code.

I might try swapping

```<code>glColor4f(1.0, 1.0, 1.0, opacity);
glBindTexture(GL_TEXTURE_2D, texture->get_image());
</code>```

to

```<code>glBindTexture(GL_TEXTURE_2D, texture->get_image());
glColor4f(1.0, 1.0, 1.0, opacity);
</code>```

and declaring vertex before texcoord like.

```<code>glVertex2f(x, y);
glTexCoord2i(0, 0);
</code>```

Short of that if you do not already have "The Red Book" consult http://glprogramming.com/red/chapter09.html

Body:
I'm having some problems trying to load images with DevIL and creating textures in OpenGL. When a friend of mine tested my program on his Windows, all the rects, whom were supposed to contain textures, were white, without any image (texture). The problem seems to occur only on Window XP, Windows Vista and Windows 7, but not in every Windows PC: my Windows XP runs the program without problems.

Maybe there're some missing DLLs or files (improbable), or something that don't let the image to be loaded or used as a texture. By the other hand, the program runs fine on *UNIX systems.

This is the code I'm using to load an image and generate a texture:

void Image::load(const char* filename)
{
    ILuint ilimg;

    ilGenImages(1, &ilimg);
    ilBindImage(ilimg);

    if (!ilLoadImage(filename))
        throw ImageLoadError;

    glGenTextures(1, &image);
    glBindTexture(GL_TEXTURE_2D, image);

    bpp = ilGetInteger(IL_IMAGE_BPP);
    width = ilGetInteger(IL_IMAGE_WIDTH);
    height = ilGetInteger(IL_IMAGE_HEIGHT);
    format = ilGetInteger(IL_IMAGE_FORMAT);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, bpp, width, height, 0, format,
        GL_UNSIGNED_BYTE, ilGetData());

    ilDeleteImages(1, &ilimg);
}

This is the code that draws a rect with the texture applied:

void Rect::show()
{
    glPushAttrib(GL_CURRENT_BIT);

    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0, 1.0, 1.0, opacity);
    glBindTexture(GL_TEXTURE_2D, texture->get_image());

    glBegin(GL_POLYGON);
        glTexCoord2i(0, 0); glVertex2f(x, y);
        glTexCoord2i(1, 0); glVertex2f(x+width, y);
        glTexCoord2i(1, 1); glVertex2f(x+width, y+height);
        glTexCoord2i(0, 1); glVertex2f(x, y+height);
    glEnd();

    glDisable(GL_TEXTURE_2D);

    glPopAttrib();
}

If you need some other code that I don't  mentioned, ask me and i'll post it.

Body:
The issue you are experiencing sounds like an implementation version issue. Probably a "correct" but less "nice" implementation isn't letting you get away with something subtly incorrect. Or on the other hand the implementation may have a subtle bug and isn't accepting your valid code.

I might try swapping

glColor4f(1.0, 1.0, 1.0, opacity);
glBindTexture(GL_TEXTURE_2D, texture->get_image());

to

glBindTexture(GL_TEXTURE_2D, texture->get_image());
glColor4f(1.0, 1.0, 1.0, opacity);

and declaring vertex before texcoord like.

glVertex2f(x, y);
glTexCoord2i(0, 0);

Short of that if you do not already have "The Red Book" consult http://glprogramming.com/red/chapter09.html

ContentLicense: CC BY-SA 2.5


问:
Python internal string format indexing with range
I would like to use segment of the same string in a formatted string.

input_string = 'abcdefhijk'
result_string = "A's name is abcd-defh; he does hijk"
```

<p>The intuitive solution is</p>

<pre class="lang-python prettyprint-override"><code>"A's name is {0[0:4]}-{0{[3:7]}; he does {0[6:10]}".format(input_string)
</code>```

And this obviously doesn't work.
What works is the round-about way

"A's name is {0}-{1}; he does {2}".format(input_string[0:4], input_string[3:7], input_string[6:10])
```

Is there any easy way to specify the index range in the formatting string?

答:
In Python 3.6, you can make a similar construct to your "intuitive solution" with f-strings:</p>

```<code>>>> input_string = 'abcdefhijk'
>>> f"A's name is {input_string[0:4]}-{input_string[3:7]}; he does {input_string[6:10]}"
"A's name is abcd-defh; he does hijk"
</code>```

Body:
I would like to use segment of the same string in a formatted string.

input_string = 'abcdefhijk'
result_string = "A's name is abcd-defh; he does hijk"

The intuitive solution is

"A's name is {0[0:4]}-{0{[3:7]}; he does {0[6:10]}".format(input_string)

And this obviously doesn't work.
What works is the round-about way

"A's name is {0}-{1}; he does {2}".format(input_string[0:4], input_string[3:7], input_string[6:10])

Is there any easy way to specify the index range in the formatting string?

Body:
In Python 3.6, you can make a similar construct to your "intuitive solution" with f-strings:

>>> input_string = 'abcdefhijk'
>>> f"A's name is {input_string[0:4]}-{input_string[3:7]}; he does {input_string[6:10]}"
"A's name is abcd-defh; he does hijk"


问:
Swap file returns to original size after reboot
I am trying to increase swapfile size on my raspberry pi 3.
I'm following this guide here on DigitalOcean.

After successfully increasing the file and setting it up using mkswap and swpon commands everything works fine. I even tried filling my ram with random data to see if it is going to use the new swap space and it works perfectly.

However after I reboot my raspberry, swap file returns to the previous (default) size of 100MB.
Is there any way to make this change permanent?

I'm running Raspberry pi 3 on Raspbian Jessie.

答:
I figured it out.

Modifying /etc/dphys-swapfile solves all problems.

I just changed CONF_SWAPSIZE=100 to CONF_SWAPSIZE=2000

dphys-swapfile is responsible for setting up, mounting/unmounting and deleting swap files.

In the configuration file you can also specify the location of the swap file as well as few other parameters.


问:
jquery post behaviour help
It's meant to call a Action Method called Logon.
depending on the logic i want it to either redirect to a url, or set some error text.

its getting the right information as json data, but all its doing is displaying the json result in a new tab when i click the submit button.

what is wrong here?

```<code>$("#submit").click(function () {
                $.post({
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error").replaceWith(data.error);
                        }
                    }
                });
</code>```

答:
You need to cancel the default action ...

return false; at the end of the click handler.

```<code>$("#submit").click(function () {
                $.post({
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error").replaceWith(data.error);
                        }
                    }
                });
                return false;
});
</code>```

Title: jquery post behaviour help

Body:
It's meant to call a Action Method called Logon.
depending on the logic i want it to either redirect to a url, or set some error text.

its getting the right information as json data, but all its doing is displaying the json result in a new tab when i click the submit button.

what is wrong here?

$("#submit").click(function () {
                $.post({
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error").replaceWith(data.error);
                        }
                    }
                });

Body:
You need to cancel the default action ...

return false; at the end of the click handler.

$("#submit").click(function () {
                $.post({
                    url: "Account/LogOn",
                    dataType: "json",
                    success: function (data) {
                        if (data.redirect) {
                            // data.redirect contains the string URL to redirect to
                            window.location.href = data.redirect;
                        }
                        else {
                            // data.form contains the HTML for the replacement form
                            $("#error").replaceWith(data.error);
                        }
                    }
                });
                return false;
});


问:
Credit Card separated by comman - Regex - Javascript
I've textfield which is accepting credit card numbers separated by comma(,)

Current Regex I'm using is :

```<code>/(\d{16})(?:,|$)/g
</code>```

This regex allows :

```<code>1. 1234567891234567,1234567891234561,1234567891234564
2. 1234567891234567,1234567891234561,123456 (as well)
</code>```

I need to apply regex which is 16 Digits (No specific Card number criteria but just 16 digits) separated by comma.
No trailing or leading comma.
No number less or greater than 16 digits.
No alphabets or symbol.

Needs Help!

答:
You can use this regex:

```<code>/^\d{16}(?:,\d{16})*$/
</code>```

RegEx Demo

Body:
I've textfield which is accepting credit card numbers separated by comma(,)

Current Regex I'm using is :

/(\d{16})(?:,|$)/g

This regex allows :

1. 1234567891234567,1234567891234561,1234567891234564
2. 1234567891234567,1234567891234561,123456 (as well)

I need to apply regex which is 16 Digits (No specific Card number criteria but just 16 digits) separated by comma.
No trailing or leading comma.
No number less or greater than 16 digits.
No alphabets or symbol.

Needs Help!

Body:
You can use this regex:

/^\d{16}(?:,\d{16})*$/

RegEx Demo


问:
How to deploy a Spring RESTful API on a Debian server?
I built a RESTful api with Spring and it works like a charm in on my computer.
Now, i want to deploy the api on my VPS (Debian 7) but i don't know how to do it !
All tutorials enable on the internet work for eclipse on a windows computer, but not on a real distant server.
I heard that use TomCat will be a good start. However, i'm not confortable with servers.
Could you help me? (Sorry for my A1 english level)

Chill,
RastaPopuloS.

答:
You can create a .war file from your Spring project which can then be deployed on a tomcat server like described here.

Before, you need to install the tomcat application server which is pretty straightforward. E.g. you could follow these instructions here.


问:
Is the type of a function parameter deducible?
I have a class which uses return code:

```<code>class MyClass
{
    // ...

public:
    // ValueType get_value() const;               // usual code
    ErrorCode get_value(ValueType& value) const;  // uses error code

   // ...
};
</code>```

Thus, the second form of get_value() actually provides the value as function parameter, rather than as return value.

Is it possible to deduce the type of the function parameter of get_value(), maybe using  decltype?

```<code>int main()
{
    // ...

    MyClass my_class;
    // auto val = my_class.get_value();  // okay: value has correct type

    declytype( /* something here */ ) value;
    const auto error = my_class.get_value( value );

    // ...
}
</code>```

答:
If you want to deduce the type of parameter, you might use templates to do that:

```<code>namespace detail
{
    template<typename>
    struct Helper;

    template<typename R, typename C, typename T>
    struct Helper <R(C::*)(T)>
    {
        using type = T;
    };
}
</code>```

Then use it like:

```<code>detail::Helper<decltype(&MyClass::get_value)>::type value;
// ...
const auto error = my_class.get_value(value);
</code>```

See related question for more details.

Body:
I have a class which uses return code:

class MyClass
{
    // ...

public:
    // ValueType get_value() const;               // usual code
    ErrorCode get_value(ValueType& value) const;  // uses error code

   // ...
};

Thus, the second form of get_value() actually provides the value as function parameter, rather than as return value.

Is it possible to deduce the type of the function parameter of get_value(), maybe using  decltype?

int main()
{
    // ...

    MyClass my_class;
    // auto val = my_class.get_value();  // okay: value has correct type

    declytype( /* something here */ ) value;
    const auto error = my_class.get_value( value );

    // ...
}

Body:
If you want to deduce the type of parameter, you might use templates to do that:

namespace detail
{
    template<typename>
    struct Helper;

    template<typename R, typename C, typename T>
    struct Helper <R(C::*)(T)>
    {
        using type = T;
    };
}

Then use it like:

detail::Helper<decltype(&MyClass::get_value)>::type value;
// ...
const auto error = my_class.get_value(value);

See related question for more details.


问:
Mutating func with external detection which variable to mutate
I have a struct with 2 variables. This struct has mutating function, but in this function I need to check, which variable to mutate. For this I use separate class' static function with complex logic. This class works with different structs, so for DRY purpose I can't represent this logic in all these structs.

The problem is, that I don't know how to receive the same struct's variable from this separate class, so no struct's variables are mutate. I think, that I miss some Swift knowledge, because I'm sure, that it is possible, without duplicating logic.

Code to represent it in Playground:

```<code>struct SomeStruct {
    var a = "a"
    var b = "b"

    mutating func mutateString(to newString: String) {
        var varToMutate = VariableDetector.whichVarToMutate(a, b)
        varToMutate = newString

        // prints to represent question
        print("varToMutate: \(varToMutate)")
        print("a: \(a)")
        print("b: \(b)")
    }
}

class VariableDetector {
    static func whichVarToMutate(_ first: String, _ second: String) -> String {
        var firstOrSecondString = ""

        // simple logic to represent question, in real case it is far more complex
        if first == "a" {
            firstOrSecondString = first
        } else {
            firstOrSecondString = second
        }

        return firstOrSecondString
    }
}

var someStruct = SomeStruct()
someStruct.mutateString(to: "c")
</code>```

This code produces:

```<code>varToMutate: c
a: a
b: b
</code>```

Yes, it can be solved with:

```<code>if varToMutate == a {
    a = newString
} else if varToMutate == b {
    b = newString
}
</code>```

But I want to solve it in more elegant way :)

Thanks for any help!

答:
In Swift 4, this could be done by returning a KeyPath from whichVarToMutate. The KeyPath could then be used to access into the instance in question, and mutate the property it represents.

In Swift 3, there are 2 approaches I can think of:

Pass a mutator closure to the decider method, which passes out the appropriate var to mutate as an inout param, and then has the closure body mutate it.

Define a protocol that contains these variables (that you said are shared between multiple types), make those types conform to it, and provide an extension on the protocol that defines a method, which will apply to all of them. This is the approach I would use, even in Swift 4:

```<code>struct SomeStruct {
    var a = "a"
    var b = "b"
}

protocol Mutable { // TODO: Rename me appropriately
    var a: String { get set }
    var b: String { get set }
}

extension SomeStruct: Mutable {}

extension Mutable {
    mutating func changeAppropriateVar(to newValue: String) -> Void {
        // simple logic to represent question, in real case it is far more complex
        let someCondition = true

        if someCondition {
            print("Setting `a` to \(newValue)")
            a = newValue
        }
        else {
            print("Setting `b` to \(newValue)")
            b = newValue
        }
    }
}

var s = SomeStruct()
s.changeAppropriateVar(to: "foo")
</code>```

Body:
I have a struct with 2 variables. This struct has mutating function, but in this function I need to check, which variable to mutate. For this I use separate class' static function with complex logic. This class works with different structs, so for DRY purpose I can't represent this logic in all these structs.

The problem is, that I don't know how to receive the same struct's variable from this separate class, so no struct's variables are mutate. I think, that I miss some Swift knowledge, because I'm sure, that it is possible, without duplicating logic.

Code to represent it in Playground:

struct SomeStruct {
    var a = "a"
    var b = "b"

    mutating func mutateString(to newString: String) {
        var varToMutate = VariableDetector.whichVarToMutate(a, b)
        varToMutate = newString

        // prints to represent question
        print("varToMutate: \(varToMutate)")
        print("a: \(a)")
        print("b: \(b)")
    }
}

class VariableDetector {
    static func whichVarToMutate(_ first: String, _ second: String) -> String {
        var firstOrSecondString = ""

        // simple logic to represent question, in real case it is far more complex
        if first == "a" {
            firstOrSecondString = first
        } else {
            firstOrSecondString = second
        }

        return firstOrSecondString
    }
}

var someStruct = SomeStruct()
someStruct.mutateString(to: "c")

This code produces:

varToMutate: c
a: a
b: b

Yes, it can be solved with:

if varToMutate == a {
    a = newString
} else if varToMutate == b {
    b = newString
}

But I want to solve it in more elegant way :)

Thanks for any help!

Body:
In Swift 4, this could be done by returning a KeyPath from whichVarToMutate. The KeyPath could then be used to access into the instance in question, and mutate the property it represents.

In Swift 3, there are 2 approaches I can think of:

Pass a mutator closure to the decider method, which passes out the appropriate var to mutate as an inout param, and then has the closure body mutate it.

Define a protocol that contains these variables (that you said are shared between multiple types), make those types conform to it, and provide an extension on the protocol that defines a method, which will apply to all of them. This is the approach I would use, even in Swift 4:

struct SomeStruct {
    var a = "a"
    var b = "b"
}

protocol Mutable { // TODO: Rename me appropriately
    var a: String { get set }
    var b: String { get set }
}

extension SomeStruct: Mutable {}

extension Mutable {
    mutating func changeAppropriateVar(to newValue: String) -> Void {
        // simple logic to represent question, in real case it is far more complex
        let someCondition = true

        if someCondition {
            print("Setting `a` to \(newValue)")
            a = newValue
        }
        else {
            print("Setting `b` to \(newValue)")
            b = newValue
        }
    }
}

var s = SomeStruct()
s.changeAppropriateVar(to: "foo")


问:
How to get length of array in a i18n-file in JavaScript/angularJS?
My translation file looks like this:

```<code>{
    "RANDOM": [
      {
        "ITEM": "basdf"
      },
      {
        "ITEM": "casdf"
      },
      {
        "ITEM": "dasdf"
      },
      {
        "ITEM": "easdf"
      }
    ]

}
</code>```

I want to randomly display one of the items:

```<code>getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}
</code>```

But whenever I wanted to add a new item in my translation file, I'd also have to manually update sizeOfRandomItems. Is there a way to get the size of the RANDOM array in the translation file?

I alread tried:

```<code>const arraySize = this.$filter('i18n')('RANDOM');
console.log(arraySize.length);
</code>```

But first I get a warning:

```<code>i18n-translate.js:205 Missing key:
</code>```

it returns 6 (which is the number of charachters in the key that holds the array RANDOM)

答:
simplest might be to have an additional item in your translation file giving the current array length - so you could first read that information from translation and use that.

```<code>getQuestion() {
  const sizeOfRandomItems = parseINT(this.$filter('i18n')('RANDOM.LENGTH'), 10);
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}
</code>```

simpler would be if you could load the object from translation file like eg. possible in i18next (https://www.i18next.com/objects-and-arrays.html) - not sure if that is possible in i18n library you use.

Body:
My translation file looks like this:

{
    "RANDOM": [
      {
        "ITEM": "basdf"
      },
      {
        "ITEM": "casdf"
      },
      {
        "ITEM": "dasdf"
      },
      {
        "ITEM": "easdf"
      }
    ]

}

I want to randomly display one of the items:

getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

But whenever I wanted to add a new item in my translation file, I'd also have to manually update sizeOfRandomItems. Is there a way to get the size of the RANDOM array in the translation file?

I alread tried:

const arraySize = this.$filter('i18n')('RANDOM');
console.log(arraySize.length);

But first I get a warning:

i18n-translate.js:205 Missing key:

it returns 6 (which is the number of charachters in the key that holds the array RANDOM)

Body:
simplest might be to have an additional item in your translation file giving the current array length - so you could first read that information from translation and use that.

getQuestion() {
  const sizeOfRandomItems = parseINT(this.$filter('i18n')('RANDOM.LENGTH'), 10);
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

simpler would be if you could load the object from translation file like eg. possible in i18next (https://www.i18next.com/objects-and-arrays.html) - not sure if that is possible in i18n library you use.


问:
Parse a file 2 lines at a time
Python beginner here. I have a file that looks like that (every field is \t separated):

```<code>chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)
</code>```

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

```<code>with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"
</code>```

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

```<code>with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))
</code>```

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

答:
You are right that using csv.reader is a better way to parse the CSV file than doing it by hand. However, you can work with the iterator explicitly, rather than using a for loop, much like you did with the file object.

```<code>with open ('file.txt') as mutmut_mutants:
    reader = csv.reader(mutmut_mutants, delimiter='\t')
    while True:
        try:
            l1 = next(reader)
            l2 = next(reader)
        except StopIteration:
            pass

        # Use l1 and l2 here
</code>```

Title: Parse a file 2 lines at a time

Body:
Python beginner here. I have a file that looks like that (every field is \t separated):

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

Body:
You are right that using csv.reader is a better way to parse the CSV file than doing it by hand. However, you can work with the iterator explicitly, rather than using a for loop, much like you did with the file object.

with open ('file.txt') as mutmut_mutants:
    reader = csv.reader(mutmut_mutants, delimiter='\t')
    while True:
        try:
            l1 = next(reader)
            l2 = next(reader)
        except StopIteration:
            pass

        # Use l1 and l2 here


问:
How would you represent a hashtable collection in a database schema?
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

```<code>public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}
</code>```

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

```<code>table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}
</code>```

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

答:
First, dedicated support for geo-located data exists in many databases - different algorithms can be used (a spatial version of a B-Tree exists for instance), and support for proximity searches probably will exist.

Since you have a different hash table for each SpaceQuadrant, you'd need something like (edited from S.Lott's post):

```<code>table Space {
    SpaceCoordinate,
    Quadrant Foreign Key SpaceQuadrant(ID),
    SpaceObject -- whatever the object is (by ID)
    Primary Key(SpaceCoordinate, Quadrant)
}
</code>```

This is a (SpaceCoordinate, Quadrant) -> SpaceObjectId dictionary.

=====

Now, about your O(1) performance concern, there is a lot of reasons why it's wrongly addressed.

You can use in many DB's a hash index for memory-based tables, as somebody told you. But if you need persistent storage, you'd need to update two tables (the memory one and the persistent one) instead of one (if there is no built-in support for this). To discover whether that's worth, you'd need to benchmark on the actual data (with actual data sizes).

Also, forcing a table into memory can have worse implications.

If something ever gets swapped, you're dead - if you had used a B-Tree (i.e. normal disk-based index), its algorithms would have minimized the needed I/O. Otherwise, all DBMS's would use hash tables and rely on swapping, instead of B-Trees. You can try to anticipate whether you'll fit in memory, but...

Moreover, B-Trees are not O(1) but they are O(log_512(N)), or stuff like that (I know that collapses to O(log N), but bear me on this). You'd need (2^9)^4 = 2^36 = 64GiB for that to be 4, and if you have so much data you'd need a big iron server anyway for that to fit in memory. So, it's almost O(1), and the constant factors are what actually matters.

Ever heard about low-asymptotic-complexity, big-constant-factor algorithms, that would be faster than simple ones just on unpractical data sizes?

Finally, I think DB authors are smarter than me and you. Especially given the declarative nature of SQL, hand-optimizing it this way isn't gonna pay. If an index fits in memory, I guess they could choose to build and use a hashtable version of the disk index, as needed, if it was worth it. Investigate your docs for that.

But the bottom line is that, premature optimization is evil, especially when it's of this kind (weird optimizations we're thinking on our own, as opposed as standard SQL optimizations), and with a declarative language.

Body:
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

Body:
First, dedicated support for geo-located data exists in many databases - different algorithms can be used (a spatial version of a B-Tree exists for instance), and support for proximity searches probably will exist.

Since you have a different hash table for each SpaceQuadrant, you'd need something like (edited from S.Lott's post):

table Space {
    SpaceCoordinate,
    Quadrant Foreign Key SpaceQuadrant(ID),
    SpaceObject -- whatever the object is (by ID)
    Primary Key(SpaceCoordinate, Quadrant)
}

This is a (SpaceCoordinate, Quadrant) -> SpaceObjectId dictionary.

=====

Now, about your O(1) performance concern, there is a lot of reasons why it's wrongly addressed.

You can use in many DB's a hash index for memory-based tables, as somebody told you. But if you need persistent storage, you'd need to update two tables (the memory one and the persistent one) instead of one (if there is no built-in support for this). To discover whether that's worth, you'd need to benchmark on the actual data (with actual data sizes).

Also, forcing a table into memory can have worse implications.

If something ever gets swapped, you're dead - if you had used a B-Tree (i.e. normal disk-based index), its algorithms would have minimized the needed I/O. Otherwise, all DBMS's would use hash tables and rely on swapping, instead of B-Trees. You can try to anticipate whether you'll fit in memory, but...

Moreover, B-Trees are not O(1) but they are O(log_512(N)), or stuff like that (I know that collapses to O(log N), but bear me on this). You'd need (2^9)^4 = 2^36 = 64GiB for that to be 4, and if you have so much data you'd need a big iron server anyway for that to fit in memory. So, it's almost O(1), and the constant factors are what actually matters.

Ever heard about low-asymptotic-complexity, big-constant-factor algorithms, that would be faster than simple ones just on unpractical data sizes?

Finally, I think DB authors are smarter than me and you. Especially given the declarative nature of SQL, hand-optimizing it this way isn't gonna pay. If an index fits in memory, I guess they could choose to build and use a hashtable version of the disk index, as needed, if it was worth it. Investigate your docs for that.

But the bottom line is that, premature optimization is evil, especially when it's of this kind (weird optimizations we're thinking on our own, as opposed as standard SQL optimizations), and with a declarative language.

OwnerDisplayName: Blaisorblade


问:
How to protect html form from spammers?
I'm getting problems with spam entries in my database through signup form.
I have tried many open source Captcha solution, but still facing same problem.

I am therefore looking for an alternative solution. What about the solution, where users would have to input the answer to a question? The answer to the question will be a server-side specific word then would this surely defeat a spambot?

Would it be better to have a series of simple randomized questions or something like "6 + ? = 9" be better as a question? The only thing that concerns me is that if it's as easy as this to protect a signup then why aren't the big giant like Facebook doing this?

答:
Update:   The answer was accepted because I recommended KeyCAPTCHA. From my hard-earned painful expereince, KeyCAPTCHA is a scam by professional spammers. I removed my recommendations of KeyCAPTCHA

Note that most professional spambots are integrated with sweatshops (1 USD a 1000 solutions) human captcha solvers API. When a spambot cannot pass captcha itself it (spam bot), keeping hundreds of open connections, sends screenshot (or webpage code) with CAPTCHA for solving by sweatshop human. This is legal and big business. In order to be legal and integrate with bots through APIs the human solvers can not directly interact with cracked web boards (blog comments, registration pages, chats, wiki, forums, etc.).

Another problem is that anti-spam programs cannot detect context-based spamming by professionally made bot. There are many approaches. The simplest one is web scraping multi-author human dialogs from other web boards  and posting them CONTEXT-SENSITIVELY (bots can detect topics) from different IP addresses of different countries at different times, so even (a weblog) owner (human) cannot detect that dialogs are posted by bots(they are really from stored in database human dialogs).

This is only the matter of interest to your website from professional spammers or time+qualified persistence of amateurs to automatically circumvent most (if not all) CAPTCHAs.

Title: How to protect html form from spammers?


问:
Android onFling not responding
I am new to android first of all so think of any newbie mistakes first

I am trying to add a fling function in my code.

```<code>public class MainGamePanel extends SurfaceView implements
    SurfaceHolder.Callback, OnGestureListener {

private MainThread thread;
private Droid droid;
private Droid droid2;
private static final String TAG = gameView.class.getSimpleName();
private GestureDetector gestureScanner;

public MainGamePanel(Context context){
        super(context);
        getHolder().addCallback(this);
        droid = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.playerbox2), 270, 300);
        droid2 = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.playerbox2), 50, 300);
        thread = new MainThread(getHolder(), this);
        setFocusable(true);
        gestureScanner = new GestureDetector(this);
}

    public boolean onTouchEvent(MotionEvent event){
    return gestureScanner.onTouchEvent(event);
}

@Override
protected void onDraw(Canvas canvas){
    canvas.drawColor(Color.BLACK);
    droid.draw(canvas);
    droid2.draw(canvas);
}

@Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float                         velocityY)
    {
         droid.setX(50);
        droid.setY(50);
        Log.d(TAG, "Coords: x=" + e1.getX() + ",y=" + e2.getY());
        return true;
    }

@Override
public boolean onDown(MotionEvent e) {
    droid2.setX((int)e.getX());
    droid2.setY((int)e.getY());

    Log.d(TAG, "Coords: x=" + e.getX() + ",y=" + e.getY());
    return false;
}
</code>```

I got the gestureListener to work with: onDown, onLongPress, and onShowPress.

But i can't get any response with onFling, onSingleTapUp, and onScroll.

What mistake am I making? does it have to do with views?

I don't know what code would be useful to see.... so any suggestions would be much appreciated.
Thank You!

答:
I tried the return value of onDown method to true, it didn't work.
then i set
    ll_action_menu.setLongClickable(true);

it worked

Title: Android onFling not responding

Body:
I am new to android first of all so think of any newbie mistakes first

I am trying to add a fling function in my code.

public class MainGamePanel extends SurfaceView implements
    SurfaceHolder.Callback, OnGestureListener {

private MainThread thread;
private Droid droid;
private Droid droid2;
private static final String TAG = gameView.class.getSimpleName();
private GestureDetector gestureScanner;

public MainGamePanel(Context context){
        super(context);
        getHolder().addCallback(this);
        droid = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.playerbox2), 270, 300);
        droid2 = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.playerbox2), 50, 300);
        thread = new MainThread(getHolder(), this);
        setFocusable(true);
        gestureScanner = new GestureDetector(this);
}

    public boolean onTouchEvent(MotionEvent event){
    return gestureScanner.onTouchEvent(event);
}

@Override
protected void onDraw(Canvas canvas){
    canvas.drawColor(Color.BLACK);
    droid.draw(canvas);
    droid2.draw(canvas);
}

@Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float                         velocityY)
    {
         droid.setX(50);
        droid.setY(50);
        Log.d(TAG, "Coords: x=" + e1.getX() + ",y=" + e2.getY());
        return true;
    }

@Override
public boolean onDown(MotionEvent e) {
    droid2.setX((int)e.getX());
    droid2.setY((int)e.getY());

    Log.d(TAG, "Coords: x=" + e.getX() + ",y=" + e.getY());
    return false;
}

I got the gestureListener to work with: onDown, onLongPress, and onShowPress.

But i can't get any response with onFling, onSingleTapUp, and onScroll.

What mistake am I making? does it have to do with views?

I don't know what code would be useful to see.... so any suggestions would be much appreciated.
Thank You!


问:
How do I assign a large number to a value?
I am struggling to assign a long number to a value.

```<code>let cardNumber = 1234567891234567
</code>```

I receive the following error:

This number is outside the allowable range for 32-bit signed

I then tried:

```<code>let cardNumber = (int64 1234567891234567)
</code>```

However, I get the same error.

I'm referencing the following documentation.
However, I am unaware of what I need to do to make the compiler happy.

答:
Being a strongly-typed language, F# requires all literals to have an explicit type.  Numbers without a decimal point which don't have a suffix are considered to be 32 bit integer literals.

In your case, that means 1234567891234567 is a 32 bit integer literal, and as you've noted, 32 bit integers can't be that large.  To tell the compiler that you want it to be a 64-bit integer literal, you need to put an 'L' after it like this:

```<code>let cardNumber = 1234567891234567L
</code>```

See https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/literals for how to declare different types of literals.

Body:
I am struggling to assign a long number to a value.

let cardNumber = 1234567891234567

I receive the following error:

This number is outside the allowable range for 32-bit signed

I then tried:

let cardNumber = (int64 1234567891234567)

However, I get the same error.

I'm referencing the following documentation.
However, I am unaware of what I need to do to make the compiler happy.

Body:
Being a strongly-typed language, F# requires all literals to have an explicit type.  Numbers without a decimal point which don't have a suffix are considered to be 32 bit integer literals.

In your case, that means 1234567891234567 is a 32 bit integer literal, and as you've noted, 32 bit integers can't be that large.  To tell the compiler that you want it to be a 64-bit integer literal, you need to put an 'L' after it like this:

let cardNumber = 1234567891234567L

See https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/literals for how to declare different types of literals.


问:
Update Transients instead of insert new Transients in wordpress
How to update transient instead of insert new transient in wordpress?

Because After expiration Must be cleared Transients.

答:
For this need to save date of end in transient value.

Example:

```<code>//on create
$expiration = 60*60*12;
$time_to_end = time() + $expiration;
set_transient(
  'transient_name',
  array('value'=>'some_data', 'end_time'=>$time_to_end),
  $expiration
);

//for update
$previous = get_transient( 'transient_name');
$expiration = $previous['end_time'] -  time();
if ( $expiration > 0 ){
set_transient(
  'transient_name',
  array('value'=>'some_new_data', 'end_time'=>$previous['end_time'] ),
  $expiration
);
}
</code>```

Body:
For this need to save date of end in transient value.

Example:

//on create
$expiration = 60*60*12;
$time_to_end = time() + $expiration;
set_transient(
  'transient_name',
  array('value'=>'some_data', 'end_time'=>$time_to_end),
  $expiration
);

//for update
$previous = get_transient( 'transient_name');
$expiration = $previous['end_time'] -  time();
if ( $expiration > 0 ){
set_transient(
  'transient_name',
  array('value'=>'some_new_data', 'end_time'=>$previous['end_time'] ),
  $expiration
);
}


问:
how to show json data in the data table using ajax call in mvc
I want to show JSON data in the datatable. getting JSON from API but unable to show in the table. I have 4 columns in the table but I want to show only 3 cols in the table.data table working with my this c# code

```<code>return Json(new { data=data }, JsonRequestBehavior.AllowGet);
</code>```

but not working with this code

```<code>return Json(data.Select(d => new { sms=d.sms,id= d.id,updtd_date = d.updtd_date.ToString()}).ToList(), JsonRequestBehavior.AllowGet);
</code>```

error

```<code>XML Parsing Error: no root element found Location:
</code>```

JSON sample data.

```<code>[{"sms":"Alert: Tank is Full","id":1027,"updtd_date":"7/6/2017 6:39:45 AM"},...]
</code>```

AJAX call

```<code>   $(document).ready(function () {
            $('#myTable').DataTable({
                "ajax": {
                    "url": "/WaterLevel/getSMS",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns" : [
                    { "data": "updtd_date", "autoWidth": true },
                    { "data": "id", "autoWidth": true },
                    { "data": "sms", "autoWidth": true }
                    ]
            });
        });
    </script>
</code>```

答:
Updated the Ajax call. </p>

```<code>       $(document).ready(function () {
                $('#myTable').DataTable({
                    "ajax": {
               "dataType": 'json',
               "contentType": "application/json; charset=utf-8",
               "type": "GET",
               "url":"/WaterLevel/getSMS",
               "dataSrc": function (json) {
                return $.parseJSON(json);
                                 }

                    },
                    "columns" : [
                        { "data": "updtd_date", "autoWidth": true },
                        { "data": "id", "autoWidth": true },
                        { "data": "sms", "autoWidth": true }
                        ]
                });
            });
        </script>
</code>```

Body:
I want to show JSON data in the datatable. getting JSON from API but unable to show in the table. I have 4 columns in the table but I want to show only 3 cols in the table.data table working with my this c# code

return Json(new { data=data }, JsonRequestBehavior.AllowGet);

but not working with this code

return Json(data.Select(d => new { sms=d.sms,id= d.id,updtd_date = d.updtd_date.ToString()}).ToList(), JsonRequestBehavior.AllowGet);

error

XML Parsing Error: no root element found Location:

JSON sample data.

[{"sms":"Alert: Tank is Full","id":1027,"updtd_date":"7/6/2017 6:39:45 AM"},...]

AJAX call

   $(document).ready(function () {
            $('#myTable').DataTable({
                "ajax": {
                    "url": "/WaterLevel/getSMS",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns" : [
                    { "data": "updtd_date", "autoWidth": true },
                    { "data": "id", "autoWidth": true },
                    { "data": "sms", "autoWidth": true }
                    ]
            });
        });
    </script>

Body:
Updated the Ajax call.

       $(document).ready(function () {
                $('#myTable').DataTable({
                    "ajax": {
               "dataType": 'json',
               "contentType": "application/json; charset=utf-8",
               "type": "GET",
               "url":"/WaterLevel/getSMS",
               "dataSrc": function (json) {
                return $.parseJSON(json);
                                 }

                    },
                    "columns" : [
                        { "data": "updtd_date", "autoWidth": true },
                        { "data": "id", "autoWidth": true },
                        { "data": "sms", "autoWidth": true }
                        ]
                });
            });
        </script>


问:
grouping data by multiple columns
I have many records of data to group by columns names.

```<code>Name  Surname  value
al     adams    120
al     adams    514
al     bats     220
al     bats     120
bill   cox      440
bill   cox      320
bill   brit     320
</code>```

I want to group by Name and Surname (and keep them), with the sum of Value.
here is my code. I don't get the desired display.

```<code>DT<-base_AA_P1 %>%  select(Name, Surname) %>% group_by(Name, Surname) %>%  summarize(SUM_value = sum(value, na.rm = TRUE))
</code>```

答:
Try this :

```<code>data = data.frame(Name = c("al","al","al","al","bill","bill","bill"),
                  Surname = c("adams","adams","bats","bats","cox","cox","brit"),
                  value = c(120,514,220,120,440,320,320))

library(dplyr)

data2 = data %>%
  group_by(Name,Surname)%>%
  summarise(new_value = sum(value))

data2

    Name Surname new_value
1     al   adams       634
2     al    bats       340
3   bill    brit       320
4   bill     cox       760
</code>```

I think that if you select name and surname you will not have the sum of values in the final data you want.

Title: grouping data by multiple columns

Body:
I have many records of data to group by columns names.

Name  Surname  value
al     adams    120
al     adams    514
al     bats     220
al     bats     120
bill   cox      440
bill   cox      320
bill   brit     320

I want to group by Name and Surname (and keep them), with the sum of Value.
here is my code. I don't get the desired display.

DT<-base_AA_P1 %>%  select(Name, Surname) %>% group_by(Name, Surname) %>%  summarize(SUM_value = sum(value, na.rm = TRUE))

Body:
Try this :

data = data.frame(Name = c("al","al","al","al","bill","bill","bill"),
                  Surname = c("adams","adams","bats","bats","cox","cox","brit"),
                  value = c(120,514,220,120,440,320,320))

library(dplyr)

data2 = data %>%
  group_by(Name,Surname)%>%
  summarise(new_value = sum(value))

data2

    Name Surname new_value
1     al   adams       634
2     al    bats       340
3   bill    brit       320
4   bill     cox       760

I think that if you select name and surname you will not have the sum of values in the final data you want.


问:
Can I get the full path to the file in PhpStorm Code Templates?
When I create a Code Template in PhpStorm, is there a way in the template (or in an include) to get the full path to the file that is about to be created?

For example, I know you can use ${FILE_NAME} to get the name of the file, but is there also something like ${PATH} or something? Or can I do something like this myself?

答: There are no predefined template variables for file path, please vote for IDEA-136387 to be notified on any progress with this feature.</p>


问:
Render multiple of the same React component, which can render multiple of another component?
I'm creating a budget app in React.js, where my parent component has an Overall Balance, and one can create any number of specific "Budget" components (say, Vacations) , from which one can create any number of "Entry" components (say, I'll spend x number of dollars in San Francisco). My initial thought was that the parent can have an array of "Budget" components in its state that can keep growing and changing, and the Budget component can have an array of "Entry" components in its state and that can keep growing as well. However, I realize that this is bad practice because only one component should have state.

What is the best way to manage both my Budgets and their entries in the parent component, given that anyone should be able to go back and change the number of entries in any previously created budget?

Thanks for your help, and I'm sorry if this is confusing!

答:
Yep, I think you're on the right track with the "only one component should have the state" idea. The commenter on your question is right that state can be put anywhere in the component tree in React - and that's often what you do with state related to the UI (e.g. is this button selected or not). But when it comes to application state, i.e. the data that your app is rendering, it's usually convenient to put it all in one place.

Just think about the pure data structure at first, don't worry about React.

It's probably going to end up looking like an array of budget objects, and inside each of those budget objects there's an array of entries:

```<code>[
  {
    title: 'Vacations',
    entries: [
      {
        spent: 10,
        place: 'San Francisco',
        ...
      },
      ...
    ],
  },
  ...
]
</code>```

Then when it comes to React you'll want to put that state in a main <App /> component. The responsibility of <App /> will be to render a list of <Budget /> components. Each one of those budget components will get it's data and entries passed into it as props. So something like,

```<code>class App extends Component {
  constructor () {
    this.state = {
      budgets: [... as above ...]
    }
  }

  render () {
    const { budgets } = this.state
    return (
      <div>
        {this.state.budgets.map(budget => {
          <Budget key={budget.title} {...budget} />
        })}
      </div>
    )
  }
}
</code>```

Inside <Budget /> you can render the array of <Entry /> components in a similar way since each <Budget /> will receive an entries array as a prop.

In terms of changing data, as long as you pass down handlers from <App /> into the child components, and those handlers call setState() inside <App /> to make changes to the budgets data then your app will react to those changes and re-render from top to bottom.

Body:
Yep, I think you're on the right track with the "only one component should have the state" idea. The commenter on your question is right that state can be put anywhere in the component tree in React - and that's often what you do with state related to the UI (e.g. is this button selected or not). But when it comes to application state, i.e. the data that your app is rendering, it's usually convenient to put it all in one place.

Just think about the pure data structure at first, don't worry about React.

It's probably going to end up looking like an array of budget objects, and inside each of those budget objects there's an array of entries:

[
  {
    title: 'Vacations',
    entries: [
      {
        spent: 10,
        place: 'San Francisco',
        ...
      },
      ...
    ],
  },
  ...
]

Then when it comes to React you'll want to put that state in a main <App /> component. The responsibility of <App /> will be to render a list of <Budget /> components. Each one of those budget components will get it's data and entries passed into it as props. So something like,

class App extends Component {
  constructor () {
    this.state = {
      budgets: [... as above ...]
    }
  }

  render () {
    const { budgets } = this.state
    return (
      <div>
        {this.state.budgets.map(budget => {
          <Budget key={budget.title} {...budget} />
        })}
      </div>
    )
  }
}

Inside <Budget /> you can render the array of <Entry /> components in a similar way since each <Budget /> will receive an entries array as a prop.

In terms of changing data, as long as you pass down handlers from <App /> into the child components, and those handlers call setState() inside <App /> to make changes to the budgets data then your app will react to those changes and re-render from top to bottom.


问:
Adding textbox which has an onkeyup event and display value on other textbox
I want to get the sum of the textbox which has an onkeyup event. units multiplied by grades and display its sum to the third textbox which is the a and b, after that I want to add the a and b and display the sum on the total textbox.

But it's not displaying the sum on the total textbox. I think the problem is on the onkeyup="s();">.

This is my code:

function suma(){
var unitsA = document.getElementById('unitsA').value;
var gradesA = document.getElementById('gradesA').value;
var result = parseInt(unitsA)  * parseInt(gradesA);
if (!isNaN(result)) {
document.getElementById('a').value = result;
}
}

function sumb(){
var unitsB = document.getElementById('unitsB').value;
var gradeB = document.getElementById('gradeB').value;
var result = parseInt(unitsB)  * parseInt(gradeB);
if (!isNaN(result)) {
document.getElementById('b').value = result;
}
}
function s(){
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var result = parseInt(a)  + parseInt(b);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"  id="unitsA"/>
<input type="text"  id="gradeA"  onkeyup="suma();"/>
<input type="text"  id="a" name="a" size="7" onkeyup="s();"/>

<input type="text"  id="unitsB"/>
<input type="text"  id="gradeB"  onkeyup="sumb();"/>
<input type="text"  id="b" name="b" size="7" onkeyup="s();"/>
<input type="text"  id="total" readonly="readonly" /></code>```

答:
Your code has some typos and issues here is the solved solution.

function suma() {
  var unitsA = document.getElementById('unitsA').value;
  var gradesA = document.getElementById('gradeA').value;
  var result = parseInt(unitsA) * parseInt(gradesA);
  if (!isNaN(result)) {
    document.getElementById('a').value = result;
    document.getElementById('a').dispatchEvent(new Event('change'));
  }
}

function sumb() {
  var unitsB = document.getElementById('unitsB').value;
  var gradeB = document.getElementById('gradeB').value;
  var result = parseInt(unitsB) * parseInt(gradeB);
  if (!isNaN(result)) {
    document.getElementById('b').value = result;
    document.getElementById('b').dispatchEvent(new Event('change'));
  }
}

function s() {
  var a = document.getElementById('a').value;
  var b = document.getElementById('b').value;
  var result = parseInt(a) + parseInt(b);
  if (!isNaN(result)) {
    document.getElementById('total').value = result;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="unitsA" />
<input type="text" id="gradeA" onkeyup="suma();" />
<input type="text" id="a" name="a" size="7" onchange="s()" />

<input type="text" id="unitsB" />
<input type="text" id="gradeB" onkeyup="sumb();" />
<input type="text" id="b" name="b" size="7" onchange="s()" />
<input type="text" id="total" readonly="readonly" /></code>```

Body:
I want to get the sum of the textbox which has an onkeyup event. units multiplied by grades and display its sum to the third textbox which is the a and b, after that I want to add the a and b and display the sum on the total textbox.

But it's not displaying the sum on the total textbox. I think the problem is on the onkeyup="s();">.

This is my code:

function suma(){
var unitsA = document.getElementById('unitsA').value;
var gradesA = document.getElementById('gradesA').value;
var result = parseInt(unitsA)  * parseInt(gradesA);
if (!isNaN(result)) {
document.getElementById('a').value = result;
}
}

function sumb(){
var unitsB = document.getElementById('unitsB').value;
var gradeB = document.getElementById('gradeB').value;
var result = parseInt(unitsB)  * parseInt(gradeB);
if (!isNaN(result)) {
document.getElementById('b').value = result;
}
}
function s(){
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var result = parseInt(a)  + parseInt(b);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}

<input type="text"  id="unitsA"/>
<input type="text"  id="gradeA"  onkeyup="suma();"/>
<input type="text"  id="a" name="a" size="7" onkeyup="s();"/>

<input type="text"  id="unitsB"/>
<input type="text"  id="gradeB"  onkeyup="sumb();"/>
<input type="text"  id="b" name="b" size="7" onkeyup="s();"/>
<input type="text"  id="total" readonly="readonly" />

Body:
Your code has some typos and issues here is the solved solution.

function suma() {
  var unitsA = document.getElementById('unitsA').value;
  var gradesA = document.getElementById('gradeA').value;
  var result = parseInt(unitsA) * parseInt(gradesA);
  if (!isNaN(result)) {
    document.getElementById('a').value = result;
    document.getElementById('a').dispatchEvent(new Event('change'));
  }
}

function sumb() {
  var unitsB = document.getElementById('unitsB').value;
  var gradeB = document.getElementById('gradeB').value;
  var result = parseInt(unitsB) * parseInt(gradeB);
  if (!isNaN(result)) {
    document.getElementById('b').value = result;
    document.getElementById('b').dispatchEvent(new Event('change'));
  }
}

function s() {
  var a = document.getElementById('a').value;
  var b = document.getElementById('b').value;
  var result = parseInt(a) + parseInt(b);
  if (!isNaN(result)) {
    document.getElementById('total').value = result;
  }
}

<input type="text" id="unitsA" />
<input type="text" id="gradeA" onkeyup="suma();" />
<input type="text" id="a" name="a" size="7" onchange="s()" />

<input type="text" id="unitsB" />
<input type="text" id="gradeB" onkeyup="sumb();" />
<input type="text" id="b" name="b" size="7" onchange="s()" />
<input type="text" id="total" readonly="readonly" />


问:
Delphi 2007 DBX Access Violation in dbxmys30.dll
I'm trying to use the dbexpress components in Delphi 2007 to connect to a MySQL database but getting an error the reads "Access violation at address 0B86E258 in module 'dbxmys30.dll'. Read of address 00000000".

I have a TSQLConnection using the MySQL drivers and setup to connect to a MySQL 5.1 database. I can set it to active without a problem.

The problem arises when I try to get data from the database using any number of components. To be more specific, I have a TSQLTable object. I set the SQLConnection parameter to the TSQLConnection I created and set table name to a table in my database. When I try to set Active to true I get the error. This happens in design mode as well as at runtime. It will also happen with any other dbx component that try to get data from the database.

I'm running Windows 7 64 bit with a MySQL 5.1 client and server. I can run queries on the database using MySQL Query Browser without any issues.

Any Help would be much appreciated. Thanks!

答:
You have a version incompatibility, the version of 'libmysql.dll' you're using is incompatible with the version that the dbx driver is built against. This thread on embarcadero forums suggests to use version '5.0.27' and this thread suggests '5.0.24'. The latest version I had success was '5.1.11'.

BTW, because 'libmysql.dll' contains no version info, I was fed up with keeping track of which dll was which version and I had to wrote this little thing:

```<code>type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormPaint(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FLastFile: string;
    procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  shellapi;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  DragAcceptFiles(Handle, True);
  Width := 350;
  Height := 110;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  DragAcceptFiles(Handle, False);
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  R: TRect;
begin
  Canvas.TextOut(40, 16, 'Drop libmysql.dll to find out version');
  R := Rect(14, 40, ClientWidth, ClientHeight);
  DrawText(Canvas.Handle, PChar(FLastFile), Length(FLastFile), R, DT_LEFT);
end;

function GetVersion(ClientDll: PChar): UINT;
const
  FUNC          = 'mysql_get_client_version';
  FUNCTIONNOTFOUND = '%s: ''%s'' in ''%s''.';
  UNABLETOLOADLIB  = 'Unable to load library (''%s''): ''%s''.';
var
  LibHandle: HMODULE;
  GetClientVersionFunc: function: Integer;
begin
  Result := 0;
  LibHandle := LoadLibrary(ClientDll);
  if LibHandle <> 0 then begin
    try
      @GetClientVersionFunc := GetProcAddress(LibHandle, FUNC);
      if @GetClientVersionFunc <> nil then begin
        Result := GetClientVersionFunc;
      end else
        raise EOSError.CreateFmt(FUNCTIONNOTFOUND,
            [SysErrorMessage(GetLastError), FUNC, ClientDll]);
    finally
      FreeLibrary(LibHandle);
    end;
  end else
    raise EOSError.CreateFmt(UNABLETOLOADLIB, [ClientDll,
        SysErrorMessage(GetLastError)]);
end;

procedure TForm1.WMDropFiles(var Msg: TWMDropFiles);
var
  len: Integer;
  DropName: string;
  Ver: UINT;
begin
  len := DragQueryFile(Msg.Drop, 0, nil, 0) + 1;
  SetLength(DropName, len);
  len := DragQueryFile(Msg.Drop, 0, PChar(DropName), len);
  SetLength(DropName, len);
  try
    try
      Ver := GetVersion(PChar(DropName));
    except
      FLastFile := '';
      raise;
    end;
    if Boolean(Ver) then
      FLastFile := DropName + #10 +'[' + IntToStr(Ver) + ']  -  ' +
          IntToStr(Ver div 10000) + '.' + IntToStr((Ver div 100) mod 100)
          + '.' + IntToStr(Ver mod 100)
    else
      FLastFile := '';
  finally
    Invalidate;
    DragFinish(Msg.Drop);
    Msg.Result := 0;
  end;
end;
</code>```

Body:
You have a version incompatibility, the version of 'libmysql.dll' you're using is incompatible with the version that the dbx driver is built against. This thread on embarcadero forums suggests to use version '5.0.27' and this thread suggests '5.0.24'. The latest version I had success was '5.1.11'.

BTW, because 'libmysql.dll' contains no version info, I was fed up with keeping track of which dll was which version and I had to wrote this little thing:

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormPaint(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FLastFile: string;
    procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  shellapi;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  DragAcceptFiles(Handle, True);
  Width := 350;
  Height := 110;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  DragAcceptFiles(Handle, False);
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  R: TRect;
begin
  Canvas.TextOut(40, 16, 'Drop libmysql.dll to find out version');
  R := Rect(14, 40, ClientWidth, ClientHeight);
  DrawText(Canvas.Handle, PChar(FLastFile), Length(FLastFile), R, DT_LEFT);
end;

function GetVersion(ClientDll: PChar): UINT;
const
  FUNC          = 'mysql_get_client_version';
  FUNCTIONNOTFOUND = '%s: ''%s'' in ''%s''.';
  UNABLETOLOADLIB  = 'Unable to load library (''%s''): ''%s''.';
var
  LibHandle: HMODULE;
  GetClientVersionFunc: function: Integer;
begin
  Result := 0;
  LibHandle := LoadLibrary(ClientDll);
  if LibHandle <> 0 then begin
    try
      @GetClientVersionFunc := GetProcAddress(LibHandle, FUNC);
      if @GetClientVersionFunc <> nil then begin
        Result := GetClientVersionFunc;
      end else
        raise EOSError.CreateFmt(FUNCTIONNOTFOUND,
            [SysErrorMessage(GetLastError), FUNC, ClientDll]);
    finally
      FreeLibrary(LibHandle);
    end;
  end else
    raise EOSError.CreateFmt(UNABLETOLOADLIB, [ClientDll,
        SysErrorMessage(GetLastError)]);
end;

procedure TForm1.WMDropFiles(var Msg: TWMDropFiles);
var
  len: Integer;
  DropName: string;
  Ver: UINT;
begin
  len := DragQueryFile(Msg.Drop, 0, nil, 0) + 1;
  SetLength(DropName, len);
  len := DragQueryFile(Msg.Drop, 0, PChar(DropName), len);
  SetLength(DropName, len);
  try
    try
      Ver := GetVersion(PChar(DropName));
    except
      FLastFile := '';
      raise;
    end;
    if Boolean(Ver) then
      FLastFile := DropName + #10 +'[' + IntToStr(Ver) + ']  -  ' +
          IntToStr(Ver div 10000) + '.' + IntToStr((Ver div 100) mod 100)
          + '.' + IntToStr(Ver mod 100)
    else
      FLastFile := '';
  finally
    Invalidate;
    DragFinish(Msg.Drop);
    Msg.Result := 0;
  end;
end;


问:
Add class to empty elements only
The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

```<code>if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}
</code>```

答:
You can use the :empty selector directly and remove the if statement, like this:

```<code>$('.Prodotto:empty').addClass('empty-content');
</code>```

Title: Add class to empty elements only

Body:
The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}

Body:
You can use the :empty selector directly and remove the if statement, like this:

$('.Prodotto:empty').addClass('empty-content');


问:
Spring Boot - Get controller method name
How can I get the called method name of a controller class in a custom authentication provider?

A REST request is calling a controller method, this request is authenticated in a custom authentication provider. How can I get the method name of the controller class in the provider?

Here is my controller method:

```<code>@RequestMapping(value = "/customer", method = RequestMethod.GET)
@ResponseBody
public String getAllCustomers() {
    return "Get customers...";
}
</code>```

Thats my custom authentication provider, I would like to get the name of the called controller method here:

```<code>@Component
public class CustomAuthProvider implements AuthenticationProvider {

@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

// ...
// get controller method here... -> getAllCustomers

return UsernamePasswordToken(username, password)
}
</code>```

My authentication provider is configured by a class, which extends the WebSecurityConfigurerAdapter class.

```<code>@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthProvider customAuthProvider;

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(this.customAuthProvider);

    }
</code>```

The custom auth provider returns an object of the class CustomAuthToken, which extedns the UsernamePasswordAuthenticationToken. I am not calling authenticationManager.authenticate(new MyCustomAuthenticationToken(....));

答:
Extend RequestMappingHandlerMapping and track the method

```<code>protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    RequestMappingInfo info = super.getMappingForMethod(method, handlerType);

    return info;
}
</code>```

The RequestMappingInfo keeps path(s) for the method. Just store the info in a map to be used in your provider. The RequestMappingHandlerMapping could be autowired.

See How to optimize my code in Spring MVC Controller using @RequestMapping?

Body:
How can I get the called method name of a controller class in a custom authentication provider?

A REST request is calling a controller method, this request is authenticated in a custom authentication provider. How can I get the method name of the controller class in the provider?

Here is my controller method:

@RequestMapping(value = "/customer", method = RequestMethod.GET)
@ResponseBody
public String getAllCustomers() {
    return "Get customers...";
}

Thats my custom authentication provider, I would like to get the name of the called controller method here:

@Component
public class CustomAuthProvider implements AuthenticationProvider {

@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

// ...
// get controller method here... -> getAllCustomers

return UsernamePasswordToken(username, password)
}

My authentication provider is configured by a class, which extends the WebSecurityConfigurerAdapter class.

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthProvider customAuthProvider;

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(this.customAuthProvider);

    }

The custom auth provider returns an object of the class CustomAuthToken, which extedns the UsernamePasswordAuthenticationToken. I am not calling authenticationManager.authenticate(new MyCustomAuthenticationToken(....));

Body:
Extend RequestMappingHandlerMapping and track the method

protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    RequestMappingInfo info = super.getMappingForMethod(method, handlerType);

    return info;
}

The RequestMappingInfo keeps path(s) for the method. Just store the info in a map to be used in your provider. The RequestMappingHandlerMapping could be autowired.

See How to optimize my code in Spring MVC Controller using @RequestMapping?


问:
Pasting text that triggers the scroll leaves cursor in visually the wrong location
See what I mean by going here: https://codemirror.net/demo/indentwrap.html

Paste in something large enough to trigger scrollbar, you may need to remove existing text first:

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

The cursor will appear not in the correct location until you type or move it. Has anyone seen this or know of a solution or workaround?

Edit:

If I put listeners for pasting and do a refresh() and scrollIntoView() it seems to work most of the time... but doesnt always seem effective if I'm posting between content for some reason.

答:
Although it has the small side affect of always having a 17px padding on the right side... adding padding-right: 17px !important to .CodeMirror-sizer seems to fix the problem.

The problem seems to have been caused by when the scrollbar appears, it makes the scrollbar visible, and also adds the 17px right padding to the sizer (so the text doesn't run under the scrollbar). The cursor appears to be positioned based on if that padding was never added until the user types or does something that would move the cursor. By always having that right padding, we don't run into this problem.

The small side affect doesn't matter much to me so I'm happy with this workaround, however... if someone else finds a better solution I'd like to see it.


答:
Generally, I think what you're trying to do is

```<code>$('.Prodotto:empty').addClass('empty-content');
</code>```

But when you say the "Current .Prodotto", it implies there is something else in your code which makes it the "current" one, like having clicked on it, and if so your code is similar to your existing, except using this

```<code>$('.Prodotto').on('click',function(){
    var $this = $(this);
    if ($this.is(':empty')){
        $this.addClass('empty-content');
    }
});
</code>```

Title: Add class to empty elements only

Body:
Generally, I think what you're trying to do is

$('.Prodotto:empty').addClass('empty-content');

But when you say the "Current .Prodotto", it implies there is something else in your code which makes it the "current" one, like having clicked on it, and if so your code is similar to your existing, except using this

$('.Prodotto').on('click',function(){
    var $this = $(this);
    if ($this.is(':empty')){
        $this.addClass('empty-content');
    }
});


问:
What's the difference between %i, %d and %D in C ? (printf)
I'm wondering what's the difference between %D, %d and %i in the printf function, because they all display integers, so why are there 3 formats to display integers? There must be a difference between these three formats?

Edit: I was also asking for %D, not only %i and %d.

答:
First, %D isn't a standard.

When it comes to %d and %i, there's no difference for output (e.g: printf), as pointed by some users on the comments and Oliver Charlesworth on his answer.

However, for input data (e.g.: scanf) you can use %i for scanning hexadecimal values (if preceded by 0x), or octal (if preceded by 0).  Its default behavior will scan decimal values.

E.g: if you input some data using %i like 0x28, it will be the same as 40 in dec.

EDIT: Some code as example:

```<code>#include <stdio.h>
int main(){
    int dec, hex;
    scanf("%i",&hex); //For example, hex = 0x28
    scanf("%d",&dec); //For example, dec = 28
    printf("Hex: %d\nDec: %d\n",hex,dec); // outputs: Hex = 40, Dec = 28
}
</code>```

Body:
First, %D isn't a standard.

When it comes to %d and %i, there's no difference for output (e.g: printf), as pointed by some users on the comments and Oliver Charlesworth on his answer.

However, for input data (e.g.: scanf) you can use %i for scanning hexadecimal values (if preceded by 0x), or octal (if preceded by 0).  Its default behavior will scan decimal values.

E.g: if you input some data using %i like 0x28, it will be the same as 40 in dec.

EDIT: Some code as example:

#include <stdio.h>
int main(){
    int dec, hex;
    scanf("%i",&hex); //For example, hex = 0x28
    scanf("%d",&dec); //For example, dec = 28
    printf("Hex: %d\nDec: %d\n",hex,dec); // outputs: Hex = 40, Dec = 28
}


问:
Android case statement help
I'm trying to make my case statement open up a different class depending on what button is pressed. I got this working fine for one button but am unsure how to proceed for two buttons.

Heres my code so far:

```<code>public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.reminderList_button:
        Intent i = new Intent (this, ReminderListActivity.class);
        startActivity(i);
        break;

    }

}
</code>```

This gives an error because I'm reusing the local variable (i) - if anyone could let me know how to do this properly it would be much appreciated.

答:
You could declare the variable i before the switch statement. This is especially preferable to "scoping" if you plan to use the variable i after the switch statement:

```<code>public void onClick(View v) {
    Intent i = null;
    switch (v.getId()) {
    case R.id.about_button:
        i = new Intent(this, About.class);
        break;
    case R.id.reminderList_button:
        i = new Intent (this, ReminderListActivity.class);
        break;
    }
    startActivity(i);
    ...; // other statements using `i'
}
</code>```

Title: Android case statement help

Body:
I'm trying to make my case statement open up a different class depending on what button is pressed. I got this working fine for one button but am unsure how to proceed for two buttons.

Heres my code so far:

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.reminderList_button:
        Intent i = new Intent (this, ReminderListActivity.class);
        startActivity(i);
        break;

    }

}

This gives an error because I'm reusing the local variable (i) - if anyone could let me know how to do this properly it would be much appreciated.

Body:
You could declare the variable i before the switch statement. This is especially preferable to "scoping" if you plan to use the variable i after the switch statement:

public void onClick(View v) {
    Intent i = null;
    switch (v.getId()) {
    case R.id.about_button:
        i = new Intent(this, About.class);
        break;
    case R.id.reminderList_button:
        i = new Intent (this, ReminderListActivity.class);
        break;
    }
    startActivity(i);
    ...; // other statements using `i'
}