问:
Zend select data with where concat
Can anyone help me to fix this?

I want to get data when I set year and month.
And got problem when I try to select data with where concat year and month.
That sql query running when I try on my DB but in Zend I got error:

```<code>$db = Zend_Registry::get('db');

$select = $db->select()
            ->from(array('air'=>$this->_name),
                array('sumtotal' => new Zend_Db_Expr('SUM(air.price) + SUM(inst.cicilan)')));
$select->joinLeft(array('s' => 'store'), 's.id = air.store_id');
$select->joinLeft(array('ar' => 'area'), 'ar.name = s.regional');
$select->joinLeft(array('inst' => 'installment'), 'inst.sn = air.sn');
$select->where('(air.status = ?', A);
$select->orwhere('air.status = ?', B);
$select->orwhere('air.status = ?', C);
$select->orwhere('air.status = ?', D);
$select->orwhere('air.status = ?', E);
$select->orwhere('air.status = ?', F);
$select->orwhere('air.status = ?', G);
$select->orwhere('air.status = ?', H);
$select->orwhere('air.status = ?', I);
$select->orwhere('air.status = ?', J);
$select->orwhere('air.status = ?)', K);
$select->where('ar.id = ?', $area);
$select->where('CONCAT(YEAR(air.date)-MONTH(air.date)) = ?', $year . '-' . $month );
$data = $db->fetchOne($select);
return $data;
</code>```

答:
You probably need to wrap the concat into a new Zend_Db_Expr(, unless the code would be looking for a db column named CONCAT(YEAR(air.date)-MONTH(air.date)).

Also, if you are trying to put a dash between the year and month, that would be CONCAT( YEAR(air.date), '-', MONTH(air.date) ) (see the comas between arguments?).

Lastly, that's ZF1, so you can do die($select->assemble()); to help with debug.

Title: Zend select data with where concat

Body:
Can anyone help me to fix this?

I want to get data when I set year and month.
And got problem when I try to select data with where concat year and month.
That sql query running when I try on my DB but in Zend I got error:

$db = Zend_Registry::get('db');

$select = $db->select()
            ->from(array('air'=>$this->_name),
                array('sumtotal' => new Zend_Db_Expr('SUM(air.price) + SUM(inst.cicilan)')));
$select->joinLeft(array('s' => 'store'), 's.id = air.store_id');
$select->joinLeft(array('ar' => 'area'), 'ar.name = s.regional');
$select->joinLeft(array('inst' => 'installment'), 'inst.sn = air.sn');
$select->where('(air.status = ?', A);
$select->orwhere('air.status = ?', B);
$select->orwhere('air.status = ?', C);
$select->orwhere('air.status = ?', D);
$select->orwhere('air.status = ?', E);
$select->orwhere('air.status = ?', F);
$select->orwhere('air.status = ?', G);
$select->orwhere('air.status = ?', H);
$select->orwhere('air.status = ?', I);
$select->orwhere('air.status = ?', J);
$select->orwhere('air.status = ?)', K);
$select->where('ar.id = ?', $area);
$select->where('CONCAT(YEAR(air.date)-MONTH(air.date)) = ?', $year . '-' . $month );
$data = $db->fetchOne($select);
return $data;


来源: stackexchange

问:
ASP.NET Identity - can't register UserTokenProvider
I have an issue with generating the reset password token in the ASP.NET Core 1.0 project:

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddIdentity<UserDB, GroupDB>()
            .AddDefaultTokenProviders()
}
</code>```

then in my controller with DI:

```<code>...
UserManager<UserDB> userManager
...

string token = await userManager.GeneratePasswordResetTokenAsync(user);
</code>```

and I get

No IUserTokenProvider named 'Default' is registered.

How to fix it ?

I can see there's no Providers inside of my UserStore constructor:

答:
I noticed that the UserStore class didn't have the IUserTokenProvider interface implementation. Also, in the ApplicationUserManager class constructor, I check if the TokenProviderDescriptor is registered

```<code>public class ApplicationUserManager : UserManager<UserDB>
{
    public ApplicationUserManager(UserStore store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<UserDB> passwordHasher, IEnumerable<IUserValidator<UserDB>> userValidators, IEnumerable<IPasswordValidator<UserDB>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<UserDB>> logger, IHttpContextAccessor contextAccessor)
        : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor)
    {
        if (!optionsAccessor.Value.Tokens.ProviderMap.ContainsKey("DefaultTokenProvider"))
            optionsAccessor.Value.Tokens.ProviderMap.Add("DefaultTokenProvider", new TokenProviderDescriptor(typeof(UserStore)));
    }
}
</code>```

That's solved the issue. Thanks for the help !

ContentLicense: CC BY-SA 3.0

Body:
I have an issue with generating the reset password token in the ASP.NET Core 1.0 project:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddIdentity<UserDB, GroupDB>()
            .AddDefaultTokenProviders()
}

then in my controller with DI:

...
UserManager<UserDB> userManager
...

string token = await userManager.GeneratePasswordResetTokenAsync(user);

and I get

No IUserTokenProvider named 'Default' is registered.

How to fix it ?

I can see there's no Providers inside of my UserStore constructor:

Body:
I noticed that the UserStore class didn't have the IUserTokenProvider interface implementation. Also, in the ApplicationUserManager class constructor, I check if the TokenProviderDescriptor is registered

public class ApplicationUserManager : UserManager<UserDB>
{
    public ApplicationUserManager(UserStore store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<UserDB> passwordHasher, IEnumerable<IUserValidator<UserDB>> userValidators, IEnumerable<IPasswordValidator<UserDB>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<UserDB>> logger, IHttpContextAccessor contextAccessor)
        : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor)
    {
        if (!optionsAccessor.Value.Tokens.ProviderMap.ContainsKey("DefaultTokenProvider"))
            optionsAccessor.Value.Tokens.ProviderMap.Add("DefaultTokenProvider", new TokenProviderDescriptor(typeof(UserStore)));
    }
}

That's solved the issue. Thanks for the help !


问:
Looping over array elements, given an array of arrays' variable names in Bash Script
I have an array containing names of categories

```<code>categories=( categoryA categoryB categoryC )
</code>```

Each category contains multiple products, which is stored in different arrays.

```<code>categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )
</code>```

I want to loop over all products, so I wrote this code:

```<code>categories=( categoryA categoryB categoryC )

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

for category_name in "${categories[@]}"
do
    echo $category_name

    category=${!category_name}
    for product in "${category[@]}"
    do
        echo -e '\t' $product
    done

    echo -e '\n'

done
</code>```

I expected the output to be:

```<code>CategoryA
    ProductA1
    ProductA2
    ProductA3

CategoryB
    ProductB1
    ProductB2
    ProductB3

CategoryC
    ProductC1
    ProductC2
    ProductC3
</code>```

but unfortunately, the output is

```<code>CategoryA
    ProductA1

CategoryB
    ProductB1

CategoryC
    ProductC1
</code>```

How to fix this ?

答:
If Inian's answer doesn't work for you because your are using a version of bash older than 4.3 (where the support for nameref variables was introduced), you can go for the following solution:

```<code>categories=( categoryA categoryB categoryC )

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

for category_name in "${categories[@]}"
do
    echo $category_name

    array_declaration="$(declare -p $category_name)"
    # "$array_declaration" expands to the command that can be (safely)
    # evaluated to recreate the $category_name variable

    # change the variable name in the array declaration and eval it
    eval "${array_declaration/#declare -a "$category_name"=/declare -a category=}"

    for product in "${category[@]}"
    do
        echo -e '\t' $product
    done

    echo -e '\n'

done
</code>```

Note that reliance on eval in the above code should be safe, since the output of declare -p is properly quoted.

Body:
I have an array containing names of categories

categories=( categoryA categoryB categoryC )

Each category contains multiple products, which is stored in different arrays.

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

I want to loop over all products, so I wrote this code:

categories=( categoryA categoryB categoryC )

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

for category_name in "${categories[@]}"
do
    echo $category_name

    category=${!category_name}
    for product in "${category[@]}"
    do
        echo -e '\t' $product
    done

    echo -e '\n'

done

I expected the output to be:

CategoryA
    ProductA1
    ProductA2
    ProductA3

CategoryB
    ProductB1
    ProductB2
    ProductB3

CategoryC
    ProductC1
    ProductC2
    ProductC3

but unfortunately, the output is

CategoryA
    ProductA1

CategoryB
    ProductB1

CategoryC
    ProductC1

How to fix this ?

Body:
If Inian's answer doesn't work for you because your are using a version of bash older than 4.3 (where the support for nameref variables was introduced), you can go for the following solution:

categories=( categoryA categoryB categoryC )

categoryA=( productA1 productA2 productA3 )
categoryB=( productB1 productB2 productB3 )
categoryC=( productC1 productC2 productC3 )

for category_name in "${categories[@]}"
do
    echo $category_name

    array_declaration="$(declare -p $category_name)"
    # "$array_declaration" expands to the command that can be (safely)
    # evaluated to recreate the $category_name variable

    # change the variable name in the array declaration and eval it
    eval "${array_declaration/#declare -a "$category_name"=/declare -a category=}"

    for product in "${category[@]}"
    do
        echo -e '\t' $product
    done

    echo -e '\n'

done

Note that reliance on eval in the above code should be safe, since the output of declare -p is properly quoted.


问:
Calculate compass bearing / heading to location in Android
I want to display an arrow at my location on a google map view that displays my direction relative to a destination location (instead of north).

a) I have calculated north using the sensor values from the magnetometer and accelerometer. I know this is correct because it lines up with the compass used on the Google Map view.

b) I have calculated the initial bearing from my location to the destination location by using myLocation.bearingTo(destLocation);

I'm missing the last step; from these two values (a & b) what formula do I use to get the  direction in which the phone is pointing relative to the destination location?

Appreciate any help for an addled mind!

答:
I'm no expert in map-reading / navigation and so on but surely 'directions' are absolute and not relative or in reality, they are relative to N or S which themselves are fixed/absolute.

Example: Suppose an imaginary line drawn between you and your destination corresponds with 'absolute' SE (a bearing of 135 degrees relative to magnetic N). Now suppose your phone is pointing NW - if you draw an imaginary line from an imaginary object on the horizon to your destination, it will pass through your location and have an angle of 180 degrees. Now 180 degrees in the sense of a compass actually refers to S but the destination is not 'due S' of the imaginary object your phone is pointing at and, moreover, if you travelled to that imaginary point, your destination would still be SE of where you moved to.

In reality, the 180 degree line actually tells you the destination is 'behind you' relative to the way the phone (and presumably you) are pointing.

Having said that, however, if calculating the angle of a line from the imaginary point to your destination (passing through your location) in order to draw a pointer towards your destination is what you want...simply subtract the (absolute) bearing of the destination from the absolute bearing of the imaginary object and ignore a negation (if present). e.g., NW - SE is 315 - 135 = 180 so draw the pointer to point at the bottom of the screen indicating 'behind you'.

EDIT: I got the Maths slightly wrong...subtract the smaller of the bearings from the larger then subtract the result from 360 to get the angle in which to draw the pointer on the screen.

ContentLicense: CC BY-SA 2.5


问:
A method to store date and time in Android using Firebase?
I'm new to Android Studio and new to the Firebase database as well. I have created an app but I don't know how to store date and time. Can you help me guys?

Here below is my code:

```<code>public class TimeBookActivity extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {

    private FirebaseAuth auth;
    private DatabaseReference databaseReference;
     Button bnt_picDate_picDate;
     TextView textView3;
    int time, day, month, year, hour, minute, a;
    int timeFinal, dayFinal, monthFinal,yearFinal, hourFinal, minuteFinal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_book);

        auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser()== null){
            startActivity(new Intent(TimeBookActivity.this, LoginActivity.class));
        }

        databaseReference = FirebaseDatabase.getInstance().getReference();
        textView3 = (TextView) findViewById(R.id.textView3);
        bnt_picDate_picDate = (Button) findViewById(R.id.bnt_picDate_picDate);

        FirebaseUser user = auth.getCurrentUser();

        bnt_picDate_picDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == bnt_picDate_picDate){

                    Calendar c = Calendar.getInstance();
                    year = c.get(Calendar.YEAR);
                    month = c.get(Calendar.MONTH);
                    day = c.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog datePickerDialog = new DatePickerDialog(TimeBookActivity.this, TimeBookActivity.this, year, month, day);
                    datePickerDialog.show();

                }

            }
        });

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDateSet(DatePicker view, int i, int i1, int i2) {
        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        yearFinal = i;
        monthFinal = i1 + 1;
        dayFinal = i2;
        String monthS = months[i1];

        Calendar c = Calendar.getInstance();
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);

        textView3.setText("Year: "+yearFinal+ "\n" +
                "Month: "+monthS+ "\n" +
                "Day: "+dayFinal+ "\n" +
                "Hour: "+hourFinal+ "\n" +
                "Minute: "+minuteFinal+ "\n" +
                "\n" +"Congratulation You are Booked!");

        TimePickerDialog timePickerDialog = new TimePickerDialog(TimeBookActivity.this,TimeBookActivity.this,hour,minute, DateFormat.is24HourFormat(TimeBookActivity.this));

        DatePickerDialog datePickerDialog = new DatePickerDialog(TimeBookActivity.this, TimeBookActivity.this, year, month, day);

    }

    @Override
    public void onTimeSet(TimePicker view, int i, int i1) {
        hourFinal = i;
        minuteFinal = i1;

    }
}
</code>```

答:
```<code>Calendar c = Calendar.getInstance();
            c.set(Syear, Smonth, Sday, Shours, Sminute);
            long startDate = c.getTimeInMillis();
</code>```

where Syear, Smonth, Sday, Shours, Sminute you can get it from your OnDateSet and
OnTimeSet
now you can put Datetime to your FireBase  as long

Body:
I'm new to Android Studio and new to the Firebase database as well. I have created an app but I don't know how to store date and time. Can you help me guys?

Here below is my code:

public class TimeBookActivity extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {

    private FirebaseAuth auth;
    private DatabaseReference databaseReference;
     Button bnt_picDate_picDate;
     TextView textView3;
    int time, day, month, year, hour, minute, a;
    int timeFinal, dayFinal, monthFinal,yearFinal, hourFinal, minuteFinal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_book);

        auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser()== null){
            startActivity(new Intent(TimeBookActivity.this, LoginActivity.class));
        }

        databaseReference = FirebaseDatabase.getInstance().getReference();
        textView3 = (TextView) findViewById(R.id.textView3);
        bnt_picDate_picDate = (Button) findViewById(R.id.bnt_picDate_picDate);

        FirebaseUser user = auth.getCurrentUser();

        bnt_picDate_picDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == bnt_picDate_picDate){

                    Calendar c = Calendar.getInstance();
                    year = c.get(Calendar.YEAR);
                    month = c.get(Calendar.MONTH);
                    day = c.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog datePickerDialog = new DatePickerDialog(TimeBookActivity.this, TimeBookActivity.this, year, month, day);
                    datePickerDialog.show();

                }

            }
        });

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDateSet(DatePicker view, int i, int i1, int i2) {
        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        yearFinal = i;
        monthFinal = i1 + 1;
        dayFinal = i2;
        String monthS = months[i1];

        Calendar c = Calendar.getInstance();
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);

        textView3.setText("Year: "+yearFinal+ "\n" +
                "Month: "+monthS+ "\n" +
                "Day: "+dayFinal+ "\n" +
                "Hour: "+hourFinal+ "\n" +
                "Minute: "+minuteFinal+ "\n" +
                "\n" +"Congratulation You are Booked!");

        TimePickerDialog timePickerDialog = new TimePickerDialog(TimeBookActivity.this,TimeBookActivity.this,hour,minute, DateFormat.is24HourFormat(TimeBookActivity.this));

        DatePickerDialog datePickerDialog = new DatePickerDialog(TimeBookActivity.this, TimeBookActivity.this, year, month, day);

    }

    @Override
    public void onTimeSet(TimePicker view, int i, int i1) {
        hourFinal = i;
        minuteFinal = i1;

    }
}

Body:
Calendar c = Calendar.getInstance();
            c.set(Syear, Smonth, Sday, Shours, Sminute);
            long startDate = c.getTimeInMillis();

where Syear, Smonth, Sday, Shours, Sminute you can get it from your OnDateSet and
OnTimeSet
now you can put Datetime to your FireBase  as long


问:
Date for the next run of the job in Autosys
I have a job which runs on business days (MON-FRI). I need the date for the next run of the job. so Suppose if Job is running on Monday I need date of Tuesday or if Job is running on Friday I need date of Monday.   </p>

答:
You may use Job Forecast report by using -t and -F combination.

job_depends -t -w -J <JOB_NAME> -F "03/29/2017" -l0

Note that this will work only for Jobs which have Date Condition. You may use -l0 if only looking for top level box.

```<code>                                 Job Forecast Report
                        From: 03/29/2017 00:00:00  To: Infinity

Job Name                                                         Next Start            Atomic Start Conditions
______________________________                                   _______________       _______________________

JOB_NAME                                                      03/29/2017 20:40:00   -------
</code>```

Body:
You may use Job Forecast report by using -t and -F combination.

job_depends -t -w -J <JOB_NAME> -F "03/29/2017" -l0

Note that this will work only for Jobs which have Date Condition. You may use -l0 if only looking for top level box.

                                 Job Forecast Report
                        From: 03/29/2017 00:00:00  To: Infinity

Job Name                                                         Next Start            Atomic Start Conditions
______________________________                                   _______________       _______________________

JOB_NAME                                                      03/29/2017 20:40:00   -------


问:
How change css of disabled input checkbox tag?..because it's too light and hard to see
Guys,
I have some input checkbox tags:

They look pretty light and hard to see or print. I tried restyle the checkbox, it seems that the disabled checkbox's style can't be changed?
Do you guys have any idea?
Thanks a lot! :)</p>

答:
If you're using default checkboxes with default styling, you shouldn't worry too much. They've designed them just fine to be seen as they should be.

Could as well be your monitor contrast/brightness setting.

but if you're using some custom checkbox design, you will most probably have to change images.


问:
Regular expressions d
I have some code:

```<code>String url1 = "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-s...";
String url2 = "shop.lenovo.com/(.*)/en_US/cart";

Pattern p = Pattern.compile(url2);
Matcher m = p.matcher(url1);
</code>```

But m.matches() return for me false. Why?

答:
Instead of your code please try this</p>

```<code>    String url1 = "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-s...";

    String subS1 = "shop.lenovo.com/";
    Pattern p1 = Pattern.compile(subS1);
    Matcher match1 = p1.matcher(url1);

    String subS2 = "en_US/cart";
    Pattern p2 = Pattern.compile(subS2);
    Matcher match2 = p2.matcher(url1);

    if (match1.find() && match2.find())
    {
        // Whatever you like
    }
</code>```

Title: Regular expressions d

Body:
I have some code:

String url1 = "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-s...";
String url2 = "shop.lenovo.com/(.*)/en_US/cart";

Pattern p = Pattern.compile(url2);
Matcher m = p.matcher(url1);

But m.matches() return for me false. Why?

Body:
Instead of your code please try this

    String url1 = "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-s...";

    String subS1 = "shop.lenovo.com/";
    Pattern p1 = Pattern.compile(subS1);
    Matcher match1 = p1.matcher(url1);

    String subS2 = "en_US/cart";
    Pattern p2 = Pattern.compile(subS2);
    Matcher match2 = p2.matcher(url1);

    if (match1.find() && match2.find())
    {
        // Whatever you like
    }


问:
Angular2 Too much loading time for bundle.js production
I am using angular2 for my project.

I have used this command to generate build.

```<code>ng build --prod
</code>```

Bundle.js size is 1.4MB.
In my application I am using angular2-google-maps, bootstrap, dropzone.

Is there any solution to fast my production site?

答:
Please checkout this link,
Not worked on it but seems they are able to reduce size of bundle from 1.4Mb to 47K!.</p>

Body:
I am using angular2 for my project.

I have used this command to generate build.

ng build --prod

Bundle.js size is 1.4MB.
In my application I am using angular2-google-maps, bootstrap, dropzone.

Is there any solution to fast my production site?


问:
how to place legend at multiple positions in r
I have made a barplot using R with legends. But legends are almost covering half width. There are total 10 legend in plot. I think I should place 5 legends at topright and 5 at top left. How can I place legends at multiple positions ?

答:
With base plot, you can have two different legend calls for "topright" and "topleft".

```<code>x <- 1:10
my_colors <- 1:10
barplot(x,ylim=c(1,15),col=my_colors)
legend("topleft",legend=x[1:5],col=my_colors[1:5],lty=1)
legend("topright",legend=x[6:10],col=my_colors[6:10],lty=1)
</code>```

Body:
With base plot, you can have two different legend calls for "topright" and "topleft".

x <- 1:10
my_colors <- 1:10
barplot(x,ylim=c(1,15),col=my_colors)
legend("topleft",legend=x[1:5],col=my_colors[1:5],lty=1)
legend("topright",legend=x[6:10],col=my_colors[6:10],lty=1)


问:
Pull variable name through to constructor on object instantiation
Here's an example constructor

```<code>function AnObject(a, b){
    this.a = a;
    this.b = b;
}
</code>```

and an instantiation of it

```<code>var example = new AnObject('test', 'test');
</code>```

Lets say that the constructor had a property .name

is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?

In the case above, the name would be example

-EDIT-

The reason I am trying to achieve this is to be as "D.R.Y" as possible.

I would like to NOT have to:

```<code>var example = new ObjectWithName('example');
</code>```

答:
No. I'm afraid that's not possible!

You see, the statement var example = new AnObject('test', 'test'); is evaluated from right to left. So, first new AnObject('test', 'test') is evaluated. Then, the value it returns is assigned to var example.

Because of this right-to-left evaluation, there is no way your AnObject constructor can know that its return value is going to be assigned to variable example when it's being evaluated.

Body:
Here's an example constructor

function AnObject(a, b){
    this.a = a;
    this.b = b;
}

and an instantiation of it

var example = new AnObject('test', 'test');

Lets say that the constructor had a property .name

is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?

In the case above, the name would be example

-EDIT-

The reason I am trying to achieve this is to be as "D.R.Y" as possible.

I would like to NOT have to:

var example = new ObjectWithName('example');


问:
populate a combobox with an xml file
This is the XML file

```<code><Users>
<User userID="4" username="lol" password="lol" usertype="Guest" />
</Users>
</code>```

the code i tried

```<code>private void ExistingUser_Load(object sender, EventArgs e)
    {
        var xml = XElement.Load("XMLFile1.xml");
        comboBox1.DisplayMember = "userID";

    }
</code>```

答:
Try the below code Works perfectly. You need to mention the path for the xml document properly in the doc.Load("path").

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        Dictionary<int, string> dictionary = new Dictionary<int, string>();
        XmlDocument doc = new XmlDocument();
        doc.Load(@"D:\WindowsFormsApplication1\WindowsFormsApplication1\XMLFile1.xml");
        XmlNodeList elemList = doc.GetElementsByTagName("User");
        for (int i = 0; i < elemList.Count; i++)
        {
            string attrVal = elemList[i].Attributes["userID"].Value;
            dictionary.Add(Convert.ToInt32(attrVal), attrVal);
        }

        comboBox1.DataSource = new BindingSource(dictionary, null);
        comboBox1.DisplayMember = "Key";
        comboBox1.ValueMember = "Value";
    }
</code>```

Title: populate a combobox with an xml file

Body:
This is the XML file

<Users>
<User userID="4" username="lol" password="lol" usertype="Guest" />
</Users>

the code i tried

private void ExistingUser_Load(object sender, EventArgs e)
    {
        var xml = XElement.Load("XMLFile1.xml");
        comboBox1.DisplayMember = "userID";

    }

Body:
Try the below code Works perfectly. You need to mention the path for the xml document properly in the doc.Load("path").

    private void Form1_Load(object sender, EventArgs e)
    {
        Dictionary<int, string> dictionary = new Dictionary<int, string>();
        XmlDocument doc = new XmlDocument();
        doc.Load(@"D:\WindowsFormsApplication1\WindowsFormsApplication1\XMLFile1.xml");
        XmlNodeList elemList = doc.GetElementsByTagName("User");
        for (int i = 0; i < elemList.Count; i++)
        {
            string attrVal = elemList[i].Attributes["userID"].Value;
            dictionary.Add(Convert.ToInt32(attrVal), attrVal);
        }

        comboBox1.DataSource = new BindingSource(dictionary, null);
        comboBox1.DisplayMember = "Key";
        comboBox1.ValueMember = "Value";
    }


问:
Traceback (most recent call last) & TypeError: unsupported operand type(s) for +: 'int' and 'str'
```<code>#!/usr/bin/python

import time
import random
import struct
import select
import socket

def chk(data):
    x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
    x = (x >> 16) + (x & 0xFFFF)
    x = (x >> 16) + (x & 0xFFFF)
    return struct.pack('<H', ~x & 0xFFFF)

def ping(addr, timeout=1, number=1, data=b''):
    conn = socket.socket(socket.AF_INET, socket.SOCK_RAW,  socket.IPPROTO_ICMP)
    payload = struct.pack('!HH', random.randrange(0, 65536), number) + data

    conn.connect((addr, 80))
    conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload)
    start = time.time()

    while select.select([conn], [], [], max(0, start + timeout - time.time()))[0]:
        data = conn.recv(65536)
        if len(data) < 20 or len(data) < struct.unpack_from('!xxH', data)[0]:
            continue
        if data[20:] == b'\0\0' + chk(b'\0\0\0\0' + payload) + payload:
            return time.time() - start

if __name__ == '__main__':
    target = raw_input("Please enter a IP Adress: ")
    print(ping(target))
</code>```

I have tried to script which works for creating packet and send to    icmp packet. I got the error the result of the script is shown below:

```<code># python Pinger.py
Please enter a IP Adress: 89.1.3.2
Traceback (most recent call last):
  File "Pinger.py", line 35, in <module>
    print(ping(target))
  File "Pinger.py", line 22, in ping
    conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload)
  File "Pinger.py", line 11, in chk
    x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

Can you help m to resolve TypeError and Traceback?

答:
checkout this !

```<code>data = b'\0\0\0\0'

list(enumerate(data))
>>> [(0, '\x00'), (1, '\x00'), (2, '\x00'), (3, '\x00')]
</code>```

you missed here

```<code>x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
        ^ << also raise TypeError     ^ this is str
</code>```

I guess, the reason of TypeError, function sum may use + operator.

Body:
#!/usr/bin/python

import time
import random
import struct
import select
import socket

def chk(data):
    x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
    x = (x >> 16) + (x & 0xFFFF)
    x = (x >> 16) + (x & 0xFFFF)
    return struct.pack('<H', ~x & 0xFFFF)

def ping(addr, timeout=1, number=1, data=b''):
    conn = socket.socket(socket.AF_INET, socket.SOCK_RAW,  socket.IPPROTO_ICMP)
    payload = struct.pack('!HH', random.randrange(0, 65536), number) + data

    conn.connect((addr, 80))
    conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload)
    start = time.time()

    while select.select([conn], [], [], max(0, start + timeout - time.time()))[0]:
        data = conn.recv(65536)
        if len(data) < 20 or len(data) < struct.unpack_from('!xxH', data)[0]:
            continue
        if data[20:] == b'\0\0' + chk(b'\0\0\0\0' + payload) + payload:
            return time.time() - start

if __name__ == '__main__':
    target = raw_input("Please enter a IP Adress: ")
    print(ping(target))

I have tried to script which works for creating packet and send to    icmp packet. I got the error the result of the script is shown below:

# python Pinger.py
Please enter a IP Adress: 89.1.3.2
Traceback (most recent call last):
  File "Pinger.py", line 35, in <module>
    print(ping(target))
  File "Pinger.py", line 22, in ping
    conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload)
  File "Pinger.py", line 11, in chk
    x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Can you help m to resolve TypeError and Traceback?

Body:
checkout this !

data = b'\0\0\0\0'

list(enumerate(data))
>>> [(0, '\x00'), (1, '\x00'), (2, '\x00'), (3, '\x00')]

you missed here

x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
        ^ << also raise TypeError     ^ this is str

I guess, the reason of TypeError, function sum may use + operator.


问:
Laravel Ajax cannot update database when click on a link
I have an audio file on public folder like this-

```<code>@foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach
</code>```

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

```<code>$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });
</code>```

My Route:

```<code>Route::post('/update_download_count', 'PagesController@updateDownloadCount');
</code>```

Controller:

```<code>public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}
</code>```

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

答:
```<code>public function updateDownloadCount(Request $request){
     \DB::table('songs')->where('songs_id', $request->input("song_id"))->increment('download');
}
</code>```

Body:
I have an audio file on public folder like this-

@foreach ($songs as $song)
     song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           Download
        </button>

 @endforeach

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });

My Route:

Route::post('/update_download_count', 'PagesController@updateDownloadCount');

Controller:

public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?


答:
Load into a DataSet and use that as your the Combobox's DataSource:

```<code>DataSet dataSet = new DataSet();
dataSet.ReadXml("XMLFile1.xml");
this.comboBox1.DataSource = dataSet.Tables[0];
this.comboBox1.DisplayMember = "userID";
</code>```

Title: populate a combobox with an xml file

Body:
Load into a DataSet and use that as your the Combobox's DataSource:

DataSet dataSet = new DataSet();
dataSet.ReadXml("XMLFile1.xml");
this.comboBox1.DataSource = dataSet.Tables[0];
this.comboBox1.DisplayMember = "userID";


问:
Spark scala error
hey i tried to use spark with scala. When i try this code

```<code>    object d29 {
    def main(args: Array[String]){
    val name : String ="myspark"
    val master : String ="local[1]"
    val conf : SparkConf = new SparkConf().setAppName(name).setMaster(master)
    val  spContext : JavaSparkContext = new JavaSparkContext(conf)
    val file = spContext.textFile("zed/text.csv")
    val mapped = file.map(s=>s.length)
    }
}
</code>```

i got this error for the s : missing parameter type

thank you

答:
```<code>object d29 {
def main(args: Array[String]){
val name : String ="myspark"
val master : String ="local[1]"
val conf : SparkConf = new SparkConf().setAppName(name).setMaster(master)
val  spContext = new SparkContext(conf)
val file = spContext.textFile("zed/text.csv")
val mapped = file.map(s=>s.length)
}
</code>```

}

JavaSparkContext is Java wrapper of SparkContext. Since you are using Scala, no need wrapper.

Title: Spark scala error

Body:
hey i tried to use spark with scala. When i try this code

    object d29 {
    def main(args: Array[String]){
    val name : String ="myspark"
    val master : String ="local[1]"
    val conf : SparkConf = new SparkConf().setAppName(name).setMaster(master)
    val  spContext : JavaSparkContext = new JavaSparkContext(conf)
    val file = spContext.textFile("zed/text.csv")
    val mapped = file.map(s=>s.length)
    }
}

i got this error for the s : missing parameter type

thank you

Body:
object d29 {
def main(args: Array[String]){
val name : String ="myspark"
val master : String ="local[1]"
val conf : SparkConf = new SparkConf().setAppName(name).setMaster(master)
val  spContext = new SparkContext(conf)
val file = spContext.textFile("zed/text.csv")
val mapped = file.map(s=>s.length)
}

}

JavaSparkContext is Java wrapper of SparkContext. Since you are using Scala, no need wrapper.


问:
MatplotLib (TKinter) + OpenCV crashing in Python 3
I am trying to run some Python 3 code which first shows an OpenCV window and when it closes it should plot something using MatplotLib. However upon the plt.show() call the program crashes: python3.6 quit unexpectedly.

```<code>import numpy as np

import matplotlib
matplotlib.use("TkAgg")     # <== Doesn't solve the problem
import matplotlib.pyplot as plt

import cv2
#cv2.ocl.setUseOpenCL(False)  <== Doesn't solve the problem

im = np.zeros((100,100,3))
cv2.imshow('test', im)
cv2.waitKey(0)

plt.plot(np.sin(np.linspace(0,20,200)))
plt.show()                  # <== Crashes on this call
</code>```

In other StackOverflow posts I found setting the MatplotLib backend to TkAgg should fix this or setting setUseOpenCL(false). However both these potential fixes do not work on my MacBook. I've tried several things, like changing the import order, trying to swap the MatplotLib backend. Anyone has an idea on how to fix this problem?

MacOS Sierra 10.12.3

Python 3.6.0

TKinter Version 8.5

OpenCV Version 3.2.0

MatplotLib Version 2.0.0

The stacktrace of how it crashes:

libc++abi.dylib: terminating with uncaught exception of type NSException

2017-03-28 11:30:45.639 python3.6[5208:78361] -[NSApplication _setup:]: unrecognized selector sent to instance 0x7f997ec98190
  2017-03-28 11:30:45.641 python3.6[5208:78361] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSApplication _setup:]: unrecognized selector sent to instance 0x7f997ec98190'
  * First throw call stack:
  (
      0   CoreFoundation                      0x00007fffbeb80e7b exceptionPreprocess + 171
      1   libobjc.A.dylib                     0x00007fffd3760cad objc_exception_throw + 48
      2   CoreFoundation                      0x00007fffbec02cb4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
      3   CoreFoundation                      0x00007fffbeaf2fb5 ___forwarding_ + 1061
      4   CoreFoundation                      0x00007fffbeaf2b08 _CF_forwarding_prep_0 + 120
      5   Tk                                  0x00000001032c45e6 TkpInit + 471
      6   Tk                                  0x000000010323fc8d Tk_Init + 1794
      7   _tkinter.cpython-36m-darwin.so      0x000000010311cde6 Tcl_AppInit + 82
      8   _tkinter.cpython-36m-darwin.so      0x00000001031183a3 _tkinter_create + 1094
      9   Python                              0x0000000100b28ea2 _PyCFunction_FastCallDict + 172
      10  Python                              0x0000000100b927a2 call_function + 584
      11  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      12  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      13  Python                              0x0000000100b938c4 _PyFunction_FastCallDict + 477
      14  Python                              0x0000000100aeea73 _PyObject_FastCallDict + 231
      15  Python                              0x0000000100aeeb93 _PyObject_Call_Prepend + 149
      16  Python                              0x0000000100aee8cb PyObject_Call + 102
      17  Python                              0x0000000100b3cd24 slot_tp_init + 61
      18  Python                              0x0000000100b39ac3 type_call + 184
      19  Python                              0x0000000100aeea34 _PyObject_FastCallDict + 168
      20  Python                              0x0000000100b9263b call_function + 225
      21  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      22  Python                              0x0000000100b93976 _PyFunction_FastCall + 122
      23  Python                              0x0000000100b92775 call_function + 539
      24  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      25  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      26  Python                              0x0000000100b89e02 PyEval_EvalCodeEx + 100
      27  Python                              0x0000000100b101e3 function_call + 363
      28  Python                              0x0000000100aee8cb PyObject_Call + 102
      29  Python                              0x0000000100b8fe16 _PyEval_EvalFrameDefault + 24533
      30  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      31  Python                              0x0000000100b936da fast_function + 241
      32  Python                              0x0000000100b92775 call_function + 539
      33  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      34  Python                              0x0000000100b93976 _PyFunction_FastCall + 122
      35  Python                              0x0000000100b92775 call_function + 539
      36  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      37  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      38  Python                              0x0000000100b936da fast_function + 241
      39  Python                              0x0000000100b92775 call_function + 539
      40  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      41  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      42  Python                              0x0000000100b936da fast_function + 241
      43  Python                              0x0000000100b92775 call_function + 539
      44  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      45  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      46  Python                              0x0000000100b89d98 PyEval_EvalCode + 100
      47  Python                              0x0000000100bb33aa run_mod + 58
      48  Python                              0x0000000100bb36bf PyRun_FileExFlags + 178
      49  Python                              0x0000000100bb2d58 PyRun_SimpleFileExFlags + 676
      50  Python                              0x0000000100bc74d0 Py_Main + 3472
      51  python3.6                           0x0000000100adfe17 python3.6 + 7703
      52  libdyld.dylib                       0x00007fffd4044255 start + 1
      53  ???                                 0x0000000000000002 0x0 + 2
  )

答:
No idea about matplotlib, but I can imagine that there could be a problem with window management. Try this: </p>

```<code>cv2.imshow('test', im)
cv2.waitKey(1)
cv2.destroyWindow('test')
</code>```

<p>At least this is the right way of treating already opened cv2.imshow() windows when they are not used anymore. </p>

Body:
I am trying to run some Python 3 code which first shows an OpenCV window and when it closes it should plot something using MatplotLib. However upon the plt.show() call the program crashes: python3.6 quit unexpectedly.

import numpy as np

import matplotlib
matplotlib.use("TkAgg")     # <== Doesn't solve the problem
import matplotlib.pyplot as plt

import cv2
#cv2.ocl.setUseOpenCL(False)  <== Doesn't solve the problem

im = np.zeros((100,100,3))
cv2.imshow('test', im)
cv2.waitKey(0)

plt.plot(np.sin(np.linspace(0,20,200)))
plt.show()                  # <== Crashes on this call

In other StackOverflow posts I found setting the MatplotLib backend to TkAgg should fix this or setting setUseOpenCL(false). However both these potential fixes do not work on my MacBook. I've tried several things, like changing the import order, trying to swap the MatplotLib backend. Anyone has an idea on how to fix this problem?

MacOS Sierra 10.12.3

Python 3.6.0

TKinter Version 8.5

OpenCV Version 3.2.0

MatplotLib Version 2.0.0

The stacktrace of how it crashes:

libc++abi.dylib: terminating with uncaught exception of type NSException

2017-03-28 11:30:45.639 python3.6[5208:78361] -[NSApplication _setup:]: unrecognized selector sent to instance 0x7f997ec98190
  2017-03-28 11:30:45.641 python3.6[5208:78361] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSApplication _setup:]: unrecognized selector sent to instance 0x7f997ec98190'
  * First throw call stack:
  (
      0   CoreFoundation                      0x00007fffbeb80e7b exceptionPreprocess + 171
      1   libobjc.A.dylib                     0x00007fffd3760cad objc_exception_throw + 48
      2   CoreFoundation                      0x00007fffbec02cb4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
      3   CoreFoundation                      0x00007fffbeaf2fb5 ___forwarding_ + 1061
      4   CoreFoundation                      0x00007fffbeaf2b08 _CF_forwarding_prep_0 + 120
      5   Tk                                  0x00000001032c45e6 TkpInit + 471
      6   Tk                                  0x000000010323fc8d Tk_Init + 1794
      7   _tkinter.cpython-36m-darwin.so      0x000000010311cde6 Tcl_AppInit + 82
      8   _tkinter.cpython-36m-darwin.so      0x00000001031183a3 _tkinter_create + 1094
      9   Python                              0x0000000100b28ea2 _PyCFunction_FastCallDict + 172
      10  Python                              0x0000000100b927a2 call_function + 584
      11  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      12  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      13  Python                              0x0000000100b938c4 _PyFunction_FastCallDict + 477
      14  Python                              0x0000000100aeea73 _PyObject_FastCallDict + 231
      15  Python                              0x0000000100aeeb93 _PyObject_Call_Prepend + 149
      16  Python                              0x0000000100aee8cb PyObject_Call + 102
      17  Python                              0x0000000100b3cd24 slot_tp_init + 61
      18  Python                              0x0000000100b39ac3 type_call + 184
      19  Python                              0x0000000100aeea34 _PyObject_FastCallDict + 168
      20  Python                              0x0000000100b9263b call_function + 225
      21  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      22  Python                              0x0000000100b93976 _PyFunction_FastCall + 122
      23  Python                              0x0000000100b92775 call_function + 539
      24  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      25  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      26  Python                              0x0000000100b89e02 PyEval_EvalCodeEx + 100
      27  Python                              0x0000000100b101e3 function_call + 363
      28  Python                              0x0000000100aee8cb PyObject_Call + 102
      29  Python                              0x0000000100b8fe16 _PyEval_EvalFrameDefault + 24533
      30  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      31  Python                              0x0000000100b936da fast_function + 241
      32  Python                              0x0000000100b92775 call_function + 539
      33  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      34  Python                              0x0000000100b93976 _PyFunction_FastCall + 122
      35  Python                              0x0000000100b92775 call_function + 539
      36  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      37  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      38  Python                              0x0000000100b936da fast_function + 241
      39  Python                              0x0000000100b92775 call_function + 539
      40  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      41  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      42  Python                              0x0000000100b936da fast_function + 241
      43  Python                              0x0000000100b92775 call_function + 539
      44  Python                              0x0000000100b8fbbb _PyEval_EvalFrameDefault + 23930
      45  Python                              0x0000000100b92fbf _PyEval_EvalCodeWithName + 1973
      46  Python                              0x0000000100b89d98 PyEval_EvalCode + 100
      47  Python                              0x0000000100bb33aa run_mod + 58
      48  Python                              0x0000000100bb36bf PyRun_FileExFlags + 178
      49  Python                              0x0000000100bb2d58 PyRun_SimpleFileExFlags + 676
      50  Python                              0x0000000100bc74d0 Py_Main + 3472
      51  python3.6                           0x0000000100adfe17 python3.6 + 7703
      52  libdyld.dylib                       0x00007fffd4044255 start + 1
      53  ???                                 0x0000000000000002 0x0 + 2
  )

Body:
No idea about matplotlib, but I can imagine that there could be a problem with window management. Try this:

cv2.imshow('test', im)
cv2.waitKey(1)
cv2.destroyWindow('test')

At least this is the right way of treating already opened cv2.imshow() windows when they are not used anymore.


问:
Angular 2 Correct syntax
We have an entity called operator which has a relationship with an entity called country .We want to filter an operator list based on country name how can we write this filter from the operator ? What is the correct syntax ?

html :

```<code>[(ngModel)]="opFilter.country?.name"
</code>```

ts :

```<code>opFilter: any = {  country?.name : '' };
</code>```

答:
What you want to achieve can be done using a simple pipe.

```<code>@Pipe({ name: 'countryFilter' })
export class CountryFilterPipe implements PipeTransform {

  transform(operators: Operator[], countryName) {
    return operators.filter(operator => operator.country === countryName);
  }
}
</code>```

and bind it in your template like this:

```<code><h2 *ngFor="let op of operators | countryFilter: country">{{op.name}}</h2>
</code>```

Where country is a property containing the name of the country you want to filter.

Here is a full demo:
https://plnkr.co/edit/GTP6P0PCDudH3NmWkkJf?p=preview

Title: Angular 2 Correct syntax

Body:
We have an entity called operator which has a relationship with an entity called country .We want to filter an operator list based on country name how can we write this filter from the operator ? What is the correct syntax ?

html :

[(ngModel)]="opFilter.country?.name"

ts :

opFilter: any = {  country?.name : '' };

Body:
What you want to achieve can be done using a simple pipe.

@Pipe({ name: 'countryFilter' })
export class CountryFilterPipe implements PipeTransform {

  transform(operators: Operator[], countryName) {
    return operators.filter(operator => operator.country === countryName);
  }
}

and bind it in your template like this:

<h2 *ngFor="let op of operators | countryFilter: country">{{op.name}}</h2>

Where country is a property containing the name of the country you want to filter.

Here is a full demo:
https://plnkr.co/edit/GTP6P0PCDudH3NmWkkJf?p=preview


问:
Cause of error in RcppExport
In a .cpp file that I'm editing in RStudio, the following code

```<code>// [[Rcpp::depends(RcppArmadillo)]]

#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
mat mkGramMatrix (mat X, int n, double (*kernel) (mat, mat, double), double k_param=0){
  double (*func_kernel) (mat, mat, double);
  func_kernel = kernel;

  mat K(n, n);

  for (int i = 0; i < n; i++){
    for (int j = 0; j < n; j++){
      K(i, j) = func_kernel(X.row(i), X.row(j), k_param);
    }
  }
  return K;
}
</code>```

produces the following error when I try to source inside RStudio:

```<code>KFDA_Rcpp.cpp:138:63: error: cannot combine with previous 'type-name' declaration specifier
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
                                                                       ^
KFDA_Rcpp.cpp:138:70: error: expected ';' after top level declarator
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
                                                                              ^
                                                                              ;
KFDA_Rcpp.cpp:138:74: error: expected unqualified-id
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
                                                                                ^
3 errors generated.
</code>```

Why is it placing a right parenthesis in

```<code>SEXP double)SEXP
</code>```

when I believe I am using the function pointer correctly? I have successfully compiled and used other RcppArmadillo functions without problem but this is the first function I'm making that utilizes a function pointer so I can specify the kernel at the time I call this function.

答:
You cannot put a function pointer in the interface as it is not a type that maps to SEXP.

We can only call functions from R that map to the .Call() interface which requires SEXP arguments --- so we can use types for which we have mappers to and from SEXP.

The easy way out here is to use Rcpp::XPtr. It provides an 'external pointer interface' through which you can pass your kernel function. Inside the mkGramMatrix() function you can then dereference the XPtr to the functions you want to call. There are several posts here and on the Rcpp Gallery to get you started.  It is a great mechanism: hang in there and read up on it.

Title: Cause of error in RcppExport

Body:
In a .cpp file that I'm editing in RStudio, the following code

// [[Rcpp::depends(RcppArmadillo)]]

#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
mat mkGramMatrix (mat X, int n, double (*kernel) (mat, mat, double), double k_param=0){
  double (*func_kernel) (mat, mat, double);
  func_kernel = kernel;

  mat K(n, n);

  for (int i = 0; i < n; i++){
    for (int j = 0; j < n; j++){
      K(i, j) = func_kernel(X.row(i), X.row(j), k_param);
    }
  }
  return K;
}

produces the following error when I try to source inside RStudio:

KFDA_Rcpp.cpp:138:63: error: cannot combine with previous 'type-name' declaration specifier
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
                                                                       ^
KFDA_Rcpp.cpp:138:70: error: expected ';' after top level declarator
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
                                                                              ^
                                                                              ;
KFDA_Rcpp.cpp:138:74: error: expected unqualified-id
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
                                                                                ^
3 errors generated.

Why is it placing a right parenthesis in

SEXP double)SEXP

when I believe I am using the function pointer correctly? I have successfully compiled and used other RcppArmadillo functions without problem but this is the first function I'm making that utilizes a function pointer so I can specify the kernel at the time I call this function.


问:
function pointer equal to another pointer within the function, why need to add *
please take look at Node *newNode(), i dont understand why i must add * for p=x
i made an Node named x(with data & next), and created a new memory space *p by using malloc,
then let p = x, but by i must add * for p=x?</p>

```<code>#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    Node *next;
};

Node *newNode(int data, Node *next){
    Node x = {data, next};
    Node *p = (Node *)malloc(sizeof(Node));
    *p = x; //i dont understand why an * need to be added here
    return p;
}

showNode(const struct Node *p){
    printf("%d\n", p->data);
}

int main(){
    Node *pHead = NULL;
    for(int i=4; i>=0; i--) {
        pHead = newNode(i,pHead);
    }
    printf("%d\n", pHead->next->next->next->data);

    Node* p = pHead;
    while(p != NULL){
        showNode(p);
        p = p-> next;
    }

    p = pHead;
    while(p != NULL){
        Node *pTemp = p;
        p = p->next;
        free(pTemp);
    }
}
</code>```

答:
If you just look at the line above the assignment, it says

```<code>Node *p = ...;
</code>```

So *p is a Node. And so is x from the declaration Node x = ...;

If you want to assign one Node to another, you use their names x and *p.

Body:
please take look at Node *newNode(), i dont understand why i must add * for p=x
i made an Node named x(with data & next), and created a new memory space *p by using malloc,
then let p = x, but by i must add * for p=x?

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    Node *next;
};

Node *newNode(int data, Node *next){
    Node x = {data, next};
    Node *p = (Node *)malloc(sizeof(Node));
    *p = x; //i dont understand why an * need to be added here
    return p;
}

showNode(const struct Node *p){
    printf("%d\n", p->data);
}

int main(){
    Node *pHead = NULL;
    for(int i=4; i>=0; i--) {
        pHead = newNode(i,pHead);
    }
    printf("%d\n", pHead->next->next->next->data);

    Node* p = pHead;
    while(p != NULL){
        showNode(p);
        p = p-> next;
    }

    p = pHead;
    while(p != NULL){
        Node *pTemp = p;
        p = p->next;
        free(pTemp);
    }
}

Body:
If you just look at the line above the assignment, it says

Node *p = ...;

So *p is a Node. And so is x from the declaration Node x = ...;

If you want to assign one Node to another, you use their names x and *p.


问:
Ruby Net::HTTP delete method with uri params and form data
So I can successfully get a session token with my REST api like so:

```<code>uri = URI.parse("#{@restapi}/users/login/cloud")
response = Net::HTTP.post_form(uri, {"username" => "jason", "password" => "password123"})
</code>```

It returns the following JSON:

```<code>{ "username" : "jason" , "token" : "1234sometoken567890" , "account" : "myaccount" , "profile" : "main"}
</code>```

I need to use the token with my form data to call this function as stated in the APIs WADL:

```<code><resource path="/removeProfile">
  <method id="removeProfile" name="DELETE">
    <request>
      <representation mediaType="application/x-www-form-urlencoded">
        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="a" style="query" type="xs:string"/>
        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="p" style="query" type="xs:string"/>
      </representation>
    </request>
    <response>
      <representation mediaType="application/json"/>
    </response>
  </method>
</resource>
</code>```

This tells me that I need to do the following in my REST call:

```<code>1) Request Method:DELETE
2) Form Data a= and p=
3) append the token to the url
</code>```

In the browser it looks like:
https://my.domain.com/rest/removeProfile?token=1234sometoken567890

with Form Data:

```<code>a=myaccount&p=someprofile
</code>```

I tried this in Ruby:

```<code>uri = URI.parse("#{@rest}/removeProfile")
# get the token with the connection code
uri.query = URI.encode_www_form(utk: "#{@token}")
http = Net::HTTP.new(uri.host, uri.port)
http.set_form_data({"a" => "#{@account}", "p" => "#{@profile}"})
request = Net::HTTP::Delete.new(uri.path)
response = http.request(request)
</code>```

Trying to mimic curl doing this (which doesn't work by the way):

```<code>curl -i -X DELETE "https://my.domain.com/rest/removeProfile?utk=1234sometoken567890&a=myaccount&p=someprofile"
</code>```

What is the proper way to send a http DELETE method with Query String Parameters and form data?

NOTE:

Here is my current code:

```<code>  def remove_profile(account, profile)

    @account = account
    @profile = profile

    uri = URI.parse("#{@rest}/removeProfile")
    http = Net::HTTP.new(uri.host, uri.port)
    puts 'uri.path = ' + uri.path
    request = Net::HTTP::Delete.new(uri.path)
    request.body = "utk=#{@utk}&a=#{@account}&p=#{@profile}"
    puts 'request.body = ' + request.body
    response = http.request(request)

  end
</code>```

Ruby blows up with a stack trace like so:

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/protocol.rb:153:in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)
</code>```

Any idea what I am doing wrong here?

答:
To pass arguments in url of delete call, you can do the following:

```<code>    uri = URI.parse('http://localhost/test')
    http = Net::HTTP.new(uri.host, uri.port)
    attribute_url = '?'
    attribute_url << body.map{|k,v| "#{k}=#{v}"}.join('&')
    request = Net::HTTP::Delete.new(uri.request_uri+attribute_url)
    response = http.request(request)
</code>```

where body is a hashmap of your parameters:
  in your example: {:a=> 'myaccount' :p=>'someprofile'}

Body:
So I can successfully get a session token with my REST api like so:

uri = URI.parse("#{@restapi}/users/login/cloud")
response = Net::HTTP.post_form(uri, {"username" => "jason", "password" => "password123"})

It returns the following JSON:

{ "username" : "jason" , "token" : "1234sometoken567890" , "account" : "myaccount" , "profile" : "main"}

I need to use the token with my form data to call this function as stated in the APIs WADL:

<resource path="/removeProfile">
  <method id="removeProfile" name="DELETE">
    <request>
      <representation mediaType="application/x-www-form-urlencoded">
        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="a" style="query" type="xs:string"/>
        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="p" style="query" type="xs:string"/>
      </representation>
    </request>
    <response>
      <representation mediaType="application/json"/>
    </response>
  </method>
</resource>

This tells me that I need to do the following in my REST call:

1) Request Method:DELETE
2) Form Data a= and p=
3) append the token to the url

In the browser it looks like:
https://my.domain.com/rest/removeProfile?token=1234sometoken567890

with Form Data:

a=myaccount&p=someprofile

I tried this in Ruby:

uri = URI.parse("#{@rest}/removeProfile")
# get the token with the connection code
uri.query = URI.encode_www_form(utk: "#{@token}")
http = Net::HTTP.new(uri.host, uri.port)
http.set_form_data({"a" => "#{@account}", "p" => "#{@profile}"})
request = Net::HTTP::Delete.new(uri.path)
response = http.request(request)

Trying to mimic curl doing this (which doesn't work by the way):

curl -i -X DELETE "https://my.domain.com/rest/removeProfile?utk=1234sometoken567890&a=myaccount&p=someprofile"

What is the proper way to send a http DELETE method with Query String Parameters and form data?

NOTE:

Here is my current code:

  def remove_profile(account, profile)

    @account = account
    @profile = profile

    uri = URI.parse("#{@rest}/removeProfile")
    http = Net::HTTP.new(uri.host, uri.port)
    puts 'uri.path = ' + uri.path
    request = Net::HTTP::Delete.new(uri.path)
    request.body = "utk=#{@utk}&a=#{@account}&p=#{@profile}"
    puts 'request.body = ' + request.body
    response = http.request(request)

  end

Ruby blows up with a stack trace like so:

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/protocol.rb:153:in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)

Any idea what I am doing wrong here?

Body:
To pass arguments in url of delete call, you can do the following:

    uri = URI.parse('http://localhost/test')
    http = Net::HTTP.new(uri.host, uri.port)
    attribute_url = '?'
    attribute_url << body.map{|k,v| "#{k}=#{v}"}.join('&')
    request = Net::HTTP::Delete.new(uri.request_uri+attribute_url)
    response = http.request(request)

where body is a hashmap of your parameters:
  in your example: {:a=> 'myaccount' :p=>'someprofile'}


问:
How to use S3 and EBS in tandem for cost effective analytics on AWS?
I receive very large (5TB) .csv files from my clients on S3 buckets. I have to process these files, add columns to them and store them back.

I might need to work with the files in the same way as I increase the number of features for future improved models.

Clearly because S3 stores data as objects, every time I make a change, I have to read and write 5TB of data.

What is the best approach I can take to process these data cost effectively and promptly:

Store a 5TB file on S3 as object, every time read the object, do
the processing and save the result back to S3

Store the 5TB on S3 as object, read the object, chunk it to smaller objects and save them back to S3 as multiple objects so in future just work with the chunks I am interested in

Save every thing on EBS from start, mount it to the EC2 and do the processing

Thank you

答:
First, a warning -- the maximum size of an object in Amazon S3 is 5TB. If you are going to add information that results in a larger object, then you will likely hit that limit.

The smarter way of processing this amount of data is to do it in parallel and preferably in multiple, smaller files rather than a single 5TB file.

Amazon EMR (effectively, a managed Hadoop environment) is excellent for performing distributed operations across large data sets. It can process data from many files in parallel and can compress/decompress data on-the-fly. It's complex to learn, but very efficient and capable.

If you are sticking with your current method of processing the data, I would recommend:

If your application can read directly from S3, use that as the source. Otherwise, copy the file(s) to EBS.

Process the data

Store the output locally in EBS, preferably in smaller files (GBs rather than TBs)

Copy the files to S3 (or keep them on EBS if that meets your needs)


问:
How to Simulate click to click a website button in UWP?
I want to learn how to Simulate click. For example, clicking 'Search' button in Bing. Now I have assigned the Value to be searched in the Search Box but how to Simulate click on Search button.

Here is my Code

```<code>private async void Button_ClickAsync(object sender, RoutedEventArgs e)
{
        var httpClint = new HttpClient();
        var elements = await httpClint.GetStringAsync(new Uri("https://www.bing.com/"));
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(elements);
        var node1 = htmlDocument.DocumentNode.Descendants("input").Where(p => p.GetAttributeValue("class", "") == "b_searchbox").ToArray();
        node1[0].Attributes[5].Value = InputText.Text;
        var node2 = htmlDocument.DocumentNode.Descendants("input").Where(p => p.GetAttributeValue("class", "") == "b_searchboxSubmit").ToArray();
}
</code>```

I know how to do it on WPF. I want a code equivalent to

```<code>webBrowser1.Document.GetElementById("ID").InvokeMember("click");
</code>```

for UWP

答:
You cannot do what your want with HtmlDocument. This is a static HTML DOM tree where the javascript is not active.
In your WPF you seem to be using the webview control (webBrower1) and not an HTML document.

The equivalent of WPF WebBrowser in UWP is WebView. You can load it from an HTTP request and invoke JS scripts.

You can either invoke a script from the page or any arbitrary JS code by invoking the eval function and providing your function code as parameter.

In the following code, I'm initiating a search on the word 'bing' once the Bing home page is loaded.

```<code>protected override void OnNavigatedTo(NavigationEventArgs e)
{
    webview.NavigationCompleted += OnNavigationCompleted;
    webview.Navigate(new Uri("http://www.bing.com"));
}

private async void OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    webview.NavigationCompleted -= OnNavigationCompleted;

    var inputValue = "Bing";

    var functionString = string.Format(@"document.getElementsByClassName('b_searchbox')[0].innerText = '{0}';
                                        document.getElementsByClassName('b_searchboxSubmit')[0].click();", inputValue);
    await webview.InvokeScriptAsync("eval", new string[] { functionString });
}
</code>```

Body:
I want to learn how to Simulate click. For example, clicking 'Search' button in Bing. Now I have assigned the Value to be searched in the Search Box but how to Simulate click on Search button.

Here is my Code

private async void Button_ClickAsync(object sender, RoutedEventArgs e)
{
        var httpClint = new HttpClient();
        var elements = await httpClint.GetStringAsync(new Uri("https://www.bing.com/"));
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(elements);
        var node1 = htmlDocument.DocumentNode.Descendants("input").Where(p => p.GetAttributeValue("class", "") == "b_searchbox").ToArray();
        node1[0].Attributes[5].Value = InputText.Text;
        var node2 = htmlDocument.DocumentNode.Descendants("input").Where(p => p.GetAttributeValue("class", "") == "b_searchboxSubmit").ToArray();
}

I know how to do it on WPF. I want a code equivalent to

webBrowser1.Document.GetElementById("ID").InvokeMember("click");

for UWP

Body:
You cannot do what your want with HtmlDocument. This is a static HTML DOM tree where the javascript is not active.
In your WPF you seem to be using the webview control (webBrower1) and not an HTML document.

The equivalent of WPF WebBrowser in UWP is WebView. You can load it from an HTTP request and invoke JS scripts.

You can either invoke a script from the page or any arbitrary JS code by invoking the eval function and providing your function code as parameter.

In the following code, I'm initiating a search on the word 'bing' once the Bing home page is loaded.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    webview.NavigationCompleted += OnNavigationCompleted;
    webview.Navigate(new Uri("http://www.bing.com"));
}

private async void OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    webview.NavigationCompleted -= OnNavigationCompleted;

    var inputValue = "Bing";

    var functionString = string.Format(@"document.getElementsByClassName('b_searchbox')[0].innerText = '{0}';
                                        document.getElementsByClassName('b_searchboxSubmit')[0].click();", inputValue);
    await webview.InvokeScriptAsync("eval", new string[] { functionString });
}


问:
Want to click f12 using jquery
I am working on one project in which I disabled f12 and right click using jquery and its working fine.
Code for it:

```<code>$(document).keydown(function(event){
 if(event.keyCode==123){
  return false;
 }
 else if(event.ctrlKey && event.shiftKey && event.keyCode==73){
    return false;  //Prevent from ctrl+shift+i
 }
});

$(document).on("contextmenu",function(e){
  e.preventDefault();
});
</code>```

Is there any way so that I can click f12 key using jquery.
I want this because I am facing one issue.
eg. If google.com is already opened with insect element and then I load my page then it shows me inspect element. So I want to hide inspect window on page load.

Is there any way???

答:
Simply: You can't.

The Dev Tools are not sandboxed (unlike any web page), thus granting sandboxed environments the power to open and control an unsandboxed environment is a major security design flaw.

I hope this answers your question :-)

Title: Want to click f12 using jquery

Body:
I am working on one project in which I disabled f12 and right click using jquery and its working fine.
Code for it:

$(document).keydown(function(event){
 if(event.keyCode==123){
  return false;
 }
 else if(event.ctrlKey && event.shiftKey && event.keyCode==73){
    return false;  //Prevent from ctrl+shift+i
 }
});

$(document).on("contextmenu",function(e){
  e.preventDefault();
});

Is there any way so that I can click f12 key using jquery.
I want this because I am facing one issue.
eg. If google.com is already opened with insect element and then I load my page then it shows me inspect element. So I want to hide inspect window on page load.

Is there any way???


问:
Conditional construct not working in Python regex
I an a newbie in python and I want to use my regex in re.sub. I tried it on regex101 and it works. Somehow when I tried to use it on my python (version 3.6) it doesn't work properly. I get the following warning

bad character in group name '?=[^\t]*' at position 5

This is my code:

```<code>re = r"(?(?=[^\t]*)([\t]+))";
str = 'a            bold, italic,           teletype';
subst = ',';

result = re.sub($re, $subst, $str);
</code>```

答:
The problem is that you cannot use lookarounds in conditional constructs in a Python re. Only capturing group IDs to test if the previous group matched.

(?(id/name)yes-pattern|no-pattern)

  Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted.

The (?(?=[^\t]*)([\t]+)) regex checks if there are 0+ chars other than tabs at the current location, and if yes, matches and captures 1 or more tabs. This makes no sense. If you want to match the first occurrence of 1 or more tabs, you may use re.sub with a mere "\t+" pattern and count=1 argument.

```<code>import re
reg = "\t+";
s = 'a          bold, italic,           teletype';
result = re.sub(reg, ',', s, count=1);
print(result);
</code>```

See the Python demo

ContentLicense: CC BY-SA 4.0

Body:
I an a newbie in python and I want to use my regex in re.sub. I tried it on regex101 and it works. Somehow when I tried to use it on my python (version 3.6) it doesn't work properly. I get the following warning

bad character in group name '?=[^\t]*' at position 5

This is my code:

re = r"(?(?=[^\t]*)([\t]+))";
str = 'a            bold, italic,           teletype';
subst = ',';

result = re.sub($re, $subst, $str);

Body:
The problem is that you cannot use lookarounds in conditional constructs in a Python re. Only capturing group IDs to test if the previous group matched.

(?(id/name)yes-pattern|no-pattern)

  Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted.

The (?(?=[^\t]*)([\t]+)) regex checks if there are 0+ chars other than tabs at the current location, and if yes, matches and captures 1 or more tabs. This makes no sense. If you want to match the first occurrence of 1 or more tabs, you may use re.sub with a mere "\t+" pattern and count=1 argument.

import re
reg = "\t+";
s = 'a          bold, italic,           teletype';
result = re.sub(reg, ',', s, count=1);
print(result);

See the Python demo


问:
Phonegap app not initially filling 100% of viewport height
I have an issue when testing a phoengap app on my Samsung Galaxy smart phone. On the initial load, the body does not fill 100% of the viewport's height (see image.)

This happens irrespective of whether the phone is in portrait or landscape mode. However, as soon as the phone is rotated, the content fills the full height. And the problem does not appear on each future load, only if I have cleared the cache.

Does anyone know what could be causing this?

Here is the markup:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
      <title>Untitled Document</title>
      <style>
        html, body {
          background:#CC9;
          height: 100vh;
          min-height: 100vh;
        }
      </style>
    </head>

    <body>
      hello
    </body>

  </html>
</code>```

答:
Is the gap where the navigation bar would be if the phone didn't have physical controls?

I encountered a similar problem with the menu bar on my galaxy j5 on resuming. I solved it by using cordova-plugin-statusbar and then adding code to onResume to force a refresh:

```<code>    window.setTimeout(function () { StatusBar.hide(); console.log("hidden"); }, 1000);
</code>```

I can see that there is a cordova-plugin-navigationbar (but haven't looked further into it) - perhaps a similar approach would work for your issue?

Body:
I have an issue when testing a phoengap app on my Samsung Galaxy smart phone. On the initial load, the body does not fill 100% of the viewport's height (see image.)

This happens irrespective of whether the phone is in portrait or landscape mode. However, as soon as the phone is rotated, the content fills the full height. And the problem does not appear on each future load, only if I have cleared the cache.

Does anyone know what could be causing this?

Here is the markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
      <title>Untitled Document</title>

      hello

Body:
Is the gap where the navigation bar would be if the phone didn't have physical controls?

I encountered a similar problem with the menu bar on my galaxy j5 on resuming. I solved it by using cordova-plugin-statusbar and then adding code to onResume to force a refresh:

    window.setTimeout(function () { StatusBar.hide(); console.log("hidden"); }, 1000);

I can see that there is a cordova-plugin-navigationbar (but haven't looked further into it) - perhaps a similar approach would work for your issue?


问:
How can I reach a specific replica of a stateless service
I've created a stateless service within Service Fabric. It has a SingletonPartition, but multiple instances (InstanceCount is -1 in my case).

I want to communicate with a specific replica of this service. To find all replica's I use:

```<code>var fabricClient = new FabricClient();
var serviceUri = new Uri(SERVICENAME);

Partition partition = (await fabricClient.QueryManager.GetPartitionListAsync(serviceUri)).First();
foreach(Replica replica in await fabricClient.QueryManager.GetReplicaListAsync(partition.PartitionInformation.Id))
{
  // communicate with this replica, but how to construct the proxy?
  //var eventHandlerServiceClient = ServiceProxy.Create<IService>(new Uri(replica.ReplicaAddress));
}
</code>```

The problem is that there is no overload of the ServiceProxy to create one to the replica. Is there another way to communicate with a specific replica?

Edit

The scenario we are building is the following. We have different moving parts with counter information: 1 named partitioned stateful service (with a couple of hundred partitions), 1 int64 partitioned stateful service, and 1 actor with state. To aggregate the counter information, we need to reach out to all service-partitions and actor-instances.

We could of course reverse it and let everyone send there counts to a single (partitioned) service. But that would add a network call in the normal flow (and thus overhead).

Instead, we came up with the following. The mentioned services&actors are combined into one executable and one servicemanifest. Therefore they are in the same process. We add a stateless service with instancecount -1 to the mentioned services&actors. All counter information is stored inside a static variable. The stateless service can read this counter information.
Now, we only need to reach out to the stateless service (which has an upper limit of the number of nodes).

答:
"Well, I would turn this question around and ask why would you want to connect to a specific stateless service instance?"

One example would be if you have multiple (3x) stateless service instances all having WebSocket connections to different clients, let's say 500 each. And you want to notify all 1500 (500x3) users of the same message, if it was possible to connect directly to a specific instance (which I would expect was possible, since I can query for those instances using the FabricClient), I could send a message to each instance which would redirect it to all connected clients.

Instead we have to come up with any of multiple workarounds:

Have all instances connect to some evented system that allows them to trigger on incoming message, e.g. Azure Event Hubs, Azure Service Bus, RedisCache.

Host an additional endpoint, as mentioned here, which makes it 3 endpoints pr service instance: WCF, WebSocket, HTTP.

Change to a stateful partitioned service which doesn't hold any state or any replicas, but simply allows to call partitions.

Currently having some serious issues with RedisCache so migrating away from that, and would like to avoid external dependencies such as Event Hubs and Service Bus just for this scenario.

Sending many messages each second, which will give additional overhead when having to call HTTP, and then the request need to transition over to the WebSocket context.

Body:
I've created a stateless service within Service Fabric. It has a SingletonPartition, but multiple instances (InstanceCount is -1 in my case).

I want to communicate with a specific replica of this service. To find all replica's I use:

var fabricClient = new FabricClient();
var serviceUri = new Uri(SERVICENAME);

Partition partition = (await fabricClient.QueryManager.GetPartitionListAsync(serviceUri)).First();
foreach(Replica replica in await fabricClient.QueryManager.GetReplicaListAsync(partition.PartitionInformation.Id))
{
  // communicate with this replica, but how to construct the proxy?
  //var eventHandlerServiceClient = ServiceProxy.Create<IService>(new Uri(replica.ReplicaAddress));
}

The problem is that there is no overload of the ServiceProxy to create one to the replica. Is there another way to communicate with a specific replica?

Edit

The scenario we are building is the following. We have different moving parts with counter information: 1 named partitioned stateful service (with a couple of hundred partitions), 1 int64 partitioned stateful service, and 1 actor with state. To aggregate the counter information, we need to reach out to all service-partitions and actor-instances.

We could of course reverse it and let everyone send there counts to a single (partitioned) service. But that would add a network call in the normal flow (and thus overhead).

Instead, we came up with the following. The mentioned services&actors are combined into one executable and one servicemanifest. Therefore they are in the same process. We add a stateless service with instancecount -1 to the mentioned services&actors. All counter information is stored inside a static variable. The stateless service can read this counter information.
Now, we only need to reach out to the stateless service (which has an upper limit of the number of nodes).


问:
How to use functions/methods in SWITCH CASE statement in Java
I have 3 types of array:
ControlType
ControlName
ControlValue

When the control type is "ClickButton", I have to pass the corresponding ControlName and ControlValue.

Code:

```<code>public class StringSwitchDemo extends StringSwitchDemoHelper
{
    public static int getMonthNumber(String ControlType) {
        int ControlValue = 0;
        int ControlName  = 0;

        if (ControlType == null) {
            return ControlValue;
        }

        switch (ControlType.toString()) {
            case ClickButton:
                return ControlType(ControlValue, ControlName);
                break;
        }

        return ControlValue;
    }

    private static int ControlType(String controlValue, String controlName) {
        // TODO Auto-generated method stub

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

答:
```<code>I simplified like below:

`import resources.StringSwitchDemoHelper;
/**
 * Description   : Functional Test Script
 * @author IBM
 */

public class StringSwitchDemo extends StringSwitchDemoHelper
{

    public static String getControlValue(String controlType) {

        String controlValue = null;
        String controlName  = null;

        if (controlType == null) {
            return controlValue;
        }

        switch (controlType) {
            case "Html.INPUT.text":
                return EnterText (controlName,controlValue);
        }
    return controlValue;

    }

public static String EnterText(String controlName, String value)
{
    TextGuiTestObject textObj = findList(controlName);
    if (textObj != null) {
    textObj.setText(value);
    } else {
    throw new ObjectNotFoundException();
    }
    return value;}
}`

Still it is not working!!
</code>```

Body:
I have 3 types of array:
ControlType
ControlName
ControlValue

When the control type is "ClickButton", I have to pass the corresponding ControlName and ControlValue.

Code:

public class StringSwitchDemo extends StringSwitchDemoHelper
{
    public static int getMonthNumber(String ControlType) {
        int ControlValue = 0;
        int ControlName  = 0;

        if (ControlType == null) {
            return ControlValue;
        }

        switch (ControlType.toString()) {
            case ClickButton:
                return ControlType(ControlValue, ControlName);
                break;
        }

        return ControlValue;
    }

    private static int ControlType(String controlValue, String controlName) {
        // TODO Auto-generated method stub

        return 0;
    }
}


问:
How to modify and add words sequentially in a list - Python
I don't know if this is possible as I'm a newbie to Python, but I wanted to create a list that has a sequential order to it. So I have two lists as follows:

```<code>stock_list = ['MSFT', 'YHOO']
ret = [0, 1, 2, 3]

returns = ["ret{}".format(*ret) for ret in enumerate(ret)]
</code>```

returns

```<code>['ret0', 'ret1', 'ret2', 'ret3']
</code>```

From the above lists of returns and stock_list, I can create the following:

```<code>for index, ret_stock in enumerate(returns):
    returns[index] += "_MSFT"
returns
</code>```

Output:

```<code>['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT']
</code>```

Ideally, what I'm trying to get is this using the stock_list for both tickers, MSFT and YHOO:

```<code>  ['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT',
       'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']
</code>```

So, I could do the previous method with enumerate, but that would become increasingly time consuming if, say instead of just two tickers, MSFT and YHOO, I had 100.

By creating a list of say, 100 or more tickers, and applying it to a list of returns such as this one already shown.

```<code>['ret0', 'ret1', 'ret2', 'ret3']
</code>```

Is it possible? Maybe I'm asking the wrong question or approaching from the wrong angle.

答:
You're not looping through the stock_list items.. just add another loop.

This code will:

for each stock in stock_list

from 1 to the defined range of tickers (100 in the example), do the following:

2.1 create string s that concatenates the prefix with the stock name

2.2 append string s to stock_list_v2

obs.: you don't have to use ret = [0, 1, 2, 3], just define a range().

Code:

```<code>stock_list = ['MSFT', 'YHOO']
stock_list_v2 = []

for stock in stock_list:
    for i in range(101):
        s = 'ret' + str(i) + '_' + stock
        stock_list_v2.append(s)
</code>```

Output:

```<code>['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT', 'ret4_MSFT', 'ret5_MSFT', 'ret6_MSFT', 'ret7_MSFT', 'ret8_MSFT', 'ret9_MSFT', 'ret10_MSFT', 'ret11_MSFT', 'ret12_MSFT', 'ret13_MSFT', 'ret14_MSFT', 'ret15_MSFT', 'ret16_MSFT', 'ret17_MSFT', 'ret18_MSFT', 'ret19_MSFT', 'ret20_MSFT', 'ret21_MSFT', 'ret22_MSFT', 'ret23_MSFT', 'ret24_MSFT', 'ret25_MSFT', 'ret26_MSFT', 'ret27_MSFT', 'ret28_MSFT', 'ret29_MSFT', 'ret30_MSFT', 'ret31_MSFT', 'ret32_MSFT', 'ret33_MSFT', 'ret34_MSFT', 'ret35_MSFT', 'ret36_MSFT', 'ret37_MSFT', 'ret38_MSFT', 'ret39_MSFT', 'ret40_MSFT', 'ret41_MSFT', 'ret42_MSFT', 'ret43_MSFT', 'ret44_MSFT', 'ret45_MSFT', 'ret46_MSFT', 'ret47_MSFT', 'ret48_MSFT', 'ret49_MSFT', 'ret50_MSFT', 'ret51_MSFT', 'ret52_MSFT', 'ret53_MSFT', 'ret54_MSFT', 'ret55_MSFT', 'ret56_MSFT', 'ret57_MSFT', 'ret58_MSFT', 'ret59_MSFT', 'ret60_MSFT', 'ret61_MSFT', 'ret62_MSFT', 'ret63_MSFT', 'ret64_MSFT', 'ret65_MSFT', 'ret66_MSFT', 'ret67_MSFT', 'ret68_MSFT', 'ret69_MSFT', 'ret70_MSFT', 'ret71_MSFT', 'ret72_MSFT', 'ret73_MSFT', 'ret74_MSFT', 'ret75_MSFT', 'ret76_MSFT', 'ret77_MSFT', 'ret78_MSFT', 'ret79_MSFT', 'ret80_MSFT', 'ret81_MSFT', 'ret82_MSFT', 'ret83_MSFT', 'ret84_MSFT', 'ret85_MSFT', 'ret86_MSFT', 'ret87_MSFT', 'ret88_MSFT', 'ret89_MSFT', 'ret90_MSFT', 'ret91_MSFT', 'ret92_MSFT', 'ret93_MSFT', 'ret94_MSFT', 'ret95_MSFT', 'ret96_MSFT', 'ret97_MSFT', 'ret98_MSFT', 'ret99_MSFT', 'ret100_MSFT', 'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO', 'ret4_YHOO', 'ret5_YHOO', 'ret6_YHOO', 'ret7_YHOO', 'ret8_YHOO', 'ret9_YHOO', 'ret10_YHOO', 'ret11_YHOO', 'ret12_YHOO', 'ret13_YHOO', 'ret14_YHOO', 'ret15_YHOO', 'ret16_YHOO', 'ret17_YHOO', 'ret18_YHOO', 'ret19_YHOO', 'ret20_YHOO', 'ret21_YHOO', 'ret22_YHOO', 'ret23_YHOO', 'ret24_YHOO', 'ret25_YHOO', 'ret26_YHOO', 'ret27_YHOO', 'ret28_YHOO', 'ret29_YHOO', 'ret30_YHOO', 'ret31_YHOO', 'ret32_YHOO', 'ret33_YHOO', 'ret34_YHOO', 'ret35_YHOO', 'ret36_YHOO', 'ret37_YHOO', 'ret38_YHOO', 'ret39_YHOO', 'ret40_YHOO', 'ret41_YHOO', 'ret42_YHOO', 'ret43_YHOO', 'ret44_YHOO', 'ret45_YHOO', 'ret46_YHOO', 'ret47_YHOO', 'ret48_YHOO', 'ret49_YHOO', 'ret50_YHOO', 'ret51_YHOO', 'ret52_YHOO', 'ret53_YHOO', 'ret54_YHOO', 'ret55_YHOO', 'ret56_YHOO', 'ret57_YHOO', 'ret58_YHOO', 'ret59_YHOO', 'ret60_YHOO', 'ret61_YHOO', 'ret62_YHOO', 'ret63_YHOO', 'ret64_YHOO', 'ret65_YHOO', 'ret66_YHOO', 'ret67_YHOO', 'ret68_YHOO', 'ret69_YHOO', 'ret70_YHOO', 'ret71_YHOO', 'ret72_YHOO', 'ret73_YHOO', 'ret74_YHOO', 'ret75_YHOO', 'ret76_YHOO', 'ret77_YHOO', 'ret78_YHOO', 'ret79_YHOO', 'ret80_YHOO', 'ret81_YHOO', 'ret82_YHOO', 'ret83_YHOO', 'ret84_YHOO', 'ret85_YHOO', 'ret86_YHOO', 'ret87_YHOO', 'ret88_YHOO', 'ret89_YHOO', 'ret90_YHOO', 'ret91_YHOO', 'ret92_YHOO', 'ret93_YHOO', 'ret94_YHOO', 'ret95_YHOO', 'ret96_YHOO', 'ret97_YHOO', 'ret98_YHOO', 'ret99_YHOO', 'ret100_YHOO']
</code>```

p.s.: you'll gain time if you transform this loop in a list comprehension.

```<code>stock_list_v2 = ['ret' + str(i) + '_' + stock for i in range(101) for stock in stock_list]
</code>```

Body:
I don't know if this is possible as I'm a newbie to Python, but I wanted to create a list that has a sequential order to it. So I have two lists as follows:

stock_list = ['MSFT', 'YHOO']
ret = [0, 1, 2, 3]

returns = ["ret{}".format(*ret) for ret in enumerate(ret)]

returns

['ret0', 'ret1', 'ret2', 'ret3']

From the above lists of returns and stock_list, I can create the following:

for index, ret_stock in enumerate(returns):
    returns[index] += "_MSFT"
returns

Output:

['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT']

Ideally, what I'm trying to get is this using the stock_list for both tickers, MSFT and YHOO:

  ['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT',
       'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']

So, I could do the previous method with enumerate, but that would become increasingly time consuming if, say instead of just two tickers, MSFT and YHOO, I had 100.

By creating a list of say, 100 or more tickers, and applying it to a list of returns such as this one already shown.

['ret0', 'ret1', 'ret2', 'ret3']

Is it possible? Maybe I'm asking the wrong question or approaching from the wrong angle.

Body:
You're not looping through the stock_list items.. just add another loop.

This code will:

for each stock in stock_list

from 1 to the defined range of tickers (100 in the example), do the following:

2.1 create string s that concatenates the prefix with the stock name

2.2 append string s to stock_list_v2

obs.: you don't have to use ret = [0, 1, 2, 3], just define a range().

Code:

stock_list = ['MSFT', 'YHOO']
stock_list_v2 = []

for stock in stock_list:
    for i in range(101):
        s = 'ret' + str(i) + '_' + stock
        stock_list_v2.append(s)

Output:

['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT', 'ret4_MSFT', 'ret5_MSFT', 'ret6_MSFT', 'ret7_MSFT', 'ret8_MSFT', 'ret9_MSFT', 'ret10_MSFT', 'ret11_MSFT', 'ret12_MSFT', 'ret13_MSFT', 'ret14_MSFT', 'ret15_MSFT', 'ret16_MSFT', 'ret17_MSFT', 'ret18_MSFT', 'ret19_MSFT', 'ret20_MSFT', 'ret21_MSFT', 'ret22_MSFT', 'ret23_MSFT', 'ret24_MSFT', 'ret25_MSFT', 'ret26_MSFT', 'ret27_MSFT', 'ret28_MSFT', 'ret29_MSFT', 'ret30_MSFT', 'ret31_MSFT', 'ret32_MSFT', 'ret33_MSFT', 'ret34_MSFT', 'ret35_MSFT', 'ret36_MSFT', 'ret37_MSFT', 'ret38_MSFT', 'ret39_MSFT', 'ret40_MSFT', 'ret41_MSFT', 'ret42_MSFT', 'ret43_MSFT', 'ret44_MSFT', 'ret45_MSFT', 'ret46_MSFT', 'ret47_MSFT', 'ret48_MSFT', 'ret49_MSFT', 'ret50_MSFT', 'ret51_MSFT', 'ret52_MSFT', 'ret53_MSFT', 'ret54_MSFT', 'ret55_MSFT', 'ret56_MSFT', 'ret57_MSFT', 'ret58_MSFT', 'ret59_MSFT', 'ret60_MSFT', 'ret61_MSFT', 'ret62_MSFT', 'ret63_MSFT', 'ret64_MSFT', 'ret65_MSFT', 'ret66_MSFT', 'ret67_MSFT', 'ret68_MSFT', 'ret69_MSFT', 'ret70_MSFT', 'ret71_MSFT', 'ret72_MSFT', 'ret73_MSFT', 'ret74_MSFT', 'ret75_MSFT', 'ret76_MSFT', 'ret77_MSFT', 'ret78_MSFT', 'ret79_MSFT', 'ret80_MSFT', 'ret81_MSFT', 'ret82_MSFT', 'ret83_MSFT', 'ret84_MSFT', 'ret85_MSFT', 'ret86_MSFT', 'ret87_MSFT', 'ret88_MSFT', 'ret89_MSFT', 'ret90_MSFT', 'ret91_MSFT', 'ret92_MSFT', 'ret93_MSFT', 'ret94_MSFT', 'ret95_MSFT', 'ret96_MSFT', 'ret97_MSFT', 'ret98_MSFT', 'ret99_MSFT', 'ret100_MSFT', 'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO', 'ret4_YHOO', 'ret5_YHOO', 'ret6_YHOO', 'ret7_YHOO', 'ret8_YHOO', 'ret9_YHOO', 'ret10_YHOO', 'ret11_YHOO', 'ret12_YHOO', 'ret13_YHOO', 'ret14_YHOO', 'ret15_YHOO', 'ret16_YHOO', 'ret17_YHOO', 'ret18_YHOO', 'ret19_YHOO', 'ret20_YHOO', 'ret21_YHOO', 'ret22_YHOO', 'ret23_YHOO', 'ret24_YHOO', 'ret25_YHOO', 'ret26_YHOO', 'ret27_YHOO', 'ret28_YHOO', 'ret29_YHOO', 'ret30_YHOO', 'ret31_YHOO', 'ret32_YHOO', 'ret33_YHOO', 'ret34_YHOO', 'ret35_YHOO', 'ret36_YHOO', 'ret37_YHOO', 'ret38_YHOO', 'ret39_YHOO', 'ret40_YHOO', 'ret41_YHOO', 'ret42_YHOO', 'ret43_YHOO', 'ret44_YHOO', 'ret45_YHOO', 'ret46_YHOO', 'ret47_YHOO', 'ret48_YHOO', 'ret49_YHOO', 'ret50_YHOO', 'ret51_YHOO', 'ret52_YHOO', 'ret53_YHOO', 'ret54_YHOO', 'ret55_YHOO', 'ret56_YHOO', 'ret57_YHOO', 'ret58_YHOO', 'ret59_YHOO', 'ret60_YHOO', 'ret61_YHOO', 'ret62_YHOO', 'ret63_YHOO', 'ret64_YHOO', 'ret65_YHOO', 'ret66_YHOO', 'ret67_YHOO', 'ret68_YHOO', 'ret69_YHOO', 'ret70_YHOO', 'ret71_YHOO', 'ret72_YHOO', 'ret73_YHOO', 'ret74_YHOO', 'ret75_YHOO', 'ret76_YHOO', 'ret77_YHOO', 'ret78_YHOO', 'ret79_YHOO', 'ret80_YHOO', 'ret81_YHOO', 'ret82_YHOO', 'ret83_YHOO', 'ret84_YHOO', 'ret85_YHOO', 'ret86_YHOO', 'ret87_YHOO', 'ret88_YHOO', 'ret89_YHOO', 'ret90_YHOO', 'ret91_YHOO', 'ret92_YHOO', 'ret93_YHOO', 'ret94_YHOO', 'ret95_YHOO', 'ret96_YHOO', 'ret97_YHOO', 'ret98_YHOO', 'ret99_YHOO', 'ret100_YHOO']

p.s.: you'll gain time if you transform this loop in a list comprehension.

stock_list_v2 = ['ret' + str(i) + '_' + stock for i in range(101) for stock in stock_list]