问:
Use of def, val, and var in scala
```<code>class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)
</code>```

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

```<code>def age = 30
age = 45
</code>```

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

答:
Let's take this:

```<code>class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)
</code>```

and rewrite it with equivalent code

```<code>class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
(new Person("Kumar", 12)).age_=(20)
println((new Person("Kumar", 12)).age)
</code>```

See, def is a method. It will execute each time it is called, and each time it will return (a) new Person("Kumar", 12). And these is no error in the "assignment" because it isn't really an assignment, but just a call to the age_= method (provided by var).

Title: Use of def, val, and var in scala

Body:
class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

def age = 30
age = 45

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

Body:
Let's take this:

class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)

and rewrite it with equivalent code

class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
(new Person("Kumar", 12)).age_=(20)
println((new Person("Kumar", 12)).age)

See, def is a method. It will execute each time it is called, and each time it will return (a) new Person("Kumar", 12). And these is no error in the "assignment" because it isn't really an assignment, but just a call to the age_= method (provided by var).


来源: stackexchange

问:
Disable / Check for Mock Location (prevent gps spoofing)
Looking to find the best way to prevent / detect GPS spoofing on Android. Any suggestions on how this is accomplished, and what can be done to stop it? I am guessing the user has to turn on mock locations to spoof GPS, if this is done, then they can spoof GPS?

I guess I would need to just detect if Mock Locations are enabled? Any other suggestions?

答:
This scrip is working for all version of android and i find it after many search</p>

```<code>LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This scrip is working for all version of android and i find it after many search

LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }


问:
Access logged in user via Ajax in Laravel
I have read a lot about this but I can't seem to solve it, so I am just going around in circles. I am trying to access a logged user via an API route I have setup using;

```<code>$user = Auth:user();
</code>```

The problem is; $user is always null when I make an ajax request but the user is not null when I access the API route in the browser. For example entering; api.example.com/v1/myaccount

I have solved many problems along the way such as turning on sessions for all subdomains and adding the following to the api route middleware.

```<code>    protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];
</code>```

Previously the url was returning a 404 error via Ajax but worked fine in the browser. Now the $user variable is just empty as if no user is logged. But I have logged normally.

I am using Laravel 5.2

答:
Answer is No! You can't do that.

I think you have confuse between Ajax with POST request from HTML Form.
Because Ajax call has different sessions.

Body:
I have read a lot about this but I can't seem to solve it, so I am just going around in circles. I am trying to access a logged user via an API route I have setup using;

$user = Auth:user();

The problem is; $user is always null when I make an ajax request but the user is not null when I access the API route in the browser. For example entering; api.example.com/v1/myaccount

I have solved many problems along the way such as turning on sessions for all subdomains and adding the following to the api route middleware.

    protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];

Previously the url was returning a 404 error via Ajax but worked fine in the browser. Now the $user variable is just empty as if no user is logged. But I have logged normally.

I am using Laravel 5.2


问:
HTTPConnectionPool redirect not working
Assume this page "www.test.com/redirecttest" redirects to another page "www.google.com"

The below code is not redirecting to google page but returns only 404 status for the test.com page.  All browsers work fine in redirecting the page.

How to get the response from the redirected page in python for HTTPConnectionPool?

```<code>firstPool = HTTPConnectionPool(firstServerURL, maxsize=10, retries =10)

res = firstPool.request("GET", "http://www.test.com/redirecttest",assert_same_host=False,redirect=True)
</code>```

If I remove assert_same_host=False it returns error

Tried to open a foreign host with url: http://www.google.com.

So I have added assert_same_host=False to avoid that error.

答: a HTTPConnectionPool is a pool for connections to "one specific host". If you redirect the request to another host, you are "leaving" this specific host. So without assert_same_hos=False, you will get a HostChangedErrorException as descripbed in the documentation: http://urllib3.readthedocs.io/en/1.0.2/pools.html#api

Title: HTTPConnectionPool redirect not working

Body:
Assume this page "www.test.com/redirecttest" redirects to another page "www.google.com"

The below code is not redirecting to google page but returns only 404 status for the test.com page.  All browsers work fine in redirecting the page.

How to get the response from the redirected page in python for HTTPConnectionPool?

firstPool = HTTPConnectionPool(firstServerURL, maxsize=10, retries =10)

res = firstPool.request("GET", "http://www.test.com/redirecttest",assert_same_host=False,redirect=True)

If I remove assert_same_host=False it returns error

Tried to open a foreign host with url: http://www.google.com.

So I have added assert_same_host=False to avoid that error.


问:
Attempting to port XTea Encryption Algorithm from C to Python
I'm having trouble translating some C Code into Python. I have tried my best to simulate the nature of integer overflow from C, but have so far been unsuccessful. If anybody has some insight, that would be greatly appreciated as I'm new to python. Encryption & decryption is as follows:

```<code>iterations = 32
delta = 0x9e3779b9
xTeaKey = [<some int32>, <some int32>, <some int32>, <some int32>]

def int_overflow(val):
    maxint = 2147483647

    if not -maxint-1 <= val <= maxint:
        val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1

    if not -maxint-1 <= val <= maxint:
        print "AAAAAH"

    return val

def xTeaShuffle(x, sum, sumOffset) :
    e1 = (x << 4) & 0xffffffff
    e2 = x >> 5
    e3 = e1 ^ e2
    e4 = int_overflow(e3 + x)

    e5a = int_overflow(sum + xTeaKey[(sum & 0x03)]);
    e5b = int_overflow(sum + xTeaKey[((sum >> 11) & 0x03)]);
    e5 = e5b if sumOffset else e5a

    result = e4 ^ e5

    return result

def xTeaEncode(data, length) :
    i = 0

    while i < length:
        sum = 0
        x1 = (data[i] << 16) + data[i + 1]
        x2 = (data[i + 2] << 16) + data[i + 3]

        iter = iterations

        while iter > 0 :
            x1 = int_overflow(x1 + xTeaShuffle(x2, sum, False))
            sum = int_overflow(sum + delta);
            x2 = int_overflow(x2 + xTeaShuffle(x1, sum, True))
            iter -= 1

        data[i] = (x1 >> 16) & 0xffff
        data[i + 1] = x1 & 0xffff
        data[i + 2] = (x2 >> 16) & 0xffff
        data[i + 3] = x2 & 0xffff

        i += 4

    return

def xTeaDecode(data, length) :
    i = 0

    while i < length:
        sum = int_overflow(delta * iterations)
        x1 = (data[i] << 16) + data[i + 1]
        x2 = (data[i + 2] << 16) + data[i + 3]

        while (sum != 0) :
            x2 = int_overflow(x2 - xTeaShuffle(x1, sum, True))
            sum = int_overflow(sum - delta)
            x1 = int_overflow(x1 - xTeaShuffle(x2, sum, False))

        data[i] = (x1 >> 16) & 0xffff
        data[i + 1] = x1 & 0xffff
        data[i + 2] = (x2 >> 16) & 0xffff
        data[i + 3] = x2 & 0xffff

        i += 4

    return
</code>```

And the original C Code

```<code>DllExport void _stdcall XTEAEncode16(unsigned short *data, unsigned char dataLength)
{
    unsigned char i = 0;
    int x1;
    int x2;
    int sum;
    unsigned char iterationCount;

    while (i < dataLength)
    {
        sum = 0;
        x1 = ((unsigned int)data[i] << 16) + (unsigned int)data[i+1];
        x2 = ((unsigned int)data[i+2] << 16) + (unsigned int)data[i+3];
        iterationCount = NUM_ITERATIONS;

        while (iterationCount > 0)
        {
            x1 += (((x2 << 4) ^ (x2 >> 5)) + x2) ^ (sum + XTEAKey[(sum & 0x03)]);
            sum += DELTA;
            x2 += (((x1 << 4) ^ (x1 >> 5)) + x1) ^ (sum + XTEAKey[((sum >> 11) & 0x03)]);
            iterationCount--;
        }
        data[i]   = (unsigned short)((unsigned int)x1>>16);     /* take upper half as an int*/
        data[i+1] = (unsigned short)(unsigned int)x1;           /* take lower half */
        data[i+2] = (unsigned short)((unsigned int)x2>>16);     /* take upper half as an int*/
        data[i+3] = (unsigned short)(unsigned int)x2;           /* take lower half */

        i += 4;
    }
}

/**
 * Decodes (deciphers) data.
 * Note that data length must be a multiple of 4 words (64 bit).
 *//* *< 16-bit data array *//* *< length of data array */
DllExport void _stdcall  XTEADecode16(unsigned short* data, unsigned char dataLength )
{
    unsigned char i = 0;
    int x1;
    int x2;
    int sum;
    unsigned char iterations;

    iterations = NUM_ITERATIONS;

    while (i < dataLength)
    {
        sum = DELTA * iterations;
        x1 = ((unsigned int)data[i] << 16) + (unsigned int)data[i+1];
        x2 = ((unsigned int)data[i+2] << 16) + (unsigned int)data[i+3];

        while (sum != 0)
        {
            x2 -= (((x1 << 4) ^ (x1 >> 5)) + x1) ^ (sum + XTEAKey[((sum >> 11) & 0x03)]);
            sum -= DELTA;
            x1 -= (((x2 << 4) ^ (x2 >> 5)) + x2) ^ (sum + XTEAKey[(sum & 0x03)]);
        }
        data[i]   = (unsigned short)((unsigned int)x1 >> 16);   /* take upper half as an int*/
        data[i+1] = (unsigned short)((unsigned int)x1);         /* take lower half */
        data[i+2] = (unsigned short)((unsigned int)x2 >> 16);   /* take upper half as an int*/
        data[i+3] = (unsigned short)((unsigned int)x2);         /* take lower half */

        i += 4;
    }
}
</code>```

From my experiments, Encryption seems to be ok, but I can never decrypt to the correct value. Any insight would be greatly appreciated.

答:
Solved it!!! Here's the gotcha:

When bit-shifting to the right (and depending on the implementation), the bits may be filled with either 0 or 1, depending on the leftmost bit. This is to preserve the sign of a two's compliment binary number. So when simulating a shift on a c integer, if we don't emulate the sign, we must pad the left with 1's if that was the left-most bit.

Body:
I'm having trouble translating some C Code into Python. I have tried my best to simulate the nature of integer overflow from C, but have so far been unsuccessful. If anybody has some insight, that would be greatly appreciated as I'm new to python. Encryption & decryption is as follows:

iterations = 32
delta = 0x9e3779b9
xTeaKey = [<some int32>, <some int32>, <some int32>, <some int32>]

def int_overflow(val):
    maxint = 2147483647

    if not -maxint-1 <= val <= maxint:
        val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1

    if not -maxint-1 <= val <= maxint:
        print "AAAAAH"

    return val

def xTeaShuffle(x, sum, sumOffset) :
    e1 = (x << 4) & 0xffffffff
    e2 = x >> 5
    e3 = e1 ^ e2
    e4 = int_overflow(e3 + x)

    e5a = int_overflow(sum + xTeaKey[(sum & 0x03)]);
    e5b = int_overflow(sum + xTeaKey[((sum >> 11) & 0x03)]);
    e5 = e5b if sumOffset else e5a

    result = e4 ^ e5

    return result

def xTeaEncode(data, length) :
    i = 0

    while i < length:
        sum = 0
        x1 = (data[i] << 16) + data[i + 1]
        x2 = (data[i + 2] << 16) + data[i + 3]

        iter = iterations

        while iter > 0 :
            x1 = int_overflow(x1 + xTeaShuffle(x2, sum, False))
            sum = int_overflow(sum + delta);
            x2 = int_overflow(x2 + xTeaShuffle(x1, sum, True))
            iter -= 1

        data[i] = (x1 >> 16) & 0xffff
        data[i + 1] = x1 & 0xffff
        data[i + 2] = (x2 >> 16) & 0xffff
        data[i + 3] = x2 & 0xffff

        i += 4

    return

def xTeaDecode(data, length) :
    i = 0

    while i < length:
        sum = int_overflow(delta * iterations)
        x1 = (data[i] << 16) + data[i + 1]
        x2 = (data[i + 2] << 16) + data[i + 3]

        while (sum != 0) :
            x2 = int_overflow(x2 - xTeaShuffle(x1, sum, True))
            sum = int_overflow(sum - delta)
            x1 = int_overflow(x1 - xTeaShuffle(x2, sum, False))

        data[i] = (x1 >> 16) & 0xffff
        data[i + 1] = x1 & 0xffff
        data[i + 2] = (x2 >> 16) & 0xffff
        data[i + 3] = x2 & 0xffff

        i += 4

    return

And the original C Code

DllExport void _stdcall XTEAEncode16(unsigned short *data, unsigned char dataLength)
{
    unsigned char i = 0;
    int x1;
    int x2;
    int sum;
    unsigned char iterationCount;

    while (i < dataLength)
    {
        sum = 0;
        x1 = ((unsigned int)data[i] << 16) + (unsigned int)data[i+1];
        x2 = ((unsigned int)data[i+2] << 16) + (unsigned int)data[i+3];
        iterationCount = NUM_ITERATIONS;

        while (iterationCount > 0)
        {
            x1 += (((x2 << 4) ^ (x2 >> 5)) + x2) ^ (sum + XTEAKey[(sum & 0x03)]);
            sum += DELTA;
            x2 += (((x1 << 4) ^ (x1 >> 5)) + x1) ^ (sum + XTEAKey[((sum >> 11) & 0x03)]);
            iterationCount--;
        }
        data[i]   = (unsigned short)((unsigned int)x1>>16);     /* take upper half as an int*/
        data[i+1] = (unsigned short)(unsigned int)x1;           /* take lower half */
        data[i+2] = (unsigned short)((unsigned int)x2>>16);     /* take upper half as an int*/
        data[i+3] = (unsigned short)(unsigned int)x2;           /* take lower half */

        i += 4;
    }
}

/**
 * Decodes (deciphers) data.
 * Note that data length must be a multiple of 4 words (64 bit).
 *//* *< 16-bit data array *//* *< length of data array */
DllExport void _stdcall  XTEADecode16(unsigned short* data, unsigned char dataLength )
{
    unsigned char i = 0;
    int x1;
    int x2;
    int sum;
    unsigned char iterations;

    iterations = NUM_ITERATIONS;

    while (i < dataLength)
    {
        sum = DELTA * iterations;
        x1 = ((unsigned int)data[i] << 16) + (unsigned int)data[i+1];
        x2 = ((unsigned int)data[i+2] << 16) + (unsigned int)data[i+3];

        while (sum != 0)
        {
            x2 -= (((x1 << 4) ^ (x1 >> 5)) + x1) ^ (sum + XTEAKey[((sum >> 11) & 0x03)]);
            sum -= DELTA;
            x1 -= (((x2 << 4) ^ (x2 >> 5)) + x2) ^ (sum + XTEAKey[(sum & 0x03)]);
        }
        data[i]   = (unsigned short)((unsigned int)x1 >> 16);   /* take upper half as an int*/
        data[i+1] = (unsigned short)((unsigned int)x1);         /* take lower half */
        data[i+2] = (unsigned short)((unsigned int)x2 >> 16);   /* take upper half as an int*/
        data[i+3] = (unsigned short)((unsigned int)x2);         /* take lower half */

        i += 4;
    }
}

From my experiments, Encryption seems to be ok, but I can never decrypt to the correct value. Any insight would be greatly appreciated.


问:
How to fetch data from response._body in proper way?
So starting first my nodejs server sends this as a response

"["name1","name2","name3"]"

but my angular 2 code for service is

```<code>return this.http.get(this.config.apiUrl + '/folder').map((response:Response)=> {
       response.json();
     console.log(response); }
</code>```

How do I fetch the array?

If I use response._body there will be an error in npm start stating "._body undefined", so I make it as a comment then after npm start I reverse back, I know it is not proper way. Here is the console.log of above service code

```<code> Response
 headers: Headers
 ok:true
 status:200
 statusText:"OK"
 type:2
 url:"http://localhost:4000/folder"
 _body:"["name1","name2","name3"]"
 __proto__:Body
</code>```

The main problem is to fetch in component in an array

Here, is the code I am trying

```<code>this.photoService.getAllfolder().subscribe(
data => {
  console.log(data);
},
error => {
      console.log(error);
});
</code>```

答:
you can get data in lot of ways easy way was response["_body"] or response.text()</p>

```<code>return this.http.get(this.config.apiUrl + '/folder').map((response)=> {
       response["_body"];
     console.log(response); }
</code>```

Body:
So starting first my nodejs server sends this as a response

"["name1","name2","name3"]"

but my angular 2 code for service is

return this.http.get(this.config.apiUrl + '/folder').map((response:Response)=> {
       response.json();
     console.log(response); }

How do I fetch the array?

If I use response._body there will be an error in npm start stating "._body undefined", so I make it as a comment then after npm start I reverse back, I know it is not proper way. Here is the console.log of above service code

 Response
 headers: Headers
 ok:true
 status:200
 statusText:"OK"
 type:2
 url:"http://localhost:4000/folder"
 _body:"["name1","name2","name3"]"
 __proto__:Body

The main problem is to fetch in component in an array

Here, is the code I am trying

this.photoService.getAllfolder().subscribe(
data => {
  console.log(data);
},
error => {
      console.log(error);
});

Body:
you can get data in lot of ways easy way was response["_body"] or response.text()

return this.http.get(this.config.apiUrl + '/folder').map((response)=> {
       response["_body"];
     console.log(response); }


问:
Python next iterator in a loop
I have a small routine like this:

```<code>to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = next((i for i in range(n) if to_use[i]),None)
</code>```

In my sample, n is of the order of a millon. Is the last like with the iterator the most efficient way to get the next "val"?. Or will it go through to_use from 0 each time in the loop? Note that once to_use[i]=False, its never reset to True.

答:
I would suggest just going through the loop one item at a time and changing it from True to False:

In Python 2:

```<code>for i in xrange(len(to_use)):
    to_use[i] = False
</code>```

In Python 3:

```<code>for i in range(len(to_use)):
    to_use[i] = False
</code>```

xrange in Python 2 and range in Python 3 are iterators, so you they won't create a the list [0..len(n)].

Title: Python next iterator in a loop

Body:
I have a small routine like this:

to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = next((i for i in range(n) if to_use[i]),None)

In my sample, n is of the order of a millon. Is the last like with the iterator the most efficient way to get the next "val"?. Or will it go through to_use from 0 each time in the loop? Note that once to_use[i]=False, its never reset to True.

Body:
I would suggest just going through the loop one item at a time and changing it from True to False:

In Python 2:

for i in xrange(len(to_use)):
    to_use[i] = False

In Python 3:

for i in range(len(to_use)):
    to_use[i] = False

xrange in Python 2 and range in Python 3 are iterators, so you they won't create a the list [0..len(n)].


问:
Accessing child props from the parent
I'm building a d3 interface using react. I want the api to be as simple as possible, and to that end I've concieved the following line chart component.

```<code><Chart type="line" multiseries="true">
    <Line data={[...]} label="line1" />
    <Line data={[....]} label="line2" interpolate="linear" />
</Chart>
</code>```

The problem I'm having is that each line needs a common scale, and to generate that I need to find the data set with the maximum range of values to use as the scale.

I have accomplished this in two ways. The first way is by having a LineChart component and passing all the data in as a big object like this

```<code>const config = { line1 : { data: [...] }, line2: { data: [...], interpolate: 'linear' } };
<LineChart config={config} />
</code>```

This has the benfit of making the lines easy to generate, LineChart creates the Line components with the propper scale for us since it has immediate access to all the data. The downside is that this feels cumbersome compared to the first option, and it requires looping through the object to get all the data properties out.

The second way is using the api as depicted above and looping through this.props.children to get the data attributes of each child.

```<code>const children = this.props.children.isArray() ? this.props.children : [this.props.children]
const data = children.map( child => (child.data) )
</code>```

This feels like an anti-pattern since react is all about composition and uni-directional data flow. What is the right way to do this?

答:
There's really nothing wrong with accessing props set by child components, and in fact, React provides the Children top-level API just for that use case:

```<code>var data = React.Children.map(this.props.children, child => child.props.data);
</code>```

The React.Children.* apis normalize children so that you don't have to worry about whether or not a single child was passed or multiple.

From the docs:

React.Children

  React.Children provides utilities for dealing with the this.props.children opaque data structure.

Title: Accessing child props from the parent

Body:
I'm building a d3 interface using react. I want the api to be as simple as possible, and to that end I've concieved the following line chart component.

<Chart type="line" multiseries="true">
    <Line data={[...]} label="line1" />
    <Line data={[....]} label="line2" interpolate="linear" />
</Chart>

The problem I'm having is that each line needs a common scale, and to generate that I need to find the data set with the maximum range of values to use as the scale.

I have accomplished this in two ways. The first way is by having a LineChart component and passing all the data in as a big object like this

const config = { line1 : { data: [...] }, line2: { data: [...], interpolate: 'linear' } };
<LineChart config={config} />

This has the benfit of making the lines easy to generate, LineChart creates the Line components with the propper scale for us since it has immediate access to all the data. The downside is that this feels cumbersome compared to the first option, and it requires looping through the object to get all the data properties out.

The second way is using the api as depicted above and looping through this.props.children to get the data attributes of each child.

const children = this.props.children.isArray() ? this.props.children : [this.props.children]
const data = children.map( child => (child.data) )

This feels like an anti-pattern since react is all about composition and uni-directional data flow. What is the right way to do this?

Body:
There's really nothing wrong with accessing props set by child components, and in fact, React provides the Children top-level API just for that use case:

var data = React.Children.map(this.props.children, child => child.props.data);

The React.Children.* apis normalize children so that you don't have to worry about whether or not a single child was passed or multiple.

From the docs:

React.Children

  React.Children provides utilities for dealing with the this.props.children opaque data structure.


问:
Perl Sublime Text format off when using Regex in source
I am pretty new at both Perl and Sublime. I have a line of code using Regex Find and Replace and everything below it is now Yellow as if it's a quoted string.

How should this line be written so that it both works and doesn't mess up the rest of my code visually?

The file runs without error.

```<code>if($file =~ /$pattern/ ) {
        my $originalname = $file =~ s/$pattern//r;
</code>```

I've tried putting tick and quotes around the actual pattern which fixes the sublime formatting but breaks the code.

I think its a Sublime problem as TextMate doesn't exhibit the same issue.

答:
Just put a comment with an additional slash there.

```<code>if($file =~ /$pattern/ ) { # /
        my $originalname = $file =~ s/$pattern//r; # /
</code>```

Not every syntax highlighter is perfect. The one Stack Overflow uses also does not get this right, as you can see above.

Body:
I am pretty new at both Perl and Sublime. I have a line of code using Regex Find and Replace and everything below it is now Yellow as if it's a quoted string.

How should this line be written so that it both works and doesn't mess up the rest of my code visually?

The file runs without error.

if($file =~ /$pattern/ ) {
        my $originalname = $file =~ s/$pattern//r;

I've tried putting tick and quotes around the actual pattern which fixes the sublime formatting but breaks the code.

I think its a Sublime problem as TextMate doesn't exhibit the same issue.

Body:
Just put a comment with an additional slash there.

if($file =~ /$pattern/ ) { # /
        my $originalname = $file =~ s/$pattern//r; # /

Not every syntax highlighter is perfect. The one Stack Overflow uses also does not get this right, as you can see above.


问:
XSLT 2.0 - How to find unmatched references/pairs
I have XML documents that contain many elements that reference other elements by id/ref pairs, similar to the example shown below. I just need to identify if there are any references that do not match any existing ids. I thought this would be straightforward, but if it is, I'm missing the trick to it.

<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <Person id="abc">
    <Name>David</Name>
  </Person>
  <Person id="def">
    <Name>Mark</Name>
  </Person>
  <Person id="ghi">
    <Name>James</Name>
  </Person>
  <Nickname ref="ghi">
    <Nname>Jim</Nname>
  </Nickname>
  <Nickname ref="abc">
    <Nname>Dave</Nname>
  </Nickname>
  <Nickname ref="xyz">
    <Nname>Fred</Nname>
  </Nickname>
  <Document id="123">
    <DocName>Document 1</DocName>
  </Document>
  <Document id="456">
    <DocName>Document 2</DocName>
  </Document>
  <Chapter ref="123">
    <Cname>Chapter 1</Cname>
  </Chapter>
  <Chapter ref="999">
    <Cname>Chapter 999</Cname>
  </Chapter>
</Root>```

In this example, I would want the output to return the Nickname reference xyz and the Chapter reference 999, because those do not match anything in the XML document. I do NOT need or want it to return any information about the unmatched Person or Document. I've tried about 20 variations on ways of comparing sequences, but I must be missing something because I can't get the result I need.

Thanks!

答:
As I mentioned in a comment, I found this on another site, "XPath only allows set operations over sequences of nodes. Atomic values are not allowed. This is because the set operations are over node identity and not value." I'm repeating it here for people who may see this page, but not read all the comments.

That means my initial set-based approach would never work, because the sets I wanted to use were composed of values, not nodes. So I switched to a template-based approach, using a key.

So, I am using a key, like this;

<xsl:key name="elem-by-id" match="*" use="@id" />

Along with that key, I created a template that works the same way as Michael's variable. This limits processing to those elements that have an @ref that does not match any @id in the XML document.
<xsl:template match="//*[@ref][not(key('elem-by-id', @ref))]">

That gets the elements that contain the unmatched @ref attributes, directly. Then, inside the template, I can just get the value of the unmatched @ref with a very simple select.

<xsl:value-of select="@ref"/>

I chose to go with this approach because it lets me also easily retrieve the name of the element that contains the unmatched @ref.

<xsl:value-of select="./../name()">

Body:
I have XML documents that contain many elements that reference other elements by id/ref pairs, similar to the example shown below. I just need to identify if there are any references that do not match any existing ids. I thought this would be straightforward, but if it is, I'm missing the trick to it.

<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <Person id="abc">
    <Name>David</Name>
  </Person>
  <Person id="def">
    <Name>Mark</Name>
  </Person>
  <Person id="ghi">
    <Name>James</Name>
  </Person>
  <Nickname ref="ghi">
    <Nname>Jim</Nname>
  </Nickname>
  <Nickname ref="abc">
    <Nname>Dave</Nname>
  </Nickname>
  <Nickname ref="xyz">
    <Nname>Fred</Nname>
  </Nickname>
  <Document id="123">
    <DocName>Document 1</DocName>
  </Document>
  <Document id="456">
    <DocName>Document 2</DocName>
  </Document>
  <Chapter ref="123">
    <Cname>Chapter 1</Cname>
  </Chapter>
  <Chapter ref="999">
    <Cname>Chapter 999</Cname>
  </Chapter>
</Root>

In this example, I would want the output to return the Nickname reference xyz and the Chapter reference 999, because those do not match anything in the XML document. I do NOT need or want it to return any information about the unmatched Person or Document. I've tried about 20 variations on ways of comparing sequences, but I must be missing something because I can't get the result I need.

Thanks!


问:
SQL Server subquery returns nothing based on another subquery
I have a 2 subqueries where based on the first subquery, the second subquery's result changes which I don't want to happen.

The 2 queries are the same exactly other than the variable they use for the date.

The first query always works correctly, but the second query seems to be affected sometimes by the first query.

If I have the first query before the second query then they will both return the same date. If I have the second query before the first, then it sometimes returns nothing.

```<code>declare @curDate date = DATEADD(week,0,'2016/02/01')
declare @shortDate date = DATEADD(week,-2,@curDate)

SELECT -- Select Columns
    quere1.Location,
    quere1.Product,
    quere1.Short,
    MAX( quere1.Date ) [Date],
    MAX( quere1.Volume ) [Volume],
    MAX( quere1.Cost ) [Cost],
    MAX( quere2.Date ) [DateAgo],
    MAX( quere2.Volume ) [VolumeAgo],
    MAX( quere2.Cost ) [CostAgo]
FROM

    (SELECT --subQuery 1
        cst_mac_a.loc [Location],                 --Branch
        cst_mac_a.product [Product],             --Product
        pro_duct.desc4 [Short],
        MAX( cst_mac_a.datecreated ) [Date],  --Date
        MAX( cst_mac_a.ohvol ) [Volume],        --Volume
        MAX( cst_mac_a.ohextcost ) [Cost]     --Cost
    FROM cst_mac as cst_mac_a
        JOIN pro_type ON pro_type.proType = cst_mac_a.proType
        JOIN pro_duct ON pro_duct.proType = cst_mac_a.proType AND pro_duct.product = cst_mac_a.product
    WHERE
        cst_mac_a.protype = 'HW' AND

        cst_mac_a.datecreated in (SELECT MAX( sub.datecreated ) from cst_mac as sub WHERE
                                    cst_mac_a.product = sub.product AND sub.datecreated <= @curDate) AND

        cst_mac_a.timecreated in (SELECT MAX( sub.timecreated ) from cst_mac as sub WHERE
                                    cst_mac_a.product = sub.product AND sub.datecreated in
                                                (SELECT MAX( sub2.datecreated ) from cst_mac as sub2 WHERE
                                                            sub2.datecreated <= @curDate and sub2.product = sub.product)) AND

        cst_mac_a.PROGRESS_RECID in (SELECT MAX( sub.PROGRESS_RECID ) from cst_mac as sub WHERE
                                    cst_mac_a.product = sub.product AND sub.datecreated in
                                                (SELECT MAX( sub2.datecreated ) from cst_mac as sub2 WHERE
                                                            sub2.datecreated <= @curDate AND sub2.product = sub.product)) AND

        cst_mac_a.ohvol <> 0 AND
        cst_mac_a.product = 'A4ROUP'
    GROUP BY
        cst_mac_a.loc,
        cst_mac_a.product,
        pro_duct.desc4)
    as quere1

    LEFT OUTER JOIN (SELECT --Basically same code, subquery 2
        cst_mac_a2.loc [Location],                 --Branch
        cst_mac_a2.product [Product],             --Product
        pro_duct.desc4 [Short],
        MAX( cst_mac_a2.datecreated ) [Date],  --Date
        MAX( cst_mac_a2.ohvol ) [Volume],        --Volume
        MAX( cst_mac_a2.ohextcost ) [Cost]     --Cost
    FROM cst_mac as cst_mac_a2
        JOIN pro_type ON pro_type.proType = cst_mac_a2.proType
        JOIN pro_duct ON pro_duct.proType = cst_mac_a2.proType AND pro_duct.product = cst_mac_a2.product
    WHERE
        cst_mac_a2.protype = 'HW' AND

        cst_mac_a2.datecreated in (SELECT MAX( sub3.datecreated ) from cst_mac as sub3 WHERE
                                    cst_mac_a2.product = sub3.product AND sub3.datecreated <= @shortDate) AND

        cst_mac_a2.timecreated in (SELECT MAX( sub3.timecreated ) from cst_mac as sub3 WHERE
                                    cst_mac_a2.product = sub3.product AND sub3.datecreated in
                                                (SELECT MAX( sub4.datecreated ) from cst_mac as sub4 WHERE
                                                            sub4.datecreated <= @shortDate and sub4.product = sub3.product)) AND

        cst_mac_a2.PROGRESS_RECID in (SELECT MAX( sub3.PROGRESS_RECID ) from cst_mac as sub3 WHERE
                                    cst_mac_a2.product = sub3.product AND sub3.datecreated in
                                                (SELECT MAX( sub4.datecreated ) from cst_mac as sub4 WHERE
                                                            sub4.datecreated <= @shortDate AND sub4.product = sub3.product))
    GROUP BY
        cst_mac_a2.loc,
        cst_mac_a2.product,
        pro_duct.desc4)
    as quere2

    ON quere1.Product = quere2.Product AND quere1.Location = quere2.Location
GROUP BY
    quere1.Location,
    quere1.Product,
    quere1.Short
Order BY
    quere1.Location,
    quere1.Product,
    quere1.Short
</code>```

Sample Output:

```<code>curDate = Today
shortDate = 2 weeks ago:
Location | Product | Short | Date | Volume | Cost | DateAgo | VolumeAgo | CostAgo
Mill     | A4ROUP  | BN.   | 2/1/2016|40   | 36   |         |           |

curDate = 1 week ago
shortDate = 2 weeks ago
Location | Product | Short | Date | Volume | Cost | DateAgo | VolumeAgo | CostAgo
Mill     | A4ROUP  | BN.   |1/25/2016|27   | 25   |1/18/2016|   29      | 26
</code>```

答:
That's the way LEFT JOIN works.   It gets all rows from the first query, but only gets matching rows (per the JOIN conditions in the ON clause) from the second query.

If you want to always get all rows from both queries, even if there is no matching row in the opposite query, then you need to use a FULL OUTER JOIN.

Body:
I have a 2 subqueries where based on the first subquery, the second subquery's result changes which I don't want to happen.

The 2 queries are the same exactly other than the variable they use for the date.

The first query always works correctly, but the second query seems to be affected sometimes by the first query.

If I have the first query before the second query then they will both return the same date. If I have the second query before the first, then it sometimes returns nothing.

declare @curDate date = DATEADD(week,0,'2016/02/01')
declare @shortDate date = DATEADD(week,-2,@curDate)

SELECT -- Select Columns
    quere1.Location,
    quere1.Product,
    quere1.Short,
    MAX( quere1.Date ) [Date],
    MAX( quere1.Volume ) [Volume],
    MAX( quere1.Cost ) [Cost],
    MAX( quere2.Date ) [DateAgo],
    MAX( quere2.Volume ) [VolumeAgo],
    MAX( quere2.Cost ) [CostAgo]
FROM

    (SELECT --subQuery 1
        cst_mac_a.loc [Location],                 --Branch
        cst_mac_a.product [Product],             --Product
        pro_duct.desc4 [Short],
        MAX( cst_mac_a.datecreated ) [Date],  --Date
        MAX( cst_mac_a.ohvol ) [Volume],        --Volume
        MAX( cst_mac_a.ohextcost ) [Cost]     --Cost
    FROM cst_mac as cst_mac_a
        JOIN pro_type ON pro_type.proType = cst_mac_a.proType
        JOIN pro_duct ON pro_duct.proType = cst_mac_a.proType AND pro_duct.product = cst_mac_a.product
    WHERE
        cst_mac_a.protype = 'HW' AND

        cst_mac_a.datecreated in (SELECT MAX( sub.datecreated ) from cst_mac as sub WHERE
                                    cst_mac_a.product = sub.product AND sub.datecreated <= @curDate) AND

        cst_mac_a.timecreated in (SELECT MAX( sub.timecreated ) from cst_mac as sub WHERE
                                    cst_mac_a.product = sub.product AND sub.datecreated in
                                                (SELECT MAX( sub2.datecreated ) from cst_mac as sub2 WHERE
                                                            sub2.datecreated <= @curDate and sub2.product = sub.product)) AND

        cst_mac_a.PROGRESS_RECID in (SELECT MAX( sub.PROGRESS_RECID ) from cst_mac as sub WHERE
                                    cst_mac_a.product = sub.product AND sub.datecreated in
                                                (SELECT MAX( sub2.datecreated ) from cst_mac as sub2 WHERE
                                                            sub2.datecreated <= @curDate AND sub2.product = sub.product)) AND

        cst_mac_a.ohvol <> 0 AND
        cst_mac_a.product = 'A4ROUP'
    GROUP BY
        cst_mac_a.loc,
        cst_mac_a.product,
        pro_duct.desc4)
    as quere1

    LEFT OUTER JOIN (SELECT --Basically same code, subquery 2
        cst_mac_a2.loc [Location],                 --Branch
        cst_mac_a2.product [Product],             --Product
        pro_duct.desc4 [Short],
        MAX( cst_mac_a2.datecreated ) [Date],  --Date
        MAX( cst_mac_a2.ohvol ) [Volume],        --Volume
        MAX( cst_mac_a2.ohextcost ) [Cost]     --Cost
    FROM cst_mac as cst_mac_a2
        JOIN pro_type ON pro_type.proType = cst_mac_a2.proType
        JOIN pro_duct ON pro_duct.proType = cst_mac_a2.proType AND pro_duct.product = cst_mac_a2.product
    WHERE
        cst_mac_a2.protype = 'HW' AND

        cst_mac_a2.datecreated in (SELECT MAX( sub3.datecreated ) from cst_mac as sub3 WHERE
                                    cst_mac_a2.product = sub3.product AND sub3.datecreated <= @shortDate) AND

        cst_mac_a2.timecreated in (SELECT MAX( sub3.timecreated ) from cst_mac as sub3 WHERE
                                    cst_mac_a2.product = sub3.product AND sub3.datecreated in
                                                (SELECT MAX( sub4.datecreated ) from cst_mac as sub4 WHERE
                                                            sub4.datecreated <= @shortDate and sub4.product = sub3.product)) AND

        cst_mac_a2.PROGRESS_RECID in (SELECT MAX( sub3.PROGRESS_RECID ) from cst_mac as sub3 WHERE
                                    cst_mac_a2.product = sub3.product AND sub3.datecreated in
                                                (SELECT MAX( sub4.datecreated ) from cst_mac as sub4 WHERE
                                                            sub4.datecreated <= @shortDate AND sub4.product = sub3.product))
    GROUP BY
        cst_mac_a2.loc,
        cst_mac_a2.product,
        pro_duct.desc4)
    as quere2

    ON quere1.Product = quere2.Product AND quere1.Location = quere2.Location
GROUP BY
    quere1.Location,
    quere1.Product,
    quere1.Short
Order BY
    quere1.Location,
    quere1.Product,
    quere1.Short

Sample Output:

curDate = Today
shortDate = 2 weeks ago:
Location | Product | Short | Date | Volume | Cost | DateAgo | VolumeAgo | CostAgo
Mill     | A4ROUP  | BN.   | 2/1/2016|40   | 36   |         |           |

curDate = 1 week ago
shortDate = 2 weeks ago
Location | Product | Short | Date | Volume | Cost | DateAgo | VolumeAgo | CostAgo
Mill     | A4ROUP  | BN.   |1/25/2016|27   | 25   |1/18/2016|   29      | 26


问:
Can I use sourced files globally?
Consider this script excerpt:

tpl file content:

```<code>FULL_ACCESS_USER_TPL="id=FA_SEND action = OK sender == $EMAIL"
</code>```

script content

```<code>source tpl

EMAILS="foo@domain.tld bar@domain.tld"

for EMAIL in $EMAILS
do
    echo $FULL_ACCESS_USER_TPL
done
</code>```

Desired output:

```<code>id=FA_SEND action = OK sender == foo@domain.tld
id=FA_SEND action = OK sender == bar@domain.tld
</code>```

When I run the script I get nothing, but if I put source tpl inside the loop for, I get what I want.

Can I source files, let's say, 'globally' in order to use them all over the script?

答:
Create a function in tpl, then call the function:

```<code>$ cat tpl
function FULL_ACCESS_USER_TPL() {

    echo "id=FA_SEND action = OK sender == $EMAIL"
}

$ cat script.sh
source tpl

EMAILS="foo@domain.tld bar@domain.tld"

for EMAIL in $EMAILS
do
    FULL_ACCESS_USER_TPL
done
</code>```

The problem was that, when you sourced tpl, EMAIL was not set.

Title: Can I use sourced files globally?

Body:
Consider this script excerpt:

tpl file content:

FULL_ACCESS_USER_TPL="id=FA_SEND action = OK sender == $EMAIL"

script content

source tpl

EMAILS="foo@domain.tld bar@domain.tld"

for EMAIL in $EMAILS
do
    echo $FULL_ACCESS_USER_TPL
done

Desired output:

id=FA_SEND action = OK sender == foo@domain.tld
id=FA_SEND action = OK sender == bar@domain.tld

When I run the script I get nothing, but if I put source tpl inside the loop for, I get what I want.

Can I source files, let's say, 'globally' in order to use them all over the script?

Body:
Create a function in tpl, then call the function:

$ cat tpl
function FULL_ACCESS_USER_TPL() {

    echo "id=FA_SEND action = OK sender == $EMAIL"
}

$ cat script.sh
source tpl

EMAILS="foo@domain.tld bar@domain.tld"

for EMAIL in $EMAILS
do
    FULL_ACCESS_USER_TPL
done

The problem was that, when you sourced tpl, EMAIL was not set.


问:
Rails: Validating min and max length of a string but allowing it to be blank
I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

```<code>validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5
</code>```

How do I write this to accomplish my goal?

答:
In your model e.g.</p>

```<code>def validate
  errors.add_to_base 'error message' unless self.foo.length == 5 or self.foo.blanc?
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5

How do I write this to accomplish my goal?

Body:
In your model e.g.

def validate
  errors.add_to_base 'error message' unless self.foo.length == 5 or self.foo.blanc?
end

ContentLicense: CC BY-SA 2.5


问:
Convert int array to char array in cpp to give filename
Lets say we have an integer array 1,2,3 (can be up to size 36, so each digit is not a single digit) and I want to name a file as 123...36.txt. I will do this on the go therefore, I need to change filename based on int array values

I checked some solutions online, none of them worked. Is there an easy fix to this? Thanks

```<code>int main(int argc, char **argv) {

    int i;

    FILE *ptr;

    int b[3]={1,2,3};
    char name[FILENAME_MAX];

    for(i=0;i<3;i++) itoa(b[i],name[i],10);

    name[3]='.';
    name[4]='t';
    name[5]='x';
    name[6]='t';
    name[7]='\0';

    ptr = fopen(name, "w");

    fclose(ptr);

    return 0;
}
</code>```

答:
The thing that most resembles your algorithm would be to just use the digits to offset the ascii value of the 0 character. Replace your itoa() line with this:

```<code>for(i=0;i<3;i++) name[i] = '0'+b[i];
</code>```

This obviously assumes, as your code did, that the incoming int values are between 0 and 9.

Body:
Lets say we have an integer array 1,2,3 (can be up to size 36, so each digit is not a single digit) and I want to name a file as 123...36.txt. I will do this on the go therefore, I need to change filename based on int array values

I checked some solutions online, none of them worked. Is there an easy fix to this? Thanks

int main(int argc, char **argv) {

    int i;

    FILE *ptr;

    int b[3]={1,2,3};
    char name[FILENAME_MAX];

    for(i=0;i<3;i++) itoa(b[i],name[i],10);

    name[3]='.';
    name[4]='t';
    name[5]='x';
    name[6]='t';
    name[7]='\0';

    ptr = fopen(name, "w");

    fclose(ptr);

    return 0;
}

Body:
The thing that most resembles your algorithm would be to just use the digits to offset the ascii value of the 0 character. Replace your itoa() line with this:

for(i=0;i<3;i++) name[i] = '0'+b[i];

This obviously assumes, as your code did, that the incoming int values are between 0 and 9.


问:
Cordova deviceready has not fired after 5 seconds in sencha touch 2 projects
I am facing a problem when I build android and ios application after upgrading Cordova from 2.8 to 5.0.0 in sencha touch 2 projects. Android console prints a message like "deviceready has not fired after 5 seconds" and "Channel not fired: onCordovaInfoReady".
Can somebody please suggest something.

Versions:
Sencha Touch : 2.4.2
Cordova : 5.0.0
Cordova Jar : cordova-2.8.1.jar
Android : 4.4.2
Android API : 19

Thank you,
Som

答:
It would be helpful if you could post the code of your index.html file -- without the code, it's impossible to tell for certain what the problem is.

The most likely cause is that you've not included cordova.js in your index.html. Try adding this line to your index.html:

```<code><script src="cordova.js"></script>
</code>```

Don't worry that cordova.js doesn't exist in your code base, the file is generated at build time by Cordova.

I recently encountered this same issue, but in my case cordova.js was already included. Eventually what worked for me was a simple remove and add of the ios platform:

```<code>cordova platform remove ios
cordova platform add ios
</code>```

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.

Body:
It would be helpful if you could post the code of your index.html file -- without the code, it's impossible to tell for certain what the problem is.

The most likely cause is that you've not included cordova.js in your index.html. Try adding this line to your index.html:

<script src="cordova.js"></script>

Don't worry that cordova.js doesn't exist in your code base, the file is generated at build time by Cordova.

I recently encountered this same issue, but in my case cordova.js was already included. Eventually what worked for me was a simple remove and add of the ios platform:

cordova platform remove ios
cordova platform add ios

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.


问:
querying a database using a date parameter
I am new to Visual Basic as well as Stackoverflow.  I am querying certain fields from a database but receiving an error.  here's my code:

```<code>Dim fifdate As Date = Now()
fifdate.AddDays(-15)

db.AddParam("collected", "N")
db.AddParam("printed", "Y")
db.AddParam("sent", "Y")
db.AddParam("date", fifdate)

Dim query As String = "Select * from badcheck where fldcollected =
@collected And fldprinted = @printed And fldsentda = @sent "

'And fldsentdate > @date

db.ExcecuteQuery(query)

CheckedListBox1.DataSource = db.DBDT
</code>```

if i add the commented out section into the query, i get the error "Data type mismatch in criteria expression", but the query works perfectly fine without it.  I know for sure that fldsentdate is set as a date in the database.  any suggestion on how the issue can be fixed?

答:
i was able to fix the problem.  I took the fifdate variable completely out and changed my parameter code to:

```<code>db.AddParam("date". date.today.AddDays(-15))
</code>```

something was going wrong with fifdate, and I believe it may be due to Now().  i tried using fifdate directly with the query and was receiving the same error.

Body:
I am new to Visual Basic as well as Stackoverflow.  I am querying certain fields from a database but receiving an error.  here's my code:

Dim fifdate As Date = Now()
fifdate.AddDays(-15)

db.AddParam("collected", "N")
db.AddParam("printed", "Y")
db.AddParam("sent", "Y")
db.AddParam("date", fifdate)

Dim query As String = "Select * from badcheck where fldcollected =
@collected And fldprinted = @printed And fldsentda = @sent "

'And fldsentdate > @date

db.ExcecuteQuery(query)

CheckedListBox1.DataSource = db.DBDT

if i add the commented out section into the query, i get the error "Data type mismatch in criteria expression", but the query works perfectly fine without it.  I know for sure that fldsentdate is set as a date in the database.  any suggestion on how the issue can be fixed?

Body:
i was able to fix the problem.  I took the fifdate variable completely out and changed my parameter code to:

db.AddParam("date". date.today.AddDays(-15))

something was going wrong with fifdate, and I believe it may be due to Now().  i tried using fifdate directly with the query and was receiving the same error.


问:
How can I use pull request name instead of number in TeamCity branch list?
I define branch specification as "+:refs/pull/*/head" and I want to see pull subject instead of pull name.
And is it possible to make link to the github PR from main project page in the TeamCity? </p>

答: You can connect TeamCity to GitHub through the built-in connector, but I'm not sure that will give you want you want.</p>


问:
Java how to put a dot after a period
I have a piece of text. What i want to do is that in the entire text i want to put a whitespace after all the periods if its not already present. If its already present i dont want two spaces.

Also if the text contains multiple consecutive periods i want to put a whitespace only after the last period and that too only if whitespace is not already present.

I tried using this:

```<code>.replaceAll("[.!?;]", "$0 ").replaceAll("\\s+", " ")
</code>```

But this fails for multiple dots

Thanks.

答:
You can use this regex to place a space after dot if it is not there:

```<code>str = str.replaceAll("\\.(?![.\\s])", "$0 ");
</code>```

RegEx Demo

(?![.\\s]) is a negative lookahead that will assert false if next position has a whitespace or dot characters.

Title: Java how to put a dot after a period

Body:
I have a piece of text. What i want to do is that in the entire text i want to put a whitespace after all the periods if its not already present. If its already present i dont want two spaces.

Also if the text contains multiple consecutive periods i want to put a whitespace only after the last period and that too only if whitespace is not already present.

I tried using this:

.replaceAll("[.!?;]", "$0 ").replaceAll("\\s+", " ")

But this fails for multiple dots

Thanks.

Body:
You can use this regex to place a space after dot if it is not there:

str = str.replaceAll("\\.(?![.\\s])", "$0 ");

RegEx Demo

(?![.\\s]) is a negative lookahead that will assert false if next position has a whitespace or dot characters.


问:
MailChimp custom template problems with drag and drop blocks
I am creating a custom MailChimp template but having issues when using the mc:repeatable element. I have it on a  wrapped around a block of code and in the editor when creating a campaign, it works fine, I can spawn a new version of the parent block and move it around in the template, but when I preview, or send the email, the child block that was spawned from the parent sits below it's parent and not where I have placed it following spawning it from the parent block... Something seems to be wrong? (Heavily simplified) Code example below... Anyone any ideas on the fix???

```<code><!-- BLOCK A -->
<div style="width:100%" mc:repeatable="CONTENTBLOCK_A">
<p>This is block A</p>
</div>
<!-- end of BLOCK A -->

<!-- BLOCK B -->
<div style="width:100%" mc:repeatable="CONTENTBLOCK_B">
<p>This is block B</p>
</div>
<!-- end of BLOCK B -->
</code>```

So, when creating a new campaign, if I duplicate BLOCK A and position the duplicated BLOCK A below BLOCK B - in the preview within the campaign editor it looks fine, but when I click to view it into PREVIEW MODE, or send a PREVIEW EMAIL - the duplicated BLOCK A sits above BLOCK B and below its original spawned parent BLOCK A element...

Any ideas? Are the HTML COMMENTS (e.g. < !-- --> ) The issue perhaps?

答:
Very late, but I was able to find success using this:

```<code><table mc:repeatable="content" mc:variant="variant_1">
  <tr>
    <td mc:edit="section_1">
      Variant 1 Content
    </td>
  </tr>

</table>
<table mc:repeatable="content" mc:variant="variant_2">
  <tr>
    <td mc:edit="section_2">
      Variant 2 Content
    </td>
  </tr>
</table>

<table mc:repeatable="content" mc:variant="variant_3">
  <tr>
    <td mc:edit="section_3">
      Variant 3 Content
    </td>
  </tr>
</table>
</code>```

More in depth explanation can be found here: Create Editable Content Areas with MailChimp’s Template Language

Body:
I am creating a custom MailChimp template but having issues when using the mc:repeatable element. I have it on a  wrapped around a block of code and in the editor when creating a campaign, it works fine, I can spawn a new version of the parent block and move it around in the template, but when I preview, or send the email, the child block that was spawned from the parent sits below it's parent and not where I have placed it following spawning it from the parent block... Something seems to be wrong? (Heavily simplified) Code example below... Anyone any ideas on the fix???

This is block A

This is block B

So, when creating a new campaign, if I duplicate BLOCK A and position the duplicated BLOCK A below BLOCK B - in the preview within the campaign editor it looks fine, but when I click to view it into PREVIEW MODE, or send a PREVIEW EMAIL - the duplicated BLOCK A sits above BLOCK B and below its original spawned parent BLOCK A element...

Any ideas? Are the HTML COMMENTS (e.g. < !-- --> ) The issue perhaps?

Body:
Very late, but I was able to find success using this:

<table mc:repeatable="content" mc:variant="variant_1">
  <tr>
    <td mc:edit="section_1">
      Variant 1 Content
    </td>
  </tr>

</table>
<table mc:repeatable="content" mc:variant="variant_2">
  <tr>
    <td mc:edit="section_2">
      Variant 2 Content
    </td>
  </tr>
</table>

<table mc:repeatable="content" mc:variant="variant_3">
  <tr>
    <td mc:edit="section_3">
      Variant 3 Content
    </td>
  </tr>
</table>

More in depth explanation can be found here: Create Editable Content Areas with MailChimp’s Template Language


问:
Python not finding modules that I have added to PYTHONPATH?
My file structure looks like this:

```<code>main
--src_module
----__init__.py
----utils.py
----tests
------test.py
</code>```

PYTHONPATH looks like: '/Users/myName/main/src_module'

test.py has the line:

```<code>from src_module.utils import something
</code>```

but when I try to run python test.py, I get the following error:

```<code>ImportError: No module named src_module.utils
</code>```

I was under the impression that adding the src_module folder to PYTHONPATH would fix this problem, but clearly it hasn't.  Can someone explain to me why I'm still experiencing these import errors?

答:
You can access the utils.py file from tests directory with this structure.

```<code>main
--src_module
----__init__.py
----utils.py
--tests
----__init__.py
----test.py
</code>```

Also you can use a test runner like nose2 to run your tests with command nose2 or if you would like to run the test.py file by itself then you can run via

```<code>python -m tests.test
</code>```

Body:
My file structure looks like this:

main
--src_module
----__init__.py
----utils.py
----tests
------test.py

PYTHONPATH looks like: '/Users/myName/main/src_module'

test.py has the line:

from src_module.utils import something

but when I try to run python test.py, I get the following error:

ImportError: No module named src_module.utils

I was under the impression that adding the src_module folder to PYTHONPATH would fix this problem, but clearly it hasn't.  Can someone explain to me why I'm still experiencing these import errors?

Body:
You can access the utils.py file from tests directory with this structure.

main
--src_module
----__init__.py
----utils.py
--tests
----__init__.py
----test.py

Also you can use a test runner like nose2 to run your tests with command nose2 or if you would like to run the test.py file by itself then you can run via

python -m tests.test


问:
Start or ensure that Delayed Job runs when an application/server restarts
We have to use delayed_job (or some other background-job processor) to run jobs in the background, but we're not allowed to change the boot scripts/boot-levels on the server. This means that the daemon is not guaranteed to remain available if the provider restarts the server (since the daemon would have been started by a capistrano recipe that is only run once per deployment).

Currently, the best way I can think of to ensure the delayed_job daemon is always running, is to add an initializer to our Rails application that checks if the daemon is running. If it's not running, then the initializer starts the daemon, otherwise, it just leaves it be.

The question, therefore, is how do we detect that the Delayed_Job daemon is running from inside a script? (We should be able to start up a daemon fairly easily, bit I don't know how to detect if one is already active).

Anyone have any ideas?

Regards,
Bernie

Based on the answer below, this is what I came up with. Just put it in config/initializers and you're all set:

```<code>#config/initializers/delayed_job.rb

DELAYED_JOB_PID_PATH = "#{Rails.root}/tmp/pids/delayed_job.pid"

def start_delayed_job
  Thread.new do
    `ruby script/delayed_job start`
  end
end

def process_is_dead?
  begin
    pid = File.read(DELAYED_JOB_PID_PATH).strip
    Process.kill(0, pid.to_i)
    false
  rescue
    true
  end
end

if !File.exist?(DELAYED_JOB_PID_PATH) && process_is_dead?
  start_delayed_job
end
</code>```

答:
Some more cleanup ideas: The "begin" is not needed. You should rescue "no such process" in order not to fire new processes when something else goes wrong. Rescue "no such file or directory" as well to simplify the condition.

```<code>DELAYED_JOB_PID_PATH = "#{Rails.root}/tmp/pids/delayed_job.pid"

def start_delayed_job
  Thread.new do
    `ruby script/delayed_job start`
  end
end

def daemon_is_running?
  pid = File.read(DELAYED_JOB_PID_PATH).strip
  Process.kill(0, pid.to_i)
  true
rescue Errno::ENOENT, Errno::ESRCH   # file or process not found
  false
end

start_delayed_job unless daemon_is_running?
</code>```

Keep in mind that this code won't work if you start more than one worker. And check out the "-m" argument of script/delayed_job which spawns a monitor process along with the daemon(s).

Body:
We have to use delayed_job (or some other background-job processor) to run jobs in the background, but we're not allowed to change the boot scripts/boot-levels on the server. This means that the daemon is not guaranteed to remain available if the provider restarts the server (since the daemon would have been started by a capistrano recipe that is only run once per deployment).

Currently, the best way I can think of to ensure the delayed_job daemon is always running, is to add an initializer to our Rails application that checks if the daemon is running. If it's not running, then the initializer starts the daemon, otherwise, it just leaves it be.

The question, therefore, is how do we detect that the Delayed_Job daemon is running from inside a script? (We should be able to start up a daemon fairly easily, bit I don't know how to detect if one is already active).

Anyone have any ideas?

Regards,
Bernie

Based on the answer below, this is what I came up with. Just put it in config/initializers and you're all set:

#config/initializers/delayed_job.rb

DELAYED_JOB_PID_PATH = "#{Rails.root}/tmp/pids/delayed_job.pid"

def start_delayed_job
  Thread.new do
    `ruby script/delayed_job start`
  end
end

def process_is_dead?
  begin
    pid = File.read(DELAYED_JOB_PID_PATH).strip
    Process.kill(0, pid.to_i)
    false
  rescue
    true
  end
end

if !File.exist?(DELAYED_JOB_PID_PATH) && process_is_dead?
  start_delayed_job
end

Body:
Some more cleanup ideas: The "begin" is not needed. You should rescue "no such process" in order not to fire new processes when something else goes wrong. Rescue "no such file or directory" as well to simplify the condition.

DELAYED_JOB_PID_PATH = "#{Rails.root}/tmp/pids/delayed_job.pid"

def start_delayed_job
  Thread.new do
    `ruby script/delayed_job start`
  end
end

def daemon_is_running?
  pid = File.read(DELAYED_JOB_PID_PATH).strip
  Process.kill(0, pid.to_i)
  true
rescue Errno::ENOENT, Errno::ESRCH   # file or process not found
  false
end

start_delayed_job unless daemon_is_running?

Keep in mind that this code won't work if you start more than one worker. And check out the "-m" argument of script/delayed_job which spawns a monitor process along with the daemon(s).


问:
WPF ComboBox SelectedItem dynamic binding
I'd like to bind the SelectedItem of a ComboBox to a specific item of an ObservableCollection inside the ViewModel.

In the ViewModel I have one ObservableCollection property:

```<code>Public Property SourceList As ObservableCollection(Of CustomItem)
</code>```

Then I have these two custom class

```<code>Public Class CustomItem
    Public Property Code As String
    Public Property Source As List(Of CustomValue)
    Public Property Selection As Object
End Class

Public Class CustomValue
    Public Property Id As Integer
    Public Property Desc As String
End Class
</code>```

The ComboBox in XAML

```<code><Border Tag="10">
    <ComboBox DisplayMemberPath="Desc">
            <ComboBox.ItemsSource>
                <MultiBinding Converter="{StaticResource comboSourceConverter}">
                    <Binding Path="SourceList"/>
                    <Binding Path="Tag" RelativeSource="{RelativeSource AncestorLevel=1, Mode=FindAncestor, AncestorType=Border}" />
                </MultiBinding>
            </ComboBox.ItemsSource>
        </ComboBox>
</Border>
</code>```

The converter I use to set the ItemsSource, which works correctly.

```<code>Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
    If values(0) IsNot Nothing AndAlso values(1) IsNot Nothing Then
        Return DirectCast(values(0), ObservableCollection(Of CustomItem)).Where(Function(x) x.Code = CStr(values(1))).First().Source
    End If
    Return Binding.DoNothing
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
    Throw New NotImplementedException
End Function
</code>```

I tried to do something similar for the SelectedItem.
In the XAML:

```<code><Border Tag="10">
<ComboBox DisplayMemberPath="Desc">
        <ComboBox.ItemsSource>
            <MultiBinding Converter="{StaticResource comboSourceConverter}">
                <Binding Path="SourceList"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource AncestorLevel=1, Mode=FindAncestor, AncestorType=Border}" />
            </MultiBinding>
        </ComboBox.ItemsSource>
        <ComboBox.SelectedItem>
            <MultiBinding Converter="{StaticResource comboSourceConverter}">
                <Binding Path="SourceList"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource AncestorLevel=1, Mode=FindAncestor, AncestorType=Border}" />
            </MultiBinding>
        </ComboBox.SelectedItem>
    </ComboBox>
</code>```

The converter return the correct value chosen in the ComboBox, but this way it will raise the Set method on the SourceList property since it is the one declared as the first Path in the Multibinding.

```<code>Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
    If values(0) IsNot Nothing AndAlso values(1) IsNot Nothing Then
        Return DirectCast(values(0), ObservableCollection(Of CustomItem)).Where(Function(x) x.Code = CStr(values(1))).First().Selection
End If
    Return Binding.DoNothing
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
    Return New Object(){value}
End Function
</code>```

Setting the binding manually everything works fine, but I'd prefer doing everything through the converter if possible.

```<code>Dim _item As CustomItem = SourceList.Where(Function(x) x.Code = Border.Tag).FirstOrDefault()
Dim _binding = New Binding("Selection")
_binding.Mode = BindingMode.TwoWay
_binding.Source = _item
ComboBox.SetBinding(ComboBox.SelectedItemProperty, _binding)
</code>```

答:
You should be letting XAML do a lot more of the hard work for you. Get your CustomItem once, and bind to its properties without any fussing around.

```<code><Border DataContext="{Binding SourceList[10]}">
    <ComboBox
        DisplayMemberPath="Desc"
        ItemsSource="{Binding Source}"
        SelectedItem="{Binding Selection}"
        />
</Border>
</code>```

Body:
I'd like to bind the SelectedItem of a ComboBox to a specific item of an ObservableCollection inside the ViewModel.

In the ViewModel I have one ObservableCollection property:

Public Property SourceList As ObservableCollection(Of CustomItem)

Then I have these two custom class

Public Class CustomItem
    Public Property Code As String
    Public Property Source As List(Of CustomValue)
    Public Property Selection As Object
End Class

Public Class CustomValue
    Public Property Id As Integer
    Public Property Desc As String
End Class

The ComboBox in XAML

<Border Tag="10">
    <ComboBox DisplayMemberPath="Desc">
            <ComboBox.ItemsSource>
                <MultiBinding Converter="{StaticResource comboSourceConverter}">
                    <Binding Path="SourceList"/>
                    <Binding Path="Tag" RelativeSource="{RelativeSource AncestorLevel=1, Mode=FindAncestor, AncestorType=Border}" />
                </MultiBinding>
            </ComboBox.ItemsSource>
        </ComboBox>
</Border>

The converter I use to set the ItemsSource, which works correctly.

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
    If values(0) IsNot Nothing AndAlso values(1) IsNot Nothing Then
        Return DirectCast(values(0), ObservableCollection(Of CustomItem)).Where(Function(x) x.Code = CStr(values(1))).First().Source
    End If
    Return Binding.DoNothing
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
    Throw New NotImplementedException
End Function

I tried to do something similar for the SelectedItem.
In the XAML:

<Border Tag="10">
<ComboBox DisplayMemberPath="Desc">
        <ComboBox.ItemsSource>
            <MultiBinding Converter="{StaticResource comboSourceConverter}">
                <Binding Path="SourceList"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource AncestorLevel=1, Mode=FindAncestor, AncestorType=Border}" />
            </MultiBinding>
        </ComboBox.ItemsSource>
        <ComboBox.SelectedItem>
            <MultiBinding Converter="{StaticResource comboSourceConverter}">
                <Binding Path="SourceList"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource AncestorLevel=1, Mode=FindAncestor, AncestorType=Border}" />
            </MultiBinding>
        </ComboBox.SelectedItem>
    </ComboBox>

The converter return the correct value chosen in the ComboBox, but this way it will raise the Set method on the SourceList property since it is the one declared as the first Path in the Multibinding.

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
    If values(0) IsNot Nothing AndAlso values(1) IsNot Nothing Then
        Return DirectCast(values(0), ObservableCollection(Of CustomItem)).Where(Function(x) x.Code = CStr(values(1))).First().Selection
End If
    Return Binding.DoNothing
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
    Return New Object(){value}
End Function

Setting the binding manually everything works fine, but I'd prefer doing everything through the converter if possible.

Dim _item As CustomItem = SourceList.Where(Function(x) x.Code = Border.Tag).FirstOrDefault()
Dim _binding = New Binding("Selection")
_binding.Mode = BindingMode.TwoWay
_binding.Source = _item
ComboBox.SetBinding(ComboBox.SelectedItemProperty, _binding)

Body:
You should be letting XAML do a lot more of the hard work for you. Get your CustomItem once, and bind to its properties without any fussing around.

<Border DataContext="{Binding SourceList[10]}">
    <ComboBox
        DisplayMemberPath="Desc"
        ItemsSource="{Binding Source}"
        SelectedItem="{Binding Selection}"
        />
</Border>


问:
Patterns in Python without using lists / only range function
Trying to create the following patterns in Python without using lists and only range function or nested loops.

Patterns are like the following.

```<code>*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******
</code>```

And,

```<code>**  **
**  **
  **  *
  **  *
**  **
**  **
  **  *
</code>```

A big thanks.

Body:
Trying to create the following patterns in Python without using lists and only range function or nested loops.

Patterns are like the following.

*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******

And,

**  **
**  **
  **  *
  **  *
**  **
**  **
  **  *

A big thanks.

Body:
you can do

print '*******'
print '*  *  *'
print '*  *  *'
print '*******'
print '*  *  *'
print '*  *  *'
print '*******'

or

>>> for i in range(7):
...     if i==0 or i==3 or i==6:
...         print '*******'
...     else:
...         print '*  *  *'
...
*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******

Or there is many way...

Give a more precise question !


问:
Custom Linked List implementation garbage collection
Given a custom linked list implementation in java (from Cracking The Coding Interview)

```<code>public class Node {
    public Node next = null;
    public int data;

    public Node(int d) {
        data = d;
    }

    protected void appendToTail(int d){
        Node end = new Node(d);
        Node n = this;
        while (n.next != null) {
            n = n.next;
        }
        n.next = end;
    }
}
</code>```

If we were to create a linked list out of this and then iterate through it without a temporary variable to point to the original head, i.e.

```<code>Node list = new Node(5);
list.appendToTail(2);
list.appendToTail(4);
</code>```

Gives us a list

```<code>5 -> 2 -> 4
</code>```

What would happen if I issued

```<code>list = list.next;
</code>```

Would this be a memory leak as it would be in C? Or would Java garbage collect?

答:
The short answer: No, there will not be a memory leak.

If you are advancing the pointer to point to the second node, that means a reference to the head is lost. This is assuming you have no other references to the head.

Without any reference pointing to it, this object will be marked for garbage collection.

Body:
Given a custom linked list implementation in java (from Cracking The Coding Interview)

public class Node {
    public Node next = null;
    public int data;

    public Node(int d) {
        data = d;
    }

    protected void appendToTail(int d){
        Node end = new Node(d);
        Node n = this;
        while (n.next != null) {
            n = n.next;
        }
        n.next = end;
    }
}

If we were to create a linked list out of this and then iterate through it without a temporary variable to point to the original head, i.e.

Node list = new Node(5);
list.appendToTail(2);
list.appendToTail(4);

Gives us a list

5 -> 2 -> 4

What would happen if I issued

list = list.next;

Would this be a memory leak as it would be in C? Or would Java garbage collect?


问:
Preventing a thread from being created when memory is low
I have an application that handles TCP connections, and when a connection is made, BeginRead is called on the stream to wait for data, and the main thread resumes waiting for new connections.

Under normal circumstances, there will be only a few connections at a time, and so generally the number of worker threads created by BeginRead is not an issue. However, in the theoretical situation that many, many connections exist at the same time, eventually when a new connection is made, the call to BeginRead causes an OutOfMemoryException. I would like to prevent the thread from being created in this situation (or be informed of a better way to wait for data from multiple streams).

What are some decent ways of accomplishing this? All I can think to do is to either

a) only allow a certain number of active connections at a time, or

b) attempt to use something called a MemoryFailPoint. After reading, I think this might be the better option, but how do I know how much memory a call to BeginRead will need to do its thing safely?

答:
Look at this thread here. It can give you many answers for that.

But you can read your current memory usage of your process like this:

```<code>Process currentProcess = Process.GetCurrentProcess();
long memorySize = currentProcess.PrivateMemorySize64;
</code>```

Body:
Look at this thread here. It can give you many answers for that.

But you can read your current memory usage of your process like this:

Process currentProcess = Process.GetCurrentProcess();
long memorySize = currentProcess.PrivateMemorySize64;


问:
Windows Forms form opens in the background if I open an OpenFileDialog in its Load event
I need the user to select a file to open before they can use the main form in the program I'm writing. I wrote the following in the form's load event handler:

```<code>private void MainForm_Load(object sender, EventArgs e)
{
    if (openXmlFileDialog.ShowDialog() != DialogResult.OK)
        Application.Exit();

    fileName = openXmlFileDialog.FileName;
    Activate();
}
</code>```

After this, MainForm appears in the background in spite of calling Activate() on it.

Another problem is that if the user presses Cancel and Application.Exit() is called, it has no effect.

答:
Do this in Program.cs

```<code>[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    OpenFileDialog o = new OpenFileDialog();
    if (DialogResult.OK == o.ShowDialog())
    {
        Application.Run(new Form1(o.FileName));
    }
    else
    {
        Application.Exit();
    }
}
</code>```

In Form1.cs

```<code>string filename;
public Form1(string filename)
{
    this.filename=filename;
    InitializeComponent();
}
</code>```

Body:
I need the user to select a file to open before they can use the main form in the program I'm writing. I wrote the following in the form's load event handler:

private void MainForm_Load(object sender, EventArgs e)
{
    if (openXmlFileDialog.ShowDialog() != DialogResult.OK)
        Application.Exit();

    fileName = openXmlFileDialog.FileName;
    Activate();
}

After this, MainForm appears in the background in spite of calling Activate() on it.

Another problem is that if the user presses Cancel and Application.Exit() is called, it has no effect.

Body:
Do this in Program.cs

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    OpenFileDialog o = new OpenFileDialog();
    if (DialogResult.OK == o.ShowDialog())
    {
        Application.Run(new Form1(o.FileName));
    }
    else
    {
        Application.Exit();
    }
}

In Form1.cs

string filename;
public Form1(string filename)
{
    this.filename=filename;
    InitializeComponent();
}


问:
Regex for replacing mailto links (Javascript)
I want to write a Javascript function to replace href tags that contain a mailto link.

```<code><a href="mailto:foo@bar.com">Email me</a>!
</code>```

Should become:

```<code><a href="<%='mailto:foo@bar.com'%>">Email me</a>!
</code>```

This is for an application that feeds HTML into a third-party service, and the service is broken in that it won't accept mailto URLs, but if we mask it as a variable, it will accept it. I'm just having a hard time wrapping my non-regex-friendly brain around only replacing the inner part of the href tags.

Thanks so much for your help!

答:
You can't fully parse HTML with RegEx, but you can use an HTML parser and just parse and replace the anchor tag's href attributes with regex.

The following specifications are relevant:

The href attribute on a and area elements must have a value that is a
valid URL potentially surrounded by spaces.
...

A string is a valid URL potentially surrounded by spaces if, after
stripping leading and trailing white space from it, it is a valid URL.
...

A URL is a valid URL if it conforms to the authoring conformance
requirements in the WHATWG URL specification. [URL]

See http://w3c.github.io/html/single-page.html#valid-url

An absolute-URL string must be [...] a URL-scheme string that is an ASCII case-insensitive match for a special scheme and not an ASCII case-insensitive match for "file", followed by U+003A (:) and a scheme-relative-special-URL string ...

See https://url.spec.what

A robust regex thus has to be case insensitive and accept whitespace:

let href = " MailTO:bob@example.com  ";
let result = href.replace(/^\s*mailto:.*$/i, "<%='$&'%>");
console.log(result);```

While you can also parse anchor element attributes with regex, you need an HTML parser to find the anchor elements within your HTML documents. And since you need an HTML parser anyway, you can rely on it to extract the anchor elements and their href attributes, too.

Body:
I want to write a Javascript function to replace href tags that contain a mailto link.

Email me!

Should become:

<a href="<%='mailto:foo@bar.com'%>">Email me!

This is for an application that feeds HTML into a third-party service, and the service is broken in that it won't accept mailto URLs, but if we mask it as a variable, it will accept it. I'm just having a hard time wrapping my non-regex-friendly brain around only replacing the inner part of the href tags.

Thanks so much for your help!

Body:
You can't fully parse HTML with RegEx, but you can use an HTML parser and just parse and replace the anchor tag's href attributes with regex.

The following specifications are relevant:

The href attribute on a and area elements must have a value that is a
valid URL potentially surrounded by spaces.
...

A string is a valid URL potentially surrounded by spaces if, after
stripping leading and trailing white space from it, it is a valid URL.
...

A URL is a valid URL if it conforms to the authoring conformance
requirements in the WHATWG URL specification. [URL]

See http://w3c.github.io/html/single-page.html#valid-url

An absolute-URL string must be [...] a URL-scheme string that is an ASCII case-insensitive match for a special scheme and not an ASCII case-insensitive match for "file", followed by U+003A (:) and a scheme-relative-special-URL string ...

See https://url.spec.what

A robust regex thus has to be case insensitive and accept whitespace:

let href = " MailTO:bob@example.com  ";
let result = href.replace(/^\s*mailto:.*$/i, "&lt;%='$&'%&gt;");
console.log(result);

While you can also parse anchor element attributes with regex, you need an HTML parser to find the anchor elements within your HTML documents. And since you need an HTML parser anyway, you can rely on it to extract the anchor elements and their href attributes, too.


问:
How to make radio boxes in XAML (Xamarin Forms PCL)
I am trying to find out how to make a radio button in XAML - I see there is a way to do it in android but was wondering if there is a simple cross platform way to do it without needing additional nuget packages.  </p>

答:
This is the best I have found for the moment by the controls of xamarin.forms, I hope it helps.

XFControls

Here nugets XFControls nuget


问:
Django Admin override displayed field value
I have following model:

```<code>class Model(models.Model):

    creator = models.ForeignKey(User,related_name='com_creator',on_delete=models.SET_NULL, blank=True, null=True)
    username = models.CharField(max_length=60,default="")
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField(max_length=10000,default=" ")
    subtype = models.CharField(_("SubType"),max_length=100)
    typ = models.CharField(_("Type"),max_length=50)
    plus = models.ManyToManyField(User,related_name='com_plus', verbose_name=_('Plus'), blank=True)
    is_anonymous = models.BooleanField(_('Stay Anonymous'), blank=True, default=False)
</code>```

The values in typ and subtype are codes, like: "6_0_p", (because the original values are ridiculosly long, so I use codes and a dict to translate to human readable form).

QUESTION: How can I intercept these values in django admin and translate them to human readable form?

This is what i tried so far:

```<code>class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" )
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','typ')

    def typ(self, obj):
        self.typ = "ppp"
        obj.typ = "ppp"
        return "pppp"
</code>```

I tried returning the object, self, some other value. I also tried to set the value without using a callable just declaring "typ='xxx'". Nothing. I probably don't understand how this whole thing works ...

Any ideas will be appreciated.

答:
I think that your code doesn't work because the method name is the same as the field.

You have to change the name of field, like _typ in fields tuple, then add a method called _typ that return anything or some obj attr.

i.e:

```<code>class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" )
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','_typ')

    def _typ(self, obj):
        return "pppp"
</code>```

Body:
I have following model:

class Model(models.Model):

    creator = models.ForeignKey(User,related_name='com_creator',on_delete=models.SET_NULL, blank=True, null=True)
    username = models.CharField(max_length=60,default="")
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField(max_length=10000,default=" ")
    subtype = models.CharField(_("SubType"),max_length=100)
    typ = models.CharField(_("Type"),max_length=50)
    plus = models.ManyToManyField(User,related_name='com_plus', verbose_name=_('Plus'), blank=True)
    is_anonymous = models.BooleanField(_('Stay Anonymous'), blank=True, default=False)

The values in typ and subtype are codes, like: "6_0_p", (because the original values are ridiculosly long, so I use codes and a dict to translate to human readable form).

QUESTION: How can I intercept these values in django admin and translate them to human readable form?

This is what i tried so far:

class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" )
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','typ')

    def typ(self, obj):
        self.typ = "ppp"
        obj.typ = "ppp"
        return "pppp"

I tried returning the object, self, some other value. I also tried to set the value without using a callable just declaring "typ='xxx'". Nothing. I probably don't understand how this whole thing works ...

Any ideas will be appreciated.

Body:
I think that your code doesn't work because the method name is the same as the field.

You have to change the name of field, like _typ in fields tuple, then add a method called _typ that return anything or some obj attr.

i.e:

class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" )
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','_typ')

    def _typ(self, obj):
        return "pppp"


问:
Escape CSV file with sed or other command line tool
I have the following CSV, separated by "|".

```<code>101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017
</code>```

I have two records, 101 and 102. 102 record is divided into 2 lines. How can I used sed or other command line tools to escape the new line character with "/"?

答:
For your specific case you can use this.

$ cat lll
101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017
105|xyz|"thie is a long desc
des for xyz continue here."|2017
101|abc|this is desc|2017
101|abc|this is desc|2017
101|abc|this is desc|2017
105|xyz|"thie is a long desc
des for xyz continue here."|2017

$ perl -F'\n' -ane 'BEGIN{our $line_to_join = undef; } foreach ( @F) { if (/[a-z]+$/) { $line_to_join = $_; } elsif ($line_to_join){ print $line_to_join,"/\n",$_,"\n"; $line_to_join = undef; }else{print $_,"\n" ; $line_to_join = undef;}} ;' < lll

Output:

101|abc|this is desc|2017
102|xyz|"thie is a long desc/
des for xyz continue here."|2017
105|xyz|"thie is a long desc/
des for xyz continue here."|2017
101|abc|this is desc|2017
101|abc|this is desc|2017
101|abc|this is desc|2017
105|xyz|"thie is a long desc/
des for xyz continue here."|2017

Body:
I have the following CSV, separated by "|".

101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017

I have two records, 101 and 102. 102 record is divided into 2 lines. How can I used sed or other command line tools to escape the new line character with "/"?