问:
How to have several templates for Java files in Eclipse?
I'd like to have several different templates for new java files in Eclipse. Is this possible?

Basically when I am creating a new Java class file in Package Explorer I'd like to use a  template X as a base for new file, when I am creating a new unit test class I'd like to use template Y, when I am creating a Wicket component class I'd like to use template Z, etc.

Also is it possible to configure Eclipse so that when I create a new Java class, Eclipse will generate corresponding new unit test class automatically?

答:
I am not sure if this is what you want, but you can add new wizards to Eclipse using the org.eclipse.ui.newWizards extension point.

Here is the corresponding documentation in Eclipse help.

Another (less elegant) way of doing this is to add your own templates (e.g. DAO) under the Java editor (Window->Preferences->Java->Editor->Templates) so when you type DAO and Ctrl + Enter it, it expands to the full template you want. This way creating a new empty file, typing DAO and autocompleting would transform into a full file snippet.

Hope it helps!


来源: stackexchange

问:
Can GPS location be acquired in a phone without internet and SIM?
I'm trying to develop an android application which can acquire GPS location without using Internet and even network location using SIM. Actually, SIM will be inserted in phone and i know that location upto 500m accurate can be acquired through it. But in case of no SIM signals in the area, is it possible to acquire location?</p>

答: Yes. If you use the Location Manager, set the Provider to LocationManager.GPS_PROVIDER. If you use Google Play Services, it should work automatically.</p>

ContentLicense: CC BY-SA 3.0


问:
App doesn't fill iPhone X screen when from the app store
I have an app running in landscape mode only.
I've been modifying it to adapt to the iPhone X layout, filling the screen but only operate within the safe are atc.
When I develop and test my app starting it on the actual device from xcode, all looks fine and it uses the full iPhone X screen. But when my app is released through the app store, it only uses part of the screen. Even the splash screen is only inside the safe area, but in full screen while testing via xcode.

Any ideas what's wrong/missing?

答:
Problem solved.
I have two target that build from the same source. I was testing one through xcode and the other through TestFlight.

It's an old project from before storyboard was introduced, so they didn't have a launch screen storyboard. I had added one for the one target to make it work with the iPhone X, but not for the other. Now that both have a launch screen storyboard, all works fine.


问:
Currency and decimal numbers
I am creating a test ecommerce shop but am having problems with two things:
1) My prices have the dollar sign ($) and not the pound sign (£).
2) My prices are rounded up.

This a screenshot

From research on the net I found how to add the pound sign using the following code:

```<code>$<?= '£'. number_format($product['list_price'],2); ?>
</code>```

I had to add &pound as the £ caused and black triangle to appear.

This is the result of adding this code:

This is not exactly what I wanted. How do I have the price as £19.99? (or other).

This is the entry in the database:

Both prices (list_price and prices where entered as £24.99 (prices), and £19.99 using the insert option in phomyadim.

This is the php code relating to the products:

```<code><?php require_once 'core/init.php';
$sql = "SELECT * FROM products WHERE featured =1";
$featured = $db->query($sql);
?>
</code>```

Any help to have my currenct formatted to £, and two decimal places wil lbe appreciated.

答:
Your DB structure is incorrect, 10,0 allows for 0 decimal places. This can be seen here.

http://sqlfiddle.com/#!9/f54cd/1

Change the structure to 10,2 to allow 2 decimal places.

http://sqlfiddle.com/#!9/f1bf0f/1

You can read more about this here,

https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html

The black diamond is an encoding issue, use UTF8.

Title: Currency and decimal numbers

Body:
I am creating a test ecommerce shop but am having problems with two things:
1) My prices have the dollar sign ($) and not the pound sign (£).
2) My prices are rounded up.

This a screenshot

From research on the net I found how to add the pound sign using the following code:

$<?= '£'. number_format($product['list_price'],2); ?>

I had to add &pound as the £ caused and black triangle to appear.

This is the result of adding this code:

This is not exactly what I wanted. How do I have the price as £19.99? (or other).

This is the entry in the database:

Both prices (list_price and prices where entered as £24.99 (prices), and £19.99 using the insert option in phomyadim.

This is the php code relating to the products:

<?php require_once 'core/init.php';
$sql = "SELECT * FROM products WHERE featured =1";
$featured = $db->query($sql);
?>

Any help to have my currenct formatted to £, and two decimal places wil lbe appreciated.


问:
Shuffling biased random numbers
While thinking about this question and conversing with the participants, the idea came up that shuffling a finite set of clearly biased random numbers makes them random because you don't know the order in which they were chosen.  Is this true and if so can someone point to some resources?

EDIT:  I think I might have been a little unclear. Suppose a bad random numbers generator. Take n values. These are biased(the rng is bad). Is there a way through shuffling to make the output of the rng over multiple trials statistically match the output of a known good rng?

答:
False

The set is finite, suppose consists of n numbers. What happens if you choose n+1 numbers? Let's also consider a basic random function as implemented in many languages which gives you a random number in [0,1). However, this number is limited to three digits after the decimal giving you a set of 1000 possible numbers (0.000 - 0.999). However in most cases you will not need to use all these 1000 numbers so this amount of randomness is more than enough.

However for some uses, you will need a better random generator than this. So it all comes down to exactly how many random numbers you are going to need, and how random you need them to be.

Addition after reading original question: in the case that you have some sort of limitation (such as in the original question in which each set of selected numbers must sum up to a certain N) you are not really selected random numbers per se, but rather choosing numbers in a random order from a given set (specifically, a permutation of numbers summing up to N).

Addition to edit: Suppose your bad number generator generated the sequence (1,1,1,2,2,2). Does the permutation (1,2,2,1,1,2) satisfy your definition of random?

OwnerDisplayName: JPunyon

ContentLicense: CC BY-SA 4.0

Title: Shuffling biased random numbers

LastEditorDisplayName: JPunyon

OwnerDisplayName: Yuval A

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Yuval A


问:
Garrysmod SQL wrapper

require( "mysqloo" )
require( "tmysql4" )

isqldb = mysqloo.connect(DETAILS) || { }
isql = isqldb || { }

--[[---------------------------------------------------------
    Initialises iSQL
-----------------------------------------------------------]]
function isql.Connect(addr, u, p, database)

        print( "MySQL Connecting:", addr )
        isqldb = mysqloo.connect(addr, u, p, database, 3306)

        -- tsql hack
        tmysql.initialize(addr, u, p, database, 3306)

        function isqldb.onConnected()
            print( "MySQL Server Version:", self:serverVersion() )
            print( "MySQL Server Info:", self:serverInfo() )
            print( "MySQL Host Info:", self:hostInfo() )

            Msg("iSQL: Sucessfully connected to " .. addr .."\n")

        end

        function isqldb.onConnectionFailed(self, error)

            print( "MySQL Connection Failed! Error:", error )

        end

        isqldb:connect()

        return true
    end

--[[---------------------------------------------------------
    Query
-----------------------------------------------------------]]
function isql.Query( query, qtype )
        if not isqldb then
            MsgN("premature db call:")
            debug.Trace()
        end

        local q = isqldb:query( query )
        q:start()
        q:wait()
        if (q:error() == "") then
            return q:getData(), true
        else
            q:error()
            return nil, false
        end

    end
```

I'm trying to run this to connect and execute ony my mysql server but it won't connect or debug. Can anyone notice where im going wrong?

This is using mysqloo and tmysql4 or should i just use mysqloo

It doesn't even say successfully connected im not sure why

答:
That is not how either Mysqloo nor tmysql4, and you really shouldn't use both of them together.

Lets go ahead now:
It's DATABASE_METATABLE:onConnected() with a ":" not a "."

Same for all methods which are functions in Mysqloo.

Why write queries like that?
You have QUERY_METATABLE:onSuccess(data) and QUERY_METATABLE:onError(err, sql)

Good luck

Title: Garrysmod SQL wrapper

Body:
require( "mysqloo" )
require( "tmysql4" )

isqldb = mysqloo.connect(DETAILS) || { }
isql = isqldb || { }

--[[---------------------------------------------------------
    Initialises iSQL
-----------------------------------------------------------]]
function isql.Connect(addr, u, p, database)

        print( "MySQL Connecting:", addr )
        isqldb = mysqloo.connect(addr, u, p, database, 3306)

        -- tsql hack
        tmysql.initialize(addr, u, p, database, 3306)

        function isqldb.onConnected()
            print( "MySQL Server Version:", self:serverVersion() )
            print( "MySQL Server Info:", self:serverInfo() )
            print( "MySQL Host Info:", self:hostInfo() )

            Msg("iSQL: Sucessfully connected to " .. addr .."\n")

        end

        function isqldb.onConnectionFailed(self, error)

            print( "MySQL Connection Failed! Error:", error )

        end

        isqldb:connect()

        return true
    end

--[[---------------------------------------------------------
    Query
-----------------------------------------------------------]]
function isql.Query( query, qtype )
        if not isqldb then
            MsgN("premature db call:")
            debug.Trace()
        end

        local q = isqldb:query( query )
        q:start()
        q:wait()
        if (q:error() == "") then
            return q:getData(), true
        else
            q:error()
            return nil, false
        end

    end

I'm trying to run this to connect and execute ony my mysql server but it won't connect or debug. Can anyone notice where im going wrong?

This is using mysqloo and tmysql4 or should i just use mysqloo

It doesn't even say successfully connected im not sure why


答:
Yes, you can use GPS without any external data connection because signals from the GPS satellites are receive-only.

On a device, the permission setting is known as device-only location mode:

Device only
  This mode uses only GPS. It doesn’t use Google's Location service to provide location information. It can estimate your device's location slower and use more battery.

Title: Can GPS location be acquired in a phone without internet and SIM?

Body: I'm trying to develop an android application which can acquire GPS location without using Internet and even network location using SIM. Actually, SIM will be inserted in phone and i know that location upto 500m accurate can be acquired through it. But in case of no SIM signals in the area, is it possible to acquire location?


问:
Differentiate session timeout in codeigniter
Is is possible to have two user data to have different timeout/expiry time? Let say first data "param_1" expired in 1 day and "param_2" expired in a month. How to do that with CI session library. Something that might be like this</p>

```<code>$this->session->set_userdata('param_1', 86400);  // seconds in a day
$this->session->set_userdata('param_2', 2592000); // seconds in a month
</code>```

答: This would only be possible if you set a cookie on the client on a different domain than the normal one with a longer expiration date and verifying that instead of session data. In more practical terms, using an ajax .get on the page to a specific url that verifies both cookies without starting the session (since the session can already be expired).</p>

Body:
Is is possible to have two user data to have different timeout/expiry time? Let say first data "param_1" expired in 1 day and "param_2" expired in a month. How to do that with CI session library. Something that might be like this

$this->session->set_userdata('param_1', 86400);  // seconds in a day
$this->session->set_userdata('param_2', 2592000); // seconds in a month


问:
Cannot Post CSV file in Python
I'm having problems with a CSV file upload with requests.post method in python 3.

```<code>from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)
</code>```

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!

答:
Try opening it in binary mode? And with specific 'text/csv' mime type?

```<code>with open(csv, 'rb') as f:
    r = requests.post(url, files={'file': ('myfile.csv', f, 'text/csv', {'Expires': '0'})})
    print(r.text)
</code>```

If it still does not work, try without the binary, but still with the rest.
If it stiiill does not work, print the exact error message. And 502 (Bad Gateway) might just mean that you're not targetting the right url. (you're not targetting example.com, right?

Title: Cannot Post CSV file in Python

Body:
I'm having problems with a CSV file upload with requests.post method in python 3.

from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!

Body:
Try opening it in binary mode? And with specific 'text/csv' mime type?

with open(csv, 'rb') as f:
    r = requests.post(url, files={'file': ('myfile.csv', f, 'text/csv', {'Expires': '0'})})
    print(r.text)

If it still does not work, try without the binary, but still with the rest.
If it stiiill does not work, print the exact error message. And 502 (Bad Gateway) might just mean that you're not targetting the right url. (you're not targetting example.com, right?


问:
SUM on navigation property as Linq to SQL
I am trying to find a solution how to execute TotalConversions => Statistics.Sum(sum => sum.Conversions) on database server using Linq to SQL.

The problem with current code is that Statistics is ICollection(IEnumerable) and not IQueryable and SUM function fetch all records from database locally and only when SUM the results. This is not solution for us because Statistics contain thousands of records.

```<code>public class User : Entity
{
   public int Id { get; set; }
   public virtual ICollection<Statistic> Statistics { get; set; }
   [NotMapped]
   public int TotalConversions => Statistics.Sum(sum => sum.Conversions);
}
</code>```

Another solution which we tried is to access DbContext inside Model and execute Linq to SQL query like this

```<code>[NotMapped]
public int TotalConversions
{
    get
    {
        if (_totalConversions == null)
        {
            var databaseContext = GetDbContextFromEntity(this);
            _totalConversions = databaseContext.Statistic.Where(s => s.UserId == Id).Sum(s => s.Conversions);
        }
        return (int)_totalConversions;
    }
}
</code>```

It works fine but another problem comes here that such property can't be used inside linq query like this

```<code>_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(o=>o.TotalConversions)
</code>```

How to perform SUM in calculated property inside Model which would be executed on database server and also could be used inside select queries. Is that possible at all with EF?

答:
The problem.

```<code>[NotMapped]
public int TotalConversions => Statistics.Sum(sum => sum.Conversions);
</code>```

When you mark a property as [NotMapped], you're telling EF that this property should not exist on the database level. It will only be available in your code (i.e. when the data is in-memory, not when it is in-database).

Marking this property as [NotMapped] inherently precludes you from using a database operation (order by) using the TotalConversions property.

I see two solutions here. One is simple, the other less so.

Simple: Use the calculation in the OrderBy without a property.

You've already pretty much done this in your second example, but you can do it a bit more concisely, avoiding use of a custom property.

What you want to do is this:

```<code>_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(o => o.TotalConversions)
</code>```

You can't do this, as I mentioned. What you can do is:

```<code>_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(o => o.Statistics.Sum(sum => sum.Conversions))
</code>```

Sum() has an SQL equivalent, so Linq2SQL is able to convert it. Essentially, you have changed your request from "order the collection based on this .Net property" (which is impossible) to "order the collection based on this SQL-compatible evaluation".

However, I assume that you're trying to use a custom property in order to avoid having to copy/paste that same calculation all over your codebase. If that is your goal, I fully agree with your intentions, and that's a good enough reason to try the more complex alternative.

More complex: define your needed OrderBy parameter as a custom static User property.

You can parametrize the OrderBy parameter. First things first, The OrderBy method is a generic method with two generic types:

```<code>IOrderedQueryable<A> OrderBy<A,B>(Expression<Func<A,B>> expression) { }
</code>```

Note: This signature is simplified for the sake of example, to show you the basic input and output of an OrderBy method.

A is your entity type, in your current case that is User.

B is the type of your sorting argument. You're sorting by an integer, so B is int.

Note: Almost always, B can be inferred by the compiler (based on the lambda method you use) and doesn't need to be declared explicitly. However, for this solution you will need to know its type.

This means that for your current case, we know that the OrderBy will take a parameter of type Expression<Func<User,int>>. You can confirm this by hovering over your Orderby, IntelliSense will tell you the types of the generic parameters as they are currently defined.

Instead of defining an int property like this:

```<code>[NotMapped]
public int TotalConversions => Statistics.Sum(sum => sum.Conversions);
</code>```

You can define an expression property like this:

```<code>[NotMapped]
public static Expression<Func<User,int>> TotalConversionsLambda = (user => user.Statistics.Sum(sum => sum.Conversions));
</code>```

Notice that I made it static, because this lambda is not tied to a specific User object, we want to access it without relying on an existing User.

This is a key difference. The int property basically says "this is how you get the total conversions for this User", whereas the expression property says "this is the method for retrieving the total conversions for any given User". Instead of defining the value, we are defining the method that will give us the needed value.

This means that you can use this predefined lambda when you call OrderBy:

```<code>_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(User.TotalConversionsLambda)
</code>```

To the compiler (and EF), this is equivalent to the solution from the simpler method and will therefore work the same way. However, this has the added benefit of defining the lambda once (DRY) instead of copy/pasting it everywhere in the codebase.

The explanation.

Parametrizing expressions can be a bit bewildering. That was the case for me when I started using them, at least. So maybe a simpler explanation is in order.

Notice that we can swap a literal value:

```<code>DoSomething(5);
</code>```

for a variable that contains the value:

```<code>int myValue = 5;
DoSomething(myValue);
</code>```

This example uses an integer, but we can do this for any type (string, bool, ... should be obvious). This also works for reference types:

```<code>DoSomething(new User() { Name = "John Doe" });
</code>```

Versus:

```<code>User john = new User() { Name = "John Doe" };
DoSomething(john);
</code>```

An Expression<> is a bit convoluted (due to its complex generic typing and the lambda notation), but it works exactly the same:

```<code>DoSomething(foo => foo.BarValue);
</code>```

Versus:

```<code>Expression<Func<Foo,Bar>> myValue = (foo => foo.BarValue);
DoSomething(myValue);
</code>```

And that's all there is to it. The type is more complex, but the underlying principle is exactly the same.

Edit - Small addition

You can create an additional int property to use in code.

```<code>[NotMapped]
public static Expression<Func<User,int>> TotalConversionsLambda = (user => user.Statistics.Sum(sum => sum.Conversions));

[NotMapped]
public int TotalConversions
{
    get
    {
        return TotalConversionsLambda.Compile().Invoke(this);
    }
}
</code>```

Honestly, I do think that the repeated compilation of the expression may end up hurting you more performance-wise, compared to simply defining a property that works independently of the expression property:

```<code>[NotMapped]
public static Expression<Func<User,int>> TotalConversionsLambda = (user => user.Statistics.Sum(sum => sum.Conversions));

[NotMapped]
public int TotalConversions
{
    get
    {
        return this.Statistics.Sum(sum => sum.Conversions);
    }
}
</code>```

The choice is yours. You can use the first one if you want to (pedantically) adhere to DRY; but the performance cost of doing so may end up hurting you more than adhering to DRY will benefit you.

I don't have the exact numbers on the performance cost of compiling an expression, and I don't know where your priorities lie (performance over DRY? DRY over performance?), so I can't make the decision for you.

Body:
I am trying to find a solution how to execute TotalConversions => Statistics.Sum(sum => sum.Conversions) on database server using Linq to SQL.

The problem with current code is that Statistics is ICollection(IEnumerable) and not IQueryable and SUM function fetch all records from database locally and only when SUM the results. This is not solution for us because Statistics contain thousands of records.

public class User : Entity
{
   public int Id { get; set; }
   public virtual ICollection<Statistic> Statistics { get; set; }
   [NotMapped]
   public int TotalConversions => Statistics.Sum(sum => sum.Conversions);
}

Another solution which we tried is to access DbContext inside Model and execute Linq to SQL query like this

[NotMapped]
public int TotalConversions
{
    get
    {
        if (_totalConversions == null)
        {
            var databaseContext = GetDbContextFromEntity(this);
            _totalConversions = databaseContext.Statistic.Where(s => s.UserId == Id).Sum(s => s.Conversions);
        }
        return (int)_totalConversions;
    }
}

It works fine but another problem comes here that such property can't be used inside linq query like this

_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(o=>o.TotalConversions)

How to perform SUM in calculated property inside Model which would be executed on database server and also could be used inside select queries. Is that possible at all with EF?

Body:
The problem.

[NotMapped]
public int TotalConversions => Statistics.Sum(sum => sum.Conversions);

When you mark a property as [NotMapped], you're telling EF that this property should not exist on the database level. It will only be available in your code (i.e. when the data is in-memory, not when it is in-database).

Marking this property as [NotMapped] inherently precludes you from using a database operation (order by) using the TotalConversions property.

I see two solutions here. One is simple, the other less so.

Simple: Use the calculation in the OrderBy without a property.

You've already pretty much done this in your second example, but you can do it a bit more concisely, avoiding use of a custom property.

What you want to do is this:

_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(o => o.TotalConversions)

You can't do this, as I mentioned. What you can do is:

_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(o => o.Statistics.Sum(sum => sum.Conversions))

Sum() has an SQL equivalent, so Linq2SQL is able to convert it. Essentially, you have changed your request from "order the collection based on this .Net property" (which is impossible) to "order the collection based on this SQL-compatible evaluation".

However, I assume that you're trying to use a custom property in order to avoid having to copy/paste that same calculation all over your codebase. If that is your goal, I fully agree with your intentions, and that's a good enough reason to try the more complex alternative.

More complex: define your needed OrderBy parameter as a custom static User property.

You can parametrize the OrderBy parameter. First things first, The OrderBy method is a generic method with two generic types:

IOrderedQueryable<A> OrderBy<A,B>(Expression<Func<A,B>> expression) { }

Note: This signature is simplified for the sake of example, to show you the basic input and output of an OrderBy method.

A is your entity type, in your current case that is User.

B is the type of your sorting argument. You're sorting by an integer, so B is int.

Note: Almost always, B can be inferred by the compiler (based on the lambda method you use) and doesn't need to be declared explicitly. However, for this solution you will need to know its type.

This means that for your current case, we know that the OrderBy will take a parameter of type Expression<Func<User,int>>. You can confirm this by hovering over your Orderby, IntelliSense will tell you the types of the generic parameters as they are currently defined.

Instead of defining an int property like this:

[NotMapped]
public int TotalConversions => Statistics.Sum(sum => sum.Conversions);

You can define an expression property like this:

[NotMapped]
public static Expression<Func<User,int>> TotalConversionsLambda = (user => user.Statistics.Sum(sum => sum.Conversions));

Notice that I made it static, because this lambda is not tied to a specific User object, we want to access it without relying on an existing User.

This is a key difference. The int property basically says "this is how you get the total conversions for this User", whereas the expression property says "this is the method for retrieving the total conversions for any given User". Instead of defining the value, we are defining the method that will give us the needed value.

This means that you can use this predefined lambda when you call OrderBy:

_context.User.Where(w=>w.Id==1 && w.Id == 2).OrderBy(User.TotalConversionsLambda)

To the compiler (and EF), this is equivalent to the solution from the simpler method and will therefore work the same way. However, this has the added benefit of defining the lambda once (DRY) instead of copy/pasting it everywhere in the codebase.

The explanation.

Parametrizing expressions can be a bit bewildering. That was the case for me when I started using them, at least. So maybe a simpler explanation is in order.

Notice that we can swap a literal value:

DoSomething(5);

for a variable that contains the value:

int myValue = 5;
DoSomething(myValue);

This example uses an integer, but we can do this for any type (string, bool, ... should be obvious). This also works for reference types:

DoSomething(new User() { Name = "John Doe" });

Versus:

User john = new User() { Name = "John Doe" };
DoSomething(john);

An Expression<> is a bit convoluted (due to its complex generic typing and the lambda notation), but it works exactly the same:

DoSomething(foo => foo.BarValue);

Versus:

Expression<Func<Foo,Bar>> myValue = (foo => foo.BarValue);
DoSomething(myValue);

And that's all there is to it. The type is more complex, but the underlying principle is exactly the same.

Edit - Small addition

You can create an additional int property to use in code.

[NotMapped]
public static Expression<Func<User,int>> TotalConversionsLambda = (user => user.Statistics.Sum(sum => sum.Conversions));

[NotMapped]
public int TotalConversions
{
    get
    {
        return TotalConversionsLambda.Compile().Invoke(this);
    }
}

Honestly, I do think that the repeated compilation of the expression may end up hurting you more performance-wise, compared to simply defining a property that works independently of the expression property:

[NotMapped]
public static Expression<Func<User,int>> TotalConversionsLambda = (user => user.Statistics.Sum(sum => sum.Conversions));

[NotMapped]
public int TotalConversions
{
    get
    {
        return this.Statistics.Sum(sum => sum.Conversions);
    }
}

The choice is yours. You can use the first one if you want to (pedantically) adhere to DRY; but the performance cost of doing so may end up hurting you more than adhering to DRY will benefit you.

I don't have the exact numbers on the performance cost of compiling an expression, and I don't know where your priorities lie (performance over DRY? DRY over performance?), so I can't make the decision for you.


问:
windows-how to get screen resolution in golang
Great guy.

I have a requirement to get the windows system screen resolution,but I can't get any useful thing about this with google.

So I look for help in stackoverflow.

Anyone know how to do it?

Thanks advance.

updates:
then I try this commandwmic desktopmonitor get screenheight screenwidth and get the answer like this:

this is the cmd:

this is go-program:

答:
We can get screen resolution through powershell, and its are arguments are its scripts.
so, I have included script in args variable.

Output is not straight forward, you will get someother extra information, try using bytes package or strings package to scan required information.

Following powershell command is retrived from here:

Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Screen]::AllScreens

```<code>package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    args := "Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Screen]::AllScreens"
    out, err := exec.Command("powershell", args).Output()
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Print(string(out))
}
</code>```

I have checked it in Windows 7 Virtual box, its working.
You can run this from Command Prompt or powershell, as this calls powershell any how.

Body:
We can get screen resolution through powershell, and its are arguments are its scripts.
so, I have included script in args variable.

Output is not straight forward, you will get someother extra information, try using bytes package or strings package to scan required information.

Following powershell command is retrived from here:

Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Screen]::AllScreens

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    args := "Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Screen]::AllScreens"
    out, err := exec.Command("powershell", args).Output()
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Print(string(out))
}

I have checked it in Windows 7 Virtual box, its working.
You can run this from Command Prompt or powershell, as this calls powershell any how.


问:
Remove minus sign from number in django tmplate
In my template I have this:

```<code>{{ gainer.total_progression }}
</code>```

Which produces -5664

I need 5664

I tried

```<code>{{ gainer.total_progression }}|slice:"1:"
</code>```

but it won't remove the -.

What is the proper way to handle this?

答:
First, your code is wrong, it should be:
{{ gainer.total_progression|slice:"1:" }}

Also, you could use cut instead of slice:
{{ gainer.total_progression|cut:"-" }}

Body:
In my template I have this:

{{ gainer.total_progression }}

Which produces -5664

I need 5664

I tried

{{ gainer.total_progression }}|slice:"1:"

but it won't remove the -.

What is the proper way to handle this?


问:
create vb project for consuming XML Web Service
I need to implement a project that will consume XML Web Service from other company. A user will retrieve data from this application. They provide a interface layout for the web service with all the functions.

Here I am to trying to create a project with VS2010 as VB project. This application will constantly pull data from the XML web service to sync with the latest data from their server.

I am confusing what types of project that I have to create and add for this whole solution with VS2010. I was thinking create a VB windows form application project first and add WCF service application to this solution.

Please, suggest me to have a right choice.
Thanks.

<---Edit----->
When the data is pulled from the web service and it will be saved in SQL server on our side. When it is updated it will be updated in our SQL server and to their server thru XML Web Service.

答:
If you are a consumer of a web API, there is no particular project type needed. If you want this to fire off over and over again, without intervention, you are restricted to a project type that can either a) work as a service or b) work as a simple executable that can be scheduled.

The easiest is the console application, sans the console window. You simply set up an executable that fires off the service call(s) and schedule with windows scheduler. A better solution, but more time consuming to create and test, is a windows service.

As far as setting up the service API in your application, you will need to get the WSDL from the client. Use this WSDL to create your proxy.

NOTE: If you are not setting up your own service, you do not need a WCF service project to consume someone else's service.


问:
NPOI does not change cell´s font color
I am trying to change a cell's font color conditionally. This is my last try:

```<code>IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}

ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}
</code>```

However, the font does not change when the condition is met. It seems like the style is applied for all cells instead of the cell I am getting within the loop. I have read some questions related to this problem but I can not make it work.

This new try is formatting all cells. No matter whether it meets the condition or not

```<code>ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

//This is how I am trying to change cells format
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
}
</code>```

Joao response would format all cells with a "normalStyle"

答:
By default, every cell will be using the same CellStyle object. If you want different styles for different cells, you have to create distinct objects.

```<code>ICellStyle redStyle = wb.CreateCellStyle();
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

ICellStyle normalStyle = wb.CreateCellStyle();
font.Color = XSSFFont.DEFAULT_FONT_COLOR;
normalStyle.SetFont(font);

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    cell.CellStyle = redStyle;
}
else
{
    cell.CellStyle = normalStyle;
}
</code>```

(Note: I have not tested this code at all. I forget whether CreateCellStyle works like that. But it should at least point you in the right direction.)

Title: NPOI does not change cell´s font color

Body:
I am trying to change a cell's font color conditionally. This is my last try:

IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}

ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}

However, the font does not change when the condition is met. It seems like the style is applied for all cells instead of the cell I am getting within the loop. I have read some questions related to this problem but I can not make it work.

This new try is formatting all cells. No matter whether it meets the condition or not

ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

//This is how I am trying to change cells format
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
}

Joao response would format all cells with a "normalStyle"

Body:
By default, every cell will be using the same CellStyle object. If you want different styles for different cells, you have to create distinct objects.

ICellStyle redStyle = wb.CreateCellStyle();
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

ICellStyle normalStyle = wb.CreateCellStyle();
font.Color = XSSFFont.DEFAULT_FONT_COLOR;
normalStyle.SetFont(font);

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    cell.CellStyle = redStyle;
}
else
{
    cell.CellStyle = normalStyle;
}

(Note: I have not tested this code at all. I forget whether CreateCellStyle works like that. But it should at least point you in the right direction.)


问:
Log in not working using scrapy
I have written scrapy code for log in to a site. first i tried for one site. It worked well. But then i changed the url and tried for other site. It is not working for that site. I used the same code without any change. What would be the problem?

```<code>        # -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class QuoteSpider(scrapy.Spider):
    name = 'Quote'
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = (
        'http://quotes.toscrape.com/login',
    )

    def parse(self, response):
        token=response.xpath('//input[@name="csrf_token"]/@value').extract_first()

        return FormRequest.from_response(response,formdata={'csrf_token':token,'password':'foo','username':'foo'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)
</code>```

This worked well.

```<code>    # -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class BucketsSpider(scrapy.Spider):
    name = 'buckets'
    allowed_domains = ['http://collegekart.in/login']
    start_urls = ['http://collegekart.in/login/']

    def parse(self, response):
        token=response.xpath('//meta[@name="csrf-token"]/@content').extract_first()
        print(token)
        return FormRequest.from_response(response,formdata={'csrf-token':token,'password':'*********','username':'**************'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)
        print("yes")
</code>```

This is not working. Please help to solve this.

答:
What's wrong

`........from_response(response........

if you check the response.url, it will give you http://collegekart.in/login/ instead of http://collegekart.in/

allowed_domains =['http://collegekart.in/login']

the login GET Request of collegekart.in/ is not in your allowed_domains

How to fix it

```<code># -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class BucketsSpider(scrapy.Spider):
    name = 'buckets'
    allowed_domains = ['collegekart.in']
    start_urls = ['http://collegekart.in/login/']

    def parse(self, response):
        token=response.xpath('//meta[@name="csrf-token"]/@content').extract_first()
        print(token)
        response = response.replace(url='http://collegekart.in/')
        return FormRequest.from_response(response,formdata={'csrf-token':token, 'password':'hanfenghanfeng','username':'zerqqr1@iydhp.com'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)
        print("yes")
</code>```

Why?

If you didn't replace the url variable in response:

scrapy will send your request to an incorrect url:
http://collegekart.in/login/access/attempt_login?utf8=%E2%9C%93&username=zerqqr1%40iydhp.com&password=hanfenghanfeng

This is the correct url: http://collegekart.in/access/attempt_login?utf8=%E2%9C%93&username=zerqqr1%40iydhp.com&password=hanfenghanfeng

Login GET url is not included in allowed_domains

allowed_domains = ['http://collegekart.in/login']

Login GET url: http://collegekart.in/access/.......

Suggestions

Use Chrome's Inspector > Network to see the actual request being made when performing Login actions

Check this scrapy official tutorial (PDF Version): Link

Title: Log in not working using scrapy

Body:
I have written scrapy code for log in to a site. first i tried for one site. It worked well. But then i changed the url and tried for other site. It is not working for that site. I used the same code without any change. What would be the problem?

        # -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class QuoteSpider(scrapy.Spider):
    name = 'Quote'
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = (
        'http://quotes.toscrape.com/login',
    )

    def parse(self, response):
        token=response.xpath('//input[@name="csrf_token"]/@value').extract_first()

        return FormRequest.from_response(response,formdata={'csrf_token':token,'password':'foo','username':'foo'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)

This worked well.

    # -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class BucketsSpider(scrapy.Spider):
    name = 'buckets'
    allowed_domains = ['http://collegekart.in/login']
    start_urls = ['http://collegekart.in/login/']

    def parse(self, response):
        token=response.xpath('//meta[@name="csrf-token"]/@content').extract_first()
        print(token)
        return FormRequest.from_response(response,formdata={'csrf-token':token,'password':'*********','username':'**************'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)
        print("yes")

This is not working. Please help to solve this.

Body:
What's wrong

`........from_response(response........

if you check the response.url, it will give you http://collegekart.in/login/ instead of http://collegekart.in/

allowed_domains =['http://collegekart.in/login']

the login GET Request of collegekart.in/ is not in your allowed_domains

How to fix it

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class BucketsSpider(scrapy.Spider):
    name = 'buckets'
    allowed_domains = ['collegekart.in']
    start_urls = ['http://collegekart.in/login/']

    def parse(self, response):
        token=response.xpath('//meta[@name="csrf-token"]/@content').extract_first()
        print(token)
        response = response.replace(url='http://collegekart.in/')
        return FormRequest.from_response(response,formdata={'csrf-token':token, 'password':'hanfenghanfeng','username':'zerqqr1@iydhp.com'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)
        print("yes")

Why?

If you didn't replace the url variable in response:

scrapy will send your request to an incorrect url:
http://collegekart.in/login/access/attempt_login?utf8=%E2%9C%93&username=zerqqr1%40iydhp.com&password=hanfenghanfeng

This is the correct url: http://collegekart.in/access/attempt_login?utf8=%E2%9C%93&username=zerqqr1%40iydhp.com&password=hanfenghanfeng

Login GET url is not included in allowed_domains

allowed_domains = ['http://collegekart.in/login']

Login GET url: http://collegekart.in/access/.......

Suggestions

Use Chrome's Inspector > Network to see the actual request being made when performing Login actions

Check this scrapy official tutorial (PDF Version): Link


问:
malloc : error double free with printf and a NULL wchar_t*
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

```<code>//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}
</code>```

Compiled with gcc:

```<code>gcc main.cpp -o test
</code>```

The output of the execution:

```<code>a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug
</code>```

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?

答:
You cannot print NULL pointers as strings, that's undefined behavior.  From the C99 standard, §7.19.6.1/8

The conversion specifiers and their meanings are:

  ...

  s     If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. ...

If an l length modifier is present, the argument shall be a pointer to the initial
  element of an array of wchar_t type.

Since NULL pointers are not explicitly allowed, they are disallowed.  You should change your code to something like:

```<code>printf("a=%ls, b=%ls \n", L"a", b ? b : L"(null)");
</code>```

Body:
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}

Compiled with gcc:

gcc main.cpp -o test

The output of the execution:

a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?

Body:
You cannot print NULL pointers as strings, that's undefined behavior.  From the C99 standard, §7.19.6.1/8

The conversion specifiers and their meanings are:

  ...

  s     If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. ...

If an l length modifier is present, the argument shall be a pointer to the initial
  element of an array of wchar_t type.

Since NULL pointers are not explicitly allowed, they are disallowed.  You should change your code to something like:

printf("a=%ls, b=%ls \n", L"a", b ? b : L"(null)");


问:
Connect to RavenDB using nodejs
I am using node to connect to RavenDB
https://www.npmjs.com/package/ravendb

but when try to create a connection, at this step
https://i.stack.imgur.com/fcFZ9.png

I dont know what to put in database url and default database name
and I put

database url=localhost:5000

default database name=test (my db name is test)

and the console show this error Failed to load http://localhost:5000/topology?name=test
how can I create this connection.

EDIT
I config the program

this is my file app.js

const DocumentStore = require('ravendb').default;
const store = DocumentStore.create('localhost:5000', 'test');
store.initialize();
const session = store.openSession();

when I run this file with node, it show the error: (but it will compile fine if I delete the line
const session = store.openSession(); so I think the problem is somewhere around the session.

Error log:

"C:\Program Files\JetBrains\WebStorm 2017.2\bin\runnerw.exe" D:\nodejs\node.exe D:\nodeProject\demoraven\app.js
Unhandled rejection ee: Node localhost:5000 is down
    at d.finally.catch.e (D:\nodeProject\demoraven\node_modules\ravendb\lib\ravendb-node.js:2:52762)
    at tryCatcher (D:\nodeProject\demoraven\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (D:\nodeProject\demoraven\node_modules\bluebird\js\release\promise.js:689:18)
    at Async._drainQueue (D:\nodeProject\demoraven\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (D:\nodeProject\demoraven\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (D:\nodeProject\demoraven\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)

答:
as @Judah Himango  said , you can test whether your code is able to connect to revendb database using url provided by him .

I think you are using the wrong port to connect to ravendb , i.e you should set database url=localhost:8080 instead of localhost:5000 as the default port of ravendb is 8080

Title: Connect to RavenDB using nodejs


问:
cURL GET service response is blank in SOAPUI
```<code>import groovy.json.JsonSlurper

def appToken = "8ry+2bvULHbuYMu75bl80vDBYC3sDbq26JUpCNd19Is="
def downloadURL = "https://api.thetradedesk.com/v3/myreports/view/9411002/538769/1507695066?sig=C0G46d8hyTJGk8blhW8smgo27JzaWDjaNogtVQaJ-Lg."

def result

def process = ["path\\curl.exe", "-X", "GET", downloadURL,
            "-H", "cache-control: no-cache",
            "-H", "postman-token: 21cc8561-8e79-0e85-ad60-ea6e4b69dda2",
            "-H", "ttd-auth:"+appToken]

result = process.execute()
/*def slurper = new groovy.json.JsonSlurper()
def jsonSlurper = slurper.parseText(slurper)*/

log.info result.text
</code>```

<p>=======================================
    When i run above groovy script in SOAP UI, it returns blank response while it is working in POSTMAN.</p>

```<code>Pl. Note: App Token expires in every 5 mins so this token wont be valid after my post, please suggest me how to handle GET response using SOAP UI for cURL request?
</code>```

答:
Try writing your command as a single string where you concatenate variables using + such as:
def process = "path\\curl.exe -X, GET "+ downloadURL+ "-H, cache-control: no-cache, -H, postman-token: 21cc8561-8e79-0e85-ad60-ea6e4b69dda2, -H, ttd-auth: "+appToken
after that do a
log.info process to check your command in between creating and running it.

Body:
import groovy.json.JsonSlurper

def appToken = "8ry+2bvULHbuYMu75bl80vDBYC3sDbq26JUpCNd19Is="
def downloadURL = "https://api.thetradedesk.com/v3/myreports/view/9411002/538769/1507695066?sig=C0G46d8hyTJGk8blhW8smgo27JzaWDjaNogtVQaJ-Lg."

def result

def process = ["path\\curl.exe", "-X", "GET", downloadURL,
            "-H", "cache-control: no-cache",
            "-H", "postman-token: 21cc8561-8e79-0e85-ad60-ea6e4b69dda2",
            "-H", "ttd-auth:"+appToken]

result = process.execute()
/*def slurper = new groovy.json.JsonSlurper()
def jsonSlurper = slurper.parseText(slurper)*/

log.info result.text

=======================================
    When i run above groovy script in SOAP UI, it returns blank response while it is working in POSTMAN.

Pl. Note: App Token expires in every 5 mins so this token wont be valid after my post, please suggest me how to handle GET response using SOAP UI for cURL request?


问:
Unity activation from Command line
Is it possible to run not-activated Unity Personal Edition (no serial number) via Command Line? If I pass username and password it still asks to select type of License.

答: Nope, the only function of those parameters are to pre-fill uservame and password, but unity needs to be activated as well, otherwise the popup shows to proceed with the activation.</p>

Title: Unity activation from Command line


问:
Out of two hazelcast instances how to make eviction event to be consumed just by one of them?
When using controlled eviction with added TTL like:

```<code>myMap.put( "1", "John", 50, TimeUnit.SECONDS )
</code>```

On two application instances using hazelcast which belong to the same group and identify each other correctly during startup, when implementing our own EntryExpiredListener, we notice that both instances receive the same event in:

```<code>@Override
public void entryExpired(EntryEvent<String, SomeObject> event) {
       ...
}
</code>```

We would expect only one hazelcast instance to process the event, is this correct behavior? How can we configure just one instance to consume such event.

答:
Found the solution, the IMap has method addLocalEntryListener , registering listener such way will make events to come just to the instance which owns the entries.

```<code>Also note that entries can migrate to
other nodes for load balancing and/or membership change.
</code>```

Body:
When using controlled eviction with added TTL like:

myMap.put( "1", "John", 50, TimeUnit.SECONDS )

On two application instances using hazelcast which belong to the same group and identify each other correctly during startup, when implementing our own EntryExpiredListener, we notice that both instances receive the same event in:

@Override
public void entryExpired(EntryEvent<String, SomeObject> event) {
       ...
}

We would expect only one hazelcast instance to process the event, is this correct behavior? How can we configure just one instance to consume such event.

Body:
Found the solution, the IMap has method addLocalEntryListener , registering listener such way will make events to come just to the instance which owns the entries.

Also note that entries can migrate to
other nodes for load balancing and/or membership change.


问:
Can't run Linux "awk" command in script from PHP
I have the shell script "test.sh":

```<code>  #!/system/bin/sh

  PID=$(ps | grep logcat | grep root |grep -v grep | awk '{print $2}')
  echo "Using awk: $PID"

  PID=$(ps | grep logcat | grep root |grep -v grep | cut -d " " -f 7 )
  echo "Using cut: $PID"
</code>```

When I run the script from PHP:

```<code>exec("su -c sh /path/to/my/script/test.sh");
</code>```

I got this output:

```<code>Using awk:
Using cut: 6512
</code>```

So "cut" command is work but "awk" command doesn't when I run the script from PHP, but when I run it from terminal:

```<code># sh test.sh
</code>```

I can get both awk and cut work fine! This how look like the output of "ps":

```<code>USER      PID   PPID  VSIZE  RSS   WCHAN       PC         NAME
root      6512  5115  3044   1108  poll_sched b6e4bb0c S logcat
</code>```

Do I missed something?

答:
You should learn how to debug first

You said

So "cut" command is work but "awk" command doesn't when I run the
  script from PHP, but when I run it from terminal:

I wonder how ?

actually throws error like below, in CLI

```<code>$ php -r 'exec("su -c sh /path/to/my/script/test.sh");'
su: user /path/to/my/script/test.sh does not exist
</code>```

You first need below syntax while debugging code

```<code>// basic :  stdin (0) stdout (1) stderr (2)

exec('your_command 2>&1', $output, $return_status);

// to see the response from your command
// su: user /path/to/my/script/test.sh does not exist
print_r($output);
</code>```

Remember :

su gives you root permissions but it does not change the PATH variable and current working directory.

The operating system assumes that, in the absence of a username, the
  user wants to change to a root session, and thus the user is prompted
  for the root password

```<code>[akshay@localhost Desktop]$ su
Password:
[root@localhost Desktop]# pwd
/home/akshay/Desktop
[root@localhost Desktop]# exit
exit

[akshay@localhost Desktop]$ su -
Password:
[root@localhost ~]# pwd
/root
</code>```

Solution:

You should allow executing your script without password prompt ( don't use su use sudo )

To allow apache user to execute your script and some commands you may make entry like below in /etc/sudoers

```<code># which awk => give you awk path
# same use in your script also, or else set path variable
www-data ALL=NOPASSWD: /path/to/my/script/test.sh, /bin/cut, /usr/bin/awk
</code>```

So it becomes :

```<code>// assuming your script is executable
exec("sudo /path/to/my/script/test.sh 2>&1", $output);
print_r($output);
</code>```

Body:
I have the shell script "test.sh":

  #!/system/bin/sh

  PID=$(ps | grep logcat | grep root |grep -v grep | awk '{print $2}')
  echo "Using awk: $PID"

  PID=$(ps | grep logcat | grep root |grep -v grep | cut -d " " -f 7 )
  echo "Using cut: $PID"

When I run the script from PHP:

exec("su -c sh /path/to/my/script/test.sh");

I got this output:

Using awk:
Using cut: 6512

So "cut" command is work but "awk" command doesn't when I run the script from PHP, but when I run it from terminal:

# sh test.sh

I can get both awk and cut work fine! This how look like the output of "ps":

USER      PID   PPID  VSIZE  RSS   WCHAN       PC         NAME
root      6512  5115  3044   1108  poll_sched b6e4bb0c S logcat

Do I missed something?

Body:
You should learn how to debug first

You said

So "cut" command is work but "awk" command doesn't when I run the
  script from PHP, but when I run it from terminal:

I wonder how ?

actually throws error like below, in CLI

$ php -r 'exec("su -c sh /path/to/my/script/test.sh");'
su: user /path/to/my/script/test.sh does not exist

You first need below syntax while debugging code

// basic :  stdin (0) stdout (1) stderr (2)

exec('your_command 2>&1', $output, $return_status);

// to see the response from your command
// su: user /path/to/my/script/test.sh does not exist
print_r($output);

Remember :

su gives you root permissions but it does not change the PATH variable and current working directory.

The operating system assumes that, in the absence of a username, the
  user wants to change to a root session, and thus the user is prompted
  for the root password

[akshay@localhost Desktop]$ su
Password:
[root@localhost Desktop]# pwd
/home/akshay/Desktop
[root@localhost Desktop]# exit
exit

[akshay@localhost Desktop]$ su -
Password:
[root@localhost ~]# pwd
/root

Solution:

You should allow executing your script without password prompt ( don't use su use sudo )

To allow apache user to execute your script and some commands you may make entry like below in /etc/sudoers

# which awk => give you awk path
# same use in your script also, or else set path variable
www-data ALL=NOPASSWD: /path/to/my/script/test.sh, /bin/cut, /usr/bin/awk

So it becomes :

// assuming your script is executable
exec("sudo /path/to/my/script/test.sh 2>&1", $output);
print_r($output);


问:
Eclipse - how to handle custom projects creation
I want to develop capability in my own Eclipse feature to create projects of  my own DSL languages - in other words, I want have wizard so I can click New > My Custom Project, then fill in all necessary fields in wizard pages and then, after perform Finish I want basic folders hierarchy and template files to be created and my DSL nature to be added. I know how to create plugins/features, as good as Wizard. I can create everything in "hard-code", I mean create folders and files, but maybe there is some build-in solution to facilitate it? I found IProject interface with its stuff, is it a good clue?

答:
Assuming your plug-in contains a subfolder template with all template files, you can copy the file structure recursively into the newly created project:

```<code>Bundle bundle = MyPlugin.getDefault().getBundle();
String templateFolderName = "template";
for (Enumeration entries = bundle.findEntries(templateFolderName, "*", true);
        entries.hasMoreElements();) {
    URL url = (URL) entries.nextElement();
    String path = url.getPath();
    if (!path.startsWith("/" + templateFolderName + "/"))
        throw new InvocationTargetException(
                new Throwable("Unknown template file: " + path));

    // create folder or file (overwrite if file already exists)
    String targetPath = path.substring(("/" + templateFolderName).length());
    if (path.endsWith("/")) {
        IFolder folder = project.getFolder(targetPath);
        if (! folder.exists()) {
            folder.create(false, true, null);
        }
    } else {
        InputStream in = url.openStream();
        IFile file = project.getFile(targetPath);
        if (file.exists()) {
            file.delete(true, null);
        }
        file.create(in, true, null);
    }
}
</code>```

(see the source of the code snippet above)

See for example this implementation of a customized New Project wizard dialog.

Body:
Assuming your plug-in contains a subfolder template with all template files, you can copy the file structure recursively into the newly created project:

Bundle bundle = MyPlugin.getDefault().getBundle();
String templateFolderName = "template";
for (Enumeration entries = bundle.findEntries(templateFolderName, "*", true);
        entries.hasMoreElements();) {
    URL url = (URL) entries.nextElement();
    String path = url.getPath();
    if (!path.startsWith("/" + templateFolderName + "/"))
        throw new InvocationTargetException(
                new Throwable("Unknown template file: " + path));

    // create folder or file (overwrite if file already exists)
    String targetPath = path.substring(("/" + templateFolderName).length());
    if (path.endsWith("/")) {
        IFolder folder = project.getFolder(targetPath);
        if (! folder.exists()) {
            folder.create(false, true, null);
        }
    } else {
        InputStream in = url.openStream();
        IFile file = project.getFile(targetPath);
        if (file.exists()) {
            file.delete(true, null);
        }
        file.create(in, true, null);
    }
}

(see the source of the code snippet above)

See for example this implementation of a customized New Project wizard dialog.


问:
read line by line with awk and parse variables
I have a script that read log files and parse the data to insert them to mysql table..

My script looks like

```<code>while read x;do
var=$(echo ${x}|cut -d+ -f1)
var2=$(echo ${x}|cut -d_ -f3)
...
echo "$var,$var2,.." >> mysql.infile
done<logfile
</code>```

The Problem is that log files are thousands of lines and taking hours....

I read that awk is better, I tried, but don't know the syntax to parse the variables...

EDIT:
inputs are structure firewall logs so they are pretty large files like

@timestamp $HOST reason="idle Timeout" source-address="x.x.x.x"
  source-port="19219" destination-address="x.x.x.x"
  destination-port="53" service-name="dns-udp" application="DNS"....

So I'm using a lot of grep for ~60 variables e.g

```<code>sourceaddress=$(echo ${x}|grep -P -o '.{0,0}
source-address=\".{0,50}'|cut -d\" -f2)
</code>```

if you think perl will be better I'm open to suggestions and maybe a hint how to script it...

答:
if you're extracting the values in order, something like this will help

```<code>$ awk -F\" '{for(i=2;i<=NF;i+=2) print $i}' file

idle Timeout
x.x.x.x
19219
x.x.x.x
53
dns-udp
DNS
</code>```

you can easily change the output format as well

```<code>$ awk -F\" -v OFS=, '{for(i=2;i<=NF;i+=2)
                        printf "%s", $i ((i>NF-2)?ORS:OFS)}' file

idle Timeout,x.x.x.x,19219,x.x.x.x,53,dns-udp,DNS
</code>```

Body:
I have a script that read log files and parse the data to insert them to mysql table..

My script looks like

while read x;do
var=$(echo ${x}|cut -d+ -f1)
var2=$(echo ${x}|cut -d_ -f3)
...
echo "$var,$var2,.." >> mysql.infile
done<logfile

The Problem is that log files are thousands of lines and taking hours....

I read that awk is better, I tried, but don't know the syntax to parse the variables...

EDIT:
inputs are structure firewall logs so they are pretty large files like

@timestamp $HOST reason="idle Timeout" source-address="x.x.x.x"
  source-port="19219" destination-address="x.x.x.x"
  destination-port="53" service-name="dns-udp" application="DNS"....

So I'm using a lot of grep for ~60 variables e.g

sourceaddress=$(echo ${x}|grep -P -o '.{0,0}
source-address=\".{0,50}'|cut -d\" -f2)

if you think perl will be better I'm open to suggestions and maybe a hint how to script it...

Body:
if you're extracting the values in order, something like this will help

$ awk -F\" '{for(i=2;i<=NF;i+=2) print $i}' file

idle Timeout
x.x.x.x
19219
x.x.x.x
53
dns-udp
DNS

you can easily change the output format as well

$ awk -F\" -v OFS=, '{for(i=2;i<=NF;i+=2)
                        printf "%s", $i ((i>NF-2)?ORS:OFS)}' file

idle Timeout,x.x.x.x,19219,x.x.x.x,53,dns-udp,DNS


问:
While adding a TFS server to VS2017 Error: "Server already exists in the list below"
While trying to add a TFS server to VS 2017, I encountered an issue where it claims that the server already exists in the list. However, it does not.

The only thing that I can think of that could cause it to think that the server is in the list, is that the two servers used to be one. This was not an issue with VS 2015.

The TFS servers are both 2015 update 3.

Please feel free to ask for any more info.

答: We just did the upgrade and found out that VS 2017 expects (at least for now) that there should only be 1 TFS server present, so you would need to remove the old one, then add the new one.  It's probably some confusion with the TFS Workspace. The "Connect" box may still give the error, but after removing the old, adding the new, and pressing the "Connect" button, it worked just fine for me.</p>


问:
How to click views behind a Toolbar?
I have a toolbar with a transparent/translucent background that overlays the content. So, behind the toolbar, views can appear that are clickable. The problem is that they can not be clicked through the toolbar because the toolbar is catching the click event.

I tried setting android:clickable="false", android:focusable="false" and android:focusableInTouchMode="false" for the toolbar, but it has no effect. How can I send a click through the toolbar to the underlying view?

答:
Toolbar consumes all clicks. You need to subclass Toolbar, like @Matthias Robbens already mentioned.

If you still want to be able to set a click listener on the toolbar, use this:

```<code>/** Do not eat touch events, like super does. Instead map an ACTION_DOWN to a click on this
 * view. If no click listener is set (default), we do not consume the click */
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_POINTER_DOWN){
        return performClick();
    }

    return false;
}
</code>```

Title: How to click views behind a Toolbar?

Body:
Toolbar consumes all clicks. You need to subclass Toolbar, like @Matthias Robbens already mentioned.

If you still want to be able to set a click listener on the toolbar, use this:

/** Do not eat touch events, like super does. Instead map an ACTION_DOWN to a click on this
 * view. If no click listener is set (default), we do not consume the click */
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_POINTER_DOWN){
        return performClick();
    }

    return false;
}


问:
PHP Regex to Change New Line Characters between Specific Tags
How can I change new line characters to
 which are only between
 and
 tags...?

```<code>$text = preg_replace( '#<P>(.*?)\r\n(.*?)</P>#s', '<P>$1<BR>$2</P>', $text );
</code>```

This made only the first new line character to be
.

答:
An example with a parser and a regular expression: this sets up the DOM first, queries it for p tags and then inserts the modified text back again.

```<code><?php

$html = <<<DATA
<div>
    <p class="someclass">Some very import
    information here
    and here as well
    </p>
</div>
DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

# regex
$regex = '~\R\s*~';

foreach ($xpath->query("//p") as $line) {
    $newnode = $dom->createDocumentFragment();
    $newnode->appendXML(preg_replace($regex, "<br />", $line->textContent));
    $line->nodeValue = '';
    $line->appendChild($newnode);

}

echo $dom->saveHTML();
?>
</code>```

This produces

```<code><div>
    <p class="someclass">Some very import<br>information here<br>and here as well<br></p>
</div>
</code>```

Note: this will fail for sth. like:

```<code><div>
    <p class="someclass">Some very import
    information here <img src="some-picture.png">
    and here as well
    </p>
</div>
</code>```

Body:
How can I change new line characters to
 which are only between
 and
 tags...?

$text = preg_replace( '#
(.*?)\r\n(.*?)
#s', '
$1
$2
', $text );

This made only the first new line character to be
.

Body:
An example with a parser and a regular expression: this sets up the DOM first, queries it for p tags and then inserts the modified text back again.

<?php

$html = <<<DATA
<div>
    <p class="someclass">Some very import
    information here
    and here as well
    </p>
</div>
DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

# regex
$regex = '~\R\s*~';

foreach ($xpath->query("//p") as $line) {
    $newnode = $dom->createDocumentFragment();
    $newnode->appendXML(preg_replace($regex, "<br />", $line->textContent));
    $line->nodeValue = '';
    $line->appendChild($newnode);

}

echo $dom->saveHTML();
?>

This produces

<div>
    <p class="someclass">Some very import<br>information here<br>and here as well<br></p>
</div>

Note: this will fail for sth. like:

<div>
    <p class="someclass">Some very import
    information here <img src="some-picture.png">
    and here as well
    </p>
</div>


问:
JavaFX TreeTableView and ContextMenu
In my project I have a TreeTableView with 5 columns.
I need a different context Menu for every columns.
I have created a ContextMenu in Source Builder for every columns (in the example you see only one for "value" column), but the menù appears only with right click on column header, but I need the menù appears only on right click on cell value

```<code>      <TreeTableView fx:id="valueTable" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
    <columns>
      <TreeTableColumn fx:id="context" prefWidth="483.20001524686813" sortable="false" text="Context" />
      <TreeTableColumn fx:id="tag" minWidth="50.0" prefWidth="90.0" sortable="false" text="Tag" />
      <TreeTableColumn fx:id="offset" minWidth="50.0" prefWidth="90.0" sortable="false" text="OffSet" />
      <TreeTableColumn fx:id="lenght" minWidth="50.0" prefWidth="90.0" sortable="false" text="Lenght" />
      <TreeTableColumn fx:id="value" prefWidth="367.99993896484375" sortable="false" text="Value">
           <contextMenu>
              <ContextMenu fx:id="contextMenuValue" >
                <items>
                  <MenuItem mnemonicParsing="false" text="Action 1" />
                  <MenuItem mnemonicParsing="false" text="Action 2" />
                  <MenuItem mnemonicParsing="false" text="Action 3" />
                  <MenuItem mnemonicParsing="false" text="Action 4" />
                </items>
              </ContextMenu>
           </contextMenu>
      </TreeTableColumn>
    </columns>
  </TreeTableView>
</code>```

I try to add this code for check the MouseClick event, but event is intercepted only on TreeTableView "valueTable" and not on TreeTableColumn "value".

```<code>        value.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
                System.out.println("Work Cell");
        });
        valueTable.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
            System.out.println("Work Table");
        });
</code>```

Can you help me?
Regard.

答:
You can do it by implementing a custom TreeTableCell then add the ContextMenu to the cell instead of the column like:

```<code>public class Controller implements Initializable {

    @FXML
    private TreeTableView<MyModel> table;
    @FXML
    private TreeTableColumn<MyModel, String> first;
    @FXML
    private TreeTableColumn<MyModel, Boolean> second;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        first.setCellValueFactory(data -> data.getValue().getValue().nameProperty());
        first.setCellFactory(cell -> new MyCell());
        second.setCellValueFactory(data -> data.getValue().getValue().selectedProperty());

        MyModel john = new MyModel("John");
        MyModel andrew = new MyModel("Andrew");

        table.setRoot(new TreeItem<>());
        table.setShowRoot(false);
        table.getRoot().getChildren().add(new TreeItem<>(john));
        table.getRoot().getChildren().add(new TreeItem<>(andrew));

    }

    private class MyModel {

        private StringProperty name;
        private BooleanProperty selected;

        MyModel(String name) {
            this.name = new SimpleStringProperty(name);
            this.selected = new SimpleBooleanProperty(false);
        }

        StringProperty nameProperty() {
            return name;
        }

        BooleanProperty selectedProperty() {
            return selected;
        }
    }

    private class MyMenu extends ContextMenu {
        MyMenu() {
            getItems().add(new MenuItem("Test"));
            getItems().add(new MenuItem("Item"));

        }
    }

    private class MyCell extends TreeTableCell<MyModel, String> {
        MyCell() {
            // Here you can set the same menu for each cell. Then the column is having the same cell for every row
            setContextMenu(new MyMenu());
        }

        // Overridden just to show the text of the cell.
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
            } else {
                contextMenuProperty().bind(Bindings
                    // here you can define your own condition
                    .when(getTreeTableRow().getTreeItem().getValue().selectedProperty())
                    .then(new MyMenu())
                    .otherwise((MyMenu) null));
                setText(item);
            }
        }
    }

}
</code>```

Of course you can set a different menu for the second column same as it is set for the first one.

Title: JavaFX TreeTableView and ContextMenu

Body:
In my project I have a TreeTableView with 5 columns.
I need a different context Menu for every columns.
I have created a ContextMenu in Source Builder for every columns (in the example you see only one for "value" column), but the menù appears only with right click on column header, but I need the menù appears only on right click on cell value

      <TreeTableView fx:id="valueTable" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
    <columns>
      <TreeTableColumn fx:id="context" prefWidth="483.20001524686813" sortable="false" text="Context" />
      <TreeTableColumn fx:id="tag" minWidth="50.0" prefWidth="90.0" sortable="false" text="Tag" />
      <TreeTableColumn fx:id="offset" minWidth="50.0" prefWidth="90.0" sortable="false" text="OffSet" />
      <TreeTableColumn fx:id="lenght" minWidth="50.0" prefWidth="90.0" sortable="false" text="Lenght" />
      <TreeTableColumn fx:id="value" prefWidth="367.99993896484375" sortable="false" text="Value">
           <contextMenu>
              <ContextMenu fx:id="contextMenuValue" >
                <items>
                  <MenuItem mnemonicParsing="false" text="Action 1" />
                  <MenuItem mnemonicParsing="false" text="Action 2" />
                  <MenuItem mnemonicParsing="false" text="Action 3" />
                  <MenuItem mnemonicParsing="false" text="Action 4" />
                </items>
              </ContextMenu>
           </contextMenu>
      </TreeTableColumn>
    </columns>
  </TreeTableView>

I try to add this code for check the MouseClick event, but event is intercepted only on TreeTableView "valueTable" and not on TreeTableColumn "value".

        value.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
                System.out.println("Work Cell");
        });
        valueTable.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
            System.out.println("Work Table");
        });

Can you help me?
Regard.

Body:
You can do it by implementing a custom TreeTableCell then add the ContextMenu to the cell instead of the column like:

public class Controller implements Initializable {

    @FXML
    private TreeTableView<MyModel> table;
    @FXML
    private TreeTableColumn<MyModel, String> first;
    @FXML
    private TreeTableColumn<MyModel, Boolean> second;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        first.setCellValueFactory(data -> data.getValue().getValue().nameProperty());
        first.setCellFactory(cell -> new MyCell());
        second.setCellValueFactory(data -> data.getValue().getValue().selectedProperty());

        MyModel john = new MyModel("John");
        MyModel andrew = new MyModel("Andrew");

        table.setRoot(new TreeItem<>());
        table.setShowRoot(false);
        table.getRoot().getChildren().add(new TreeItem<>(john));
        table.getRoot().getChildren().add(new TreeItem<>(andrew));

    }

    private class MyModel {

        private StringProperty name;
        private BooleanProperty selected;

        MyModel(String name) {
            this.name = new SimpleStringProperty(name);
            this.selected = new SimpleBooleanProperty(false);
        }

        StringProperty nameProperty() {
            return name;
        }

        BooleanProperty selectedProperty() {
            return selected;
        }
    }

    private class MyMenu extends ContextMenu {
        MyMenu() {
            getItems().add(new MenuItem("Test"));
            getItems().add(new MenuItem("Item"));

        }
    }

    private class MyCell extends TreeTableCell<MyModel, String> {
        MyCell() {
            // Here you can set the same menu for each cell. Then the column is having the same cell for every row
            setContextMenu(new MyMenu());
        }

        // Overridden just to show the text of the cell.
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
            } else {
                contextMenuProperty().bind(Bindings
                    // here you can define your own condition
                    .when(getTreeTableRow().getTreeItem().getValue().selectedProperty())
                    .then(new MyMenu())
                    .otherwise((MyMenu) null));
                setText(item);
            }
        }
    }

}

Of course you can set a different menu for the second column same as it is set for the first one.


问:
using pexpect pxssh twice on two different ports
I am trying to connect via SSH using pxssh to a remote device, however one of these devices is SSH port 2222 and one is 22. I know I can change the hardcoded value in pxssh.py to either 22 or 2222 but I don't know how I can do both at the same time.

I looked at the pxssh login() function and tried putting 'port' after password, so when calling pxssh I could specify the port required e.g

pxssh.py file

```<code>def login (self, server, username, password='', port, terminal_type='ansi',original
            _prompt=r"[#$]", login_timeout=10,
            auto_prompt_reset=True, ssh_key=None, quiet=True,
            sync_multiplier=1, check_local_ip=True):
</code>```

calling pxssh login from my file

```<code>s.login(server, username, password, port)
</code>```

however that error'ed with

```<code>SyntaxError: non-default argument follows default argument
</code>```

I then thought I could duplicate pxssh and have pxssh22.py and pxssh2222.py

```<code>if something:
     from pexpect import pxssh22
else:
     from pexpect import pxssh2222
</code>```

each specifying a different hard coded port number however that kept erroring with when called:

```<code>try:
    s = pxssh2222.pxssh()
    s.login(server, username, password)

except pxssh2222.ExceptionPxssh as e:
NameError: global name 'pxssh2222' is not defined
</code>```

How could I use pxssh to access both port 2222 and 22. Thanks

答:
You can provide port as an optional parameter when calling the login method.

```<code>  s = pxssh.pxssh()
  s.login(server, username, password, port=2222)
</code>```

Body:
I am trying to connect via SSH using pxssh to a remote device, however one of these devices is SSH port 2222 and one is 22. I know I can change the hardcoded value in pxssh.py to either 22 or 2222 but I don't know how I can do both at the same time.

I looked at the pxssh login() function and tried putting 'port' after password, so when calling pxssh I could specify the port required e.g

pxssh.py file

def login (self, server, username, password='', port, terminal_type='ansi',original
            _prompt=r"[#$]", login_timeout=10,
            auto_prompt_reset=True, ssh_key=None, quiet=True,
            sync_multiplier=1, check_local_ip=True):

calling pxssh login from my file

s.login(server, username, password, port)

however that error'ed with

SyntaxError: non-default argument follows default argument

I then thought I could duplicate pxssh and have pxssh22.py and pxssh2222.py

if something:
     from pexpect import pxssh22
else:
     from pexpect import pxssh2222

each specifying a different hard coded port number however that kept erroring with when called:

try:
    s = pxssh2222.pxssh()
    s.login(server, username, password)

except pxssh2222.ExceptionPxssh as e:
NameError: global name 'pxssh2222' is not defined

How could I use pxssh to access both port 2222 and 22. Thanks

Body:
You can provide port as an optional parameter when calling the login method.

  s = pxssh.pxssh()
  s.login(server, username, password, port=2222)


问:
How execute function at 20 November 2017 15:53 [node-cron]
I want execute a function at 20 November 2017 at 15:53 with node-cron so I do this:

```<code>    var task = cron.schedule('00 53 15 20 11 *', function() {
console.log("HELLO");

            }, false);

            task.start();
</code>```

The task is not execute because I think that I'm wronging put the date so I don't read the "HELLO" print. Anyone can help?

答: I managed to run your code by using cron.schedule('1 53 15 20 11 *', cb)

Body:
I want execute a function at 20 November 2017 at 15:53 with node-cron so I do this:

    var task = cron.schedule('00 53 15 20 11 *', function() {
console.log("HELLO");

            }, false);

            task.start();

The task is not execute because I think that I'm wronging put the date so I don't read the "HELLO" print. Anyone can help?


问:
Count concurrent calls on a method
Let's say I have a very simple web-service whose only task is to count how many times it's endpoint was called. The endpoint is /hello.

```<code>@Controller
public class HelloController {

    private int calls = 0;

    @RequestMapping("/hello")
    public String hello() {
        incrementCalls();
        return "hello";
    }

    private void incrementCalls() {
        calls++;
    }
}
</code>```

Now this works all fine as long as two users don't call /hello at the same time, simultaneously. But when a parallel call to /hello does happen, the calls variable would only get incremented once (if I am not mistaken). So obviously some kind of synchronization would need to take place here.

The question is what would be the best way to make this method thread-safe?

答:
The reason that calls++ could cause a behavior other than you expect is if it is not atomic. Atomic operations happen in such a way that the entire operation can not be intercepted by another thread. Atomicity is implemented either by locking the operation, or by harnessing hardware that already performs it an atomic manner.

Incrementing is most likely not an atomic operation, as you have supposed, since it is a shortcut for calls = calls + 1;. It could indeed happen that two threads retrieve the same value for calls before either has a chance to increment. Both would then store the same value back, instead of one getting the already-incremented value.

There are a few simple ways of turning the get-and-increment into an atomic operation. The simplest one for you, not requiring any imports, is to make your method synchronized:

```<code>private void incrementCalls() {
    calls++;
}
</code>```

This will implicitly lock on the HelloController object it belongs to whenever a thread enters the method. Other threads will have to wait until the lock is released to enter the method, making the whole method into an atomic operation.

Another method would be to explicitly synchronize the portion of the code that you want. This is often a better choice for large methods that do not need to have a lot of atomic operations, since synchronization is fairly time- and space-expensive:

```<code>private void incrementCalls() {
    sychronized(this) {
        calls++;
    }
}
</code>```

Making the whole method synchronized is just a shortcut for wrapping its entire contents in synchronized(this).

java.util.concurrent.atomic.AtomicInteger handles the synchronization to make most of the operations you would want to do on an integer into atomic operations for you. In this case you could call getAndAdd(1), or getAndIncrement(). This would probably be the cleanest solution in terms of keeping the code legible as it reduces the number of braces and uses carefully designed library functions.

Title: Count concurrent calls on a method

Body:
Let's say I have a very simple web-service whose only task is to count how many times it's endpoint was called. The endpoint is /hello.

@Controller
public class HelloController {

    private int calls = 0;

    @RequestMapping("/hello")
    public String hello() {
        incrementCalls();
        return "hello";
    }

    private void incrementCalls() {
        calls++;
    }
}

Now this works all fine as long as two users don't call /hello at the same time, simultaneously. But when a parallel call to /hello does happen, the calls variable would only get incremented once (if I am not mistaken). So obviously some kind of synchronization would need to take place here.

The question is what would be the best way to make this method thread-safe?

Body:
The reason that calls++ could cause a behavior other than you expect is if it is not atomic. Atomic operations happen in such a way that the entire operation can not be intercepted by another thread. Atomicity is implemented either by locking the operation, or by harnessing hardware that already performs it an atomic manner.

Incrementing is most likely not an atomic operation, as you have supposed, since it is a shortcut for calls = calls + 1;. It could indeed happen that two threads retrieve the same value for calls before either has a chance to increment. Both would then store the same value back, instead of one getting the already-incremented value.

There are a few simple ways of turning the get-and-increment into an atomic operation. The simplest one for you, not requiring any imports, is to make your method synchronized:

private void incrementCalls() {
    calls++;
}

This will implicitly lock on the HelloController object it belongs to whenever a thread enters the method. Other threads will have to wait until the lock is released to enter the method, making the whole method into an atomic operation.

Another method would be to explicitly synchronize the portion of the code that you want. This is often a better choice for large methods that do not need to have a lot of atomic operations, since synchronization is fairly time- and space-expensive:

private void incrementCalls() {
    sychronized(this) {
        calls++;
    }
}

Making the whole method synchronized is just a shortcut for wrapping its entire contents in synchronized(this).

java.util.concurrent.atomic.AtomicInteger handles the synchronization to make most of the operations you would want to do on an integer into atomic operations for you. In this case you could call getAndAdd(1), or getAndIncrement(). This would probably be the cleanest solution in terms of keeping the code legible as it reduces the number of braces and uses carefully designed library functions.


问:
WCF webmethod xml string problem
I have a WCF web service that returns a string to a Java based client.

```<code><OperationContract()>
Function SomeSvc(ByVal fileString As String) As String
</code>```

fileString is a bunch of xml. When the client gets the response my xmlstring is encoded as text.

```<code> <s:Body u:Id="_0">
    <SomeSvcResponse xmlns="http://tempuri.org/">
      <SomeSvcResult>> </ns2:FailureMessage> </ns:BOD> </ns:ConfirmDataArea> </ns:Confirm>
      </SomeSvcResult>
    </SomeSvcResponse>
  </s:Body>
</s:Envelope>
</code>```

Why is my service returning encoded text instead of xml?

答: The service encodes your data because you defined return value as String. If you want to return XML use XElement instead.

Title: WCF webmethod xml string problem

Body:
I have a WCF web service that returns a string to a Java based client.

<OperationContract()>
Function SomeSvc(ByVal fileString As String) As String

fileString is a bunch of xml. When the client gets the response my xmlstring is encoded as text.

 <s:Body u:Id="_0">
    <SomeSvcResponse xmlns="http://tempuri.org/">
      <SomeSvcResult>> </ns2:FailureMessage> </ns:BOD> </ns:ConfirmDataArea> </ns:Confirm>
      </SomeSvcResult>
    </SomeSvcResponse>
  </s:Body>
</s:Envelope>

Why is my service returning encoded text instead of xml?


问:
Filling nulls with a list in Pandas using fillna
Given a pd.Series, I would like to replace null values with a list. That is, given:

```<code>import numpy as np
import pandas as pd
ser = pd.Series([0,1,np.nan])
</code>```

I want a function that would return

```<code>0        0
1        1
2    [nan]
</code>```

But if I try using the natural function for this, namely fillna:

```<code>result = ser.fillna([np.nan])
</code>```

but I get the error

TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

Any suggestions of a simple way to acheive this?

答:
You can change to object

```<code>ser=ser.astype('object')
</code>```

Then assign the list np.nan

```<code>ser.loc[ser.isnull()]=[[np.nan]]
</code>```

Body:
Given a pd.Series, I would like to replace null values with a list. That is, given:

import numpy as np
import pandas as pd
ser = pd.Series([0,1,np.nan])

I want a function that would return

0        0
1        1
2    [nan]

But if I try using the natural function for this, namely fillna:

result = ser.fillna([np.nan])

but I get the error

TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

Any suggestions of a simple way to acheive this?

Body:
You can change to object

ser=ser.astype('object')

Then assign the list np.nan

ser.loc[ser.isnull()]=[[np.nan]]


问:
Need to submit a form without the onsubmit and include the action
Here is a form

```<code><cfoutput>
<form name    = "xrefform"
    id        = "xrefform"
    action    = ""
    method    = "post"
    onsubmit  = "return submitx('#coltop#', '#col#')">
</cfoutput>
</code>```

There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table

For the first case I have

```<code><input type     = "Submit"
        name    = "SubmitXref"
        class   = "submitbut"
        value   = "Submit"
        onclick = "aasubmit('xref2.cfm')">
</code>```

with corresponding javascript:

```<code> function aasubmit(target) {
   document.xrefform.action = target;
 }//end function aasubmit
</code>```

This works fine.

For the delete case I have

```<code><input   type    = "Submit"
         id      = "delbut"
         class   = "onoffbut"
         value   = "delete"
         onclick = "aasubmit('repdel.cfm')">
</code>```

This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.

I find references that say using the document.form.submit() method will avoid running the onsubmit function.  But I can't figure out how to indicate the action.

Can someone show me how to do this?

After fussing around some more I found the answer:

For the delete button --which needs to evade the onsubmit script --here is the HTML:

```<code>   <input type    = "button"
        id      = "delbut"
        value   = "Delete this item"
        onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">
</code>```

And here is the javascript.

```<code>function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}
</code>```

This works perfectly.  The ordinary submit honors the onsubmit script, the delete button skips it.

答:
Let's outline your requirements:

One form

Two submit buttons

No JavaScript submit.

If you give each of the submit buttons a name, then you can have a single action page and check which button was clicked.

name="doUpdate" or name="doDelete"

The only name key that will exist in the form scope is whichever submit button was clicked. Use structKeyExists() to check and process accordingly.

Of course, you probably want to use onsubmit="return validateForm()" to call a validation function. If you click on "delete", you might want the user to confirm that was what they wanted to do before processing it. The function validateForm() just needs to return true or false, so you'll still avoid the JavaScript submit().

Body:
Here is a form

<cfoutput>
<form name    = "xrefform"
    id        = "xrefform"
    action    = ""
    method    = "post"
    onsubmit  = "return submitx('#coltop#', '#col#')">
</cfoutput>

There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table

For the first case I have

<input type     = "Submit"
        name    = "SubmitXref"
        class   = "submitbut"
        value   = "Submit"
        onclick = "aasubmit('xref2.cfm')">

with corresponding javascript:

 function aasubmit(target) {
   document.xrefform.action = target;
 }//end function aasubmit

This works fine.

For the delete case I have

<input   type    = "Submit"
         id      = "delbut"
         class   = "onoffbut"
         value   = "delete"
         onclick = "aasubmit('repdel.cfm')">

This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.

I find references that say using the document.form.submit() method will avoid running the onsubmit function.  But I can't figure out how to indicate the action.

Can someone show me how to do this?

After fussing around some more I found the answer:

For the delete button --which needs to evade the onsubmit script --here is the HTML:

   <input type    = "button"
        id      = "delbut"
        value   = "Delete this item"
        onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">

And here is the javascript.

function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}

This works perfectly.  The ordinary submit honors the onsubmit script, the delete button skips it.