问:
jmx authentication failed in cassandra (zabbix)
I tried to set up zabbix monitoring for a cassandra cluster using JMX i am getting the following error on the node. Please help me solve this,

In zabbix ui the cassandra host showed me this error:

```<code>java.lang.SecurityException: Authentication failed! Credentials required
</code>```

JAVA GATEWAY LOGS

```<code>2017-06-07 11:57:47.538 [pool-1-thread-1] WARN  com.zabbix.gateway.SocketProcessor - error processing request
com.zabbix.gateway.ZabbixException: java.lang.SecurityException: Authentication failed! Credentials required
        at com.zabbix.gateway.JMXItemChecker.getValues(JMXItemChecker.java:97) ~[zabbix-java-gateway-3.0.9.jar:na]
        at com.zabbix.gateway.SocketProcessor.run(SocketProcessor.java:62) ~[zabbix-java-gateway-3.0.9.jar:na]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: java.lang.SecurityException: Authentication failed! Credentials required
        at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticationFailure(Unknown Source) ~[na:1.8.0_131]
        at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticate(Unknown Source) ~[na:1.8.0_131]
        at org.apache.cassandra.utils.JMXServerUtils$JMXPluggableAuthenticatorWrapper.authenticate(JMXServerUtils.java:257) ~[na:na]
        at javax.management.remote.rmi.RMIServerImpl.doNewClient(Unknown Source) ~[na:1.8.0_131]
        at javax.management.remote.rmi.RMIServerImpl.newClient(Unknown Source) ~[na:1.8.0_131]
        at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
</code>```

答: You must set a valid username and password in the JMX items. Test username and password using nodetool.

Body:
I tried to set up zabbix monitoring for a cassandra cluster using JMX i am getting the following error on the node. Please help me solve this,

In zabbix ui the cassandra host showed me this error:

java.lang.SecurityException: Authentication failed! Credentials required

JAVA GATEWAY LOGS

2017-06-07 11:57:47.538 [pool-1-thread-1] WARN  com.zabbix.gateway.SocketProcessor - error processing request
com.zabbix.gateway.ZabbixException: java.lang.SecurityException: Authentication failed! Credentials required
        at com.zabbix.gateway.JMXItemChecker.getValues(JMXItemChecker.java:97) ~[zabbix-java-gateway-3.0.9.jar:na]
        at com.zabbix.gateway.SocketProcessor.run(SocketProcessor.java:62) ~[zabbix-java-gateway-3.0.9.jar:na]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: java.lang.SecurityException: Authentication failed! Credentials required
        at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticationFailure(Unknown Source) ~[na:1.8.0_131]
        at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticate(Unknown Source) ~[na:1.8.0_131]
        at org.apache.cassandra.utils.JMXServerUtils$JMXPluggableAuthenticatorWrapper.authenticate(JMXServerUtils.java:257) ~[na:na]
        at javax.management.remote.rmi.RMIServerImpl.doNewClient(Unknown Source) ~[na:1.8.0_131]
        at javax.management.remote.rmi.RMIServerImpl.newClient(Unknown Source) ~[na:1.8.0_131]
        at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]


来源: stackexchange

问:
Unable to submit custom field, which extends dataview
I have a fiddle which demonstrates this strange behaviour. In a nutshell, I have a custom field which extends Ext.DataView. I need to extend dataview, because this field is supposed to have dynamic contents. This is how my field is defined:

```<code>Ext.define('Ext.ux.SimpleList', {
    extend: 'Ext.DataView',
    alias: 'widget.simplelist',
    requires: [
        'Ext.XTemplate'
    ],
    itemSelector: 'div.record',
    isFormField: true,
    getFieldIdentifier: function () {
        return this.name;
    },
    getModelData: function() {
        var me = this;
        var data = {};
        data[me.getFieldIdentifier()] = me.getValue();
        return data;
    },
    getSubmitData: function() { return {}; },
    submitValue: true,
    isValid: function () { return true; },
    isDirty: function () { return true; },
    validate: function () { return true; },
    isFileUpload: function() { return false; },
    constructor: function(config) {
        Ext.applyIf(config, {
            tpl: [
               '{% var name = this.owner.name; %}',
                '<tpl for=".">',
                    '<div class="record"><input record-id="{id}" type="checkbox" name="{[name]}" /> {label}</div>',
                '</tpl>',
                {compiled: true}
            ]
        });
        this.callParent([config]);
    },
    getValue: function () {
        var cb = this.el.select("input").elements, i, res = [];
        for (i in cb) {
            if (cb.hasOwnProperty(i) && cb[i].checked) {
                res.push(cb[i].getAttribute("record-id"));
            }
        }
        return res;
    },
    setValue: function (values) {
        //not yet implemented
    }
});
</code>```

And this is how I add this field to a form:

```<code>Ext.create("Ext.form.Panel",{
    renderTo: Ext.getBody(),
    items:[{
        xtype: "textfield",
        name: "text"
    },{
       xtype: "simplelist",
       name: "list",
       store: {
            fields: ["id", "label", "checked"],
            data: [{"id": "1", "label": "One"},{"id": "2", "label": "Two"}]
        }
    },{
       xtype: "button",
       text: "Submit",
       handler: function () {
            var frm = this.up("form").getForm();
            console.log(frm.getFieldValues()); // it' ok
            //simplelist field is not submitted
            this.up("form").getForm().submit({
                url: "/"
            });
        }
   }]
});
</code>```

As you can see, when I submit the form I log to the console form field values. And what is interesting about that, is that I see my custom field among those field values. So, I have a field with isFormField set to true, this field is in the list returned by form getFields() method and this field is also among those values returned by form getFieldValues() method, but still this field is not submitted. What is wrong with that and how can I fix it?

答:
Your code uses basicForm.getFieldValues(), which calls basicForm.getValues() with some parameters, while the form while submitting uses the same method with different parameters. One of those parameters is useDataValues, which decides whether to use the getModelData or getSubmitData.

You are returning empty object in your getSubmitData method, which prevents it to correctly get the values.

All you need to change, for both methods to work in your current state, is this:

```<code>getSubmitData: function() {
    return this.getModelData();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a fiddle which demonstrates this strange behaviour. In a nutshell, I have a custom field which extends Ext.DataView. I need to extend dataview, because this field is supposed to have dynamic contents. This is how my field is defined:

Ext.define('Ext.ux.SimpleList', {
    extend: 'Ext.DataView',
    alias: 'widget.simplelist',
    requires: [
        'Ext.XTemplate'
    ],
    itemSelector: 'div.record',
    isFormField: true,
    getFieldIdentifier: function () {
        return this.name;
    },
    getModelData: function() {
        var me = this;
        var data = {};
        data[me.getFieldIdentifier()] = me.getValue();
        return data;
    },
    getSubmitData: function() { return {}; },
    submitValue: true,
    isValid: function () { return true; },
    isDirty: function () { return true; },
    validate: function () { return true; },
    isFileUpload: function() { return false; },
    constructor: function(config) {
        Ext.applyIf(config, {
            tpl: [
               '{% var name = this.owner.name; %}',
                '<tpl for=".">',
                    '
<input record-id="{id}" type="checkbox" name="{[name]}" /> {label}
',
                '</tpl>',
                {compiled: true}
            ]
        });
        this.callParent([config]);
    },
    getValue: function () {
        var cb = this.el.select("input").elements, i, res = [];
        for (i in cb) {
            if (cb.hasOwnProperty(i) && cb[i].checked) {
                res.push(cb[i].getAttribute("record-id"));
            }
        }
        return res;
    },
    setValue: function (values) {
        //not yet implemented
    }
});

And this is how I add this field to a form:

Ext.create("Ext.form.Panel",{
    renderTo: Ext.getBody(),
    items:[{
        xtype: "textfield",
        name: "text"
    },{
       xtype: "simplelist",
       name: "list",
       store: {
            fields: ["id", "label", "checked"],
            data: [{"id": "1", "label": "One"},{"id": "2", "label": "Two"}]
        }
    },{
       xtype: "button",
       text: "Submit",
       handler: function () {
            var frm = this.up("form").getForm();
            console.log(frm.getFieldValues()); // it' ok
            //simplelist field is not submitted
            this.up("form").getForm().submit({
                url: "/"
            });
        }
   }]
});

As you can see, when I submit the form I log to the console form field values. And what is interesting about that, is that I see my custom field among those field values. So, I have a field with isFormField set to true, this field is in the list returned by form getFields() method and this field is also among those values returned by form getFieldValues() method, but still this field is not submitted. What is wrong with that and how can I fix it?

Body:
Your code uses basicForm.getFieldValues(), which calls basicForm.getValues() with some parameters, while the form while submitting uses the same method with different parameters. One of those parameters is useDataValues, which decides whether to use the getModelData or getSubmitData.

You are returning empty object in your getSubmitData method, which prevents it to correctly get the values.

All you need to change, for both methods to work in your current state, is this:

getSubmitData: function() {
    return this.getModelData();
}


问:
How do I get Hibernate to ignore subclasses?
I have two classes C1 and C2. Each persists to its own table. Each has its own Hibernate XML description, mentioning its own table. There is no connection between these classes at all.

Except that C1 is a subclass of C2.

Obviously C1's XML copies a lot from C2's (with some stuff added), but it's a separate copy. Again: neither XML file mentions the other class or the other table.

But now, when I do a "From C2" query, Hibernate pulls in all of both tables.

Logically, this makes sense: a C1 is in fact a C2, so if I want all C2s I need the C1s as well, so we need to read all of C1's table. Hibernate must be using reflection to detect subclass C1 of C2.

Supposing this is expected behavior (though it wasn't expected by me!) how do I avoid it? Is there any way I can tell Hibernate that when I say "From C2" I really mean just C2 and not C1 to boot? Is there a clause I can add to the query that will restrict it to objects not of type C1, also avoiding the performance hit of querying C1's table in the first place?

答:
When you select from C2 it will also select C1 by default in hibernate. It's called Polymorphic queries. see Polymorphic queries , and Tutorial.

To fix/solve it you should add Polymorphism annotation with type PolymorphismType.EXPLICIT

@Polymorphism(type = PolymorphismType.EXPLICIT)

from https://docs.jboss.org/hibernate/orm/5.2/javadocs/

IMPLICIT -This entity is retrieved if any of its super entity are retrieved. The default,

EXPLICIT -This entity is retrieved only if explicitly asked.

ContentLicense: CC BY-SA 4.0


问:
Why does C# handle command line args inconsistently?
In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}
</code>```

Output:

```<code>C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa
</code>```

答:
Because it isn't C and thus isn't tied to it's conventions. Needing the exe name is pretty much an edge case; the small number of times I've needed this (compared to the other args) IMO justifies the decision to omit it.

This is additionally demanded in the spec (ECMA334v4, §10.1); (snipping to relevant parts):

10. Basic concepts

10.1 Application startup

...

This entry point method is always named Main, and shall have one of the
  following signatures:

```<code>static void Main() {…}
static void Main(string[] args) {…}
static int Main() {…}
static int Main(string[] args) {…}
</code>```

...

• Let args be the name of the parameter. If the length of the array designated by args is greater than
  zero, the array members args[0] through args[args.Length-1], inclusive, shall refer to strings,
  called application parameters, which are given implementation-defined values by the host environment
  prior to application startup. The intent is to supply to the application information determined prior to
  application startup from elsewhere in the hosted environment. If the host environment is not capable of
  supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the
  strings are received in lowercase. [Note: On systems supporting a command line, application, application parameters
  correspond to what are generally known as command-line arguments. end note]

ContentLicense: CC BY-SA 2.5

Body:
In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}

Output:

C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa

Body:
Because it isn't C and thus isn't tied to it's conventions. Needing the exe name is pretty much an edge case; the small number of times I've needed this (compared to the other args) IMO justifies the decision to omit it.

This is additionally demanded in the spec (ECMA334v4, §10.1); (snipping to relevant parts):

10. Basic concepts

10.1 Application startup

...

This entry point method is always named Main, and shall have one of the
  following signatures:

static void Main() {…}
static void Main(string[] args) {…}
static int Main() {…}
static int Main(string[] args) {…}

...

• Let args be the name of the parameter. If the length of the array designated by args is greater than
  zero, the array members args[0] through args[args.Length-1], inclusive, shall refer to strings,
  called application parameters, which are given implementation-defined values by the host environment
  prior to application startup. The intent is to supply to the application information determined prior to
  application startup from elsewhere in the hosted environment. If the host environment is not capable of
  supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the
  strings are received in lowercase. [Note: On systems supporting a command line, application, application parameters
  correspond to what are generally known as command-line arguments. end note]


问:
Angular shared modules and webpack
We are trying to figure out what is the correct approach for sharing modules in Angular with Webpack.

We have components that are re-used in various locations of our application. They are not used in all views of the application but most.

We created a sharedModule that imports and exports the components. This sharedModule is then imported in the needed areas of the application.

This is where we start to wonder. If module A imports sharedModule but only needs 2 of the 5 shared components, what happens to the 3 imported components not needed?

We understand that Webpack is supposed to do tree shaking and deadcode removal, but do we want to rely on Webpack to do this, or do we not use a sharedModule and import the components where we need them only?

答:
if you load shared module in app.module it will load all components and directives even if the page don't need them.

i suggest you to split the shared module, and keep there only the components and directives that you need across your application.

for example, if you have 3 components that you need in only 3 pages, create a module that holds only those 3 and export them from that module.

it will increase your performance dramatically if your shared module is pretty big right now.

split as much as you can to small modules.

Title: Angular shared modules and webpack


问:
Running Different Data sets in a Loop in R
I am attempting to run multiple years of a data set through a loop, 2009 to 2014 specifically, and renaming variables to reflect the year. For example, I am loading in consolidated from 2009, and trying to rename $AGE09 to $AGE. To clarify: I would like to be able to do this with 2010, 2011, and so on -- I want to be able to run consolidated.2009$AGE <- consolidated.2009$AGE09Xin a loop for all years, changing the 2009 to 2010, and 09 to 10, etc.

I am having a great deal of difficulty figuring out how to have R load a single year of data, rename the variable, and do to the other things I would like in a loop.

```<code>rx_files <- as.list(dir(pattern="* - rx.rda"))
consolidated_files <- as.list(dir(pattern="* - consolidated.rda"))
   for(i in c(2009:2014)){
     load(rx_files[[i]])
     load(consolidated_files[[i]])
     rx.[[i]] <- rx.[[i]]
     consolidated.[[i]] <- consolidated.[[i]]
     consolidated.2009$AGE <- consolidated.2009$AGE09X
     #I attempted to run the above code in the loop using the below code
     consolidated.[[i]]$AGE <- consolidated.[[i]]$AGE*X
   }
</code>```

I continuously run into errors where R does does not identifyrx.[[i]] or consolidated.[[i]] as a legitimate object. It is a difficult problem to explain, hopefully someone here may be able to offer assistance.

Thank you.

答:
First a few comments on your question:
when you call rx_files[[i]] with i == 2009 you're looking for the 2009th element of that list, I doubt this list starts at year 1, so you're probably not getting year 2009 by doing so.

When you do rx.[[i]] it seems you're trying to concatenate a name such as rx.2009. it doesn't work this way, [[ is used for lists rx. is not a list.

Please try this and let me know if it's what you want, I can then edit to explain.

```<code>library(data.table) # to use the function setnames, execute install.packages("data.table") if you don't have it
rx_files <- as.list(dir(pattern="* - rx.rda"))
consolidated_files <- as.list(dir(pattern="* - consolidated.rda"))
#supposing all these files start with a clean year (4 numeric characters) and that there's only one file per year and filetype
years_rx <- as.numeric(substr(rx_files,1,4)
years_cf <- as.numeric(substr(consolidated_files,1,4)
for(i in c(2009:2014)){
  load(rx_files[[which(years_rx == i)]]) # not used actually, why do you load it ?
  load(consolidated_files[[which(years_cf == i)]])
  eval(parse(text=sprintf("setnames(consolidated.%s,'AGE%sX','AGE')",i,substr(i,3,4))))
}
</code>```

Body:
I am attempting to run multiple years of a data set through a loop, 2009 to 2014 specifically, and renaming variables to reflect the year. For example, I am loading in consolidated from 2009, and trying to rename $AGE09 to $AGE. To clarify: I would like to be able to do this with 2010, 2011, and so on -- I want to be able to run consolidated.2009$AGE <- consolidated.2009$AGE09Xin a loop for all years, changing the 2009 to 2010, and 09 to 10, etc.

I am having a great deal of difficulty figuring out how to have R load a single year of data, rename the variable, and do to the other things I would like in a loop.

rx_files <- as.list(dir(pattern="* - rx.rda"))
consolidated_files <- as.list(dir(pattern="* - consolidated.rda"))
   for(i in c(2009:2014)){
     load(rx_files[[i]])
     load(consolidated_files[[i]])
     rx.[[i]] <- rx.[[i]]
     consolidated.[[i]] <- consolidated.[[i]]
     consolidated.2009$AGE <- consolidated.2009$AGE09X
     #I attempted to run the above code in the loop using the below code
     consolidated.[[i]]$AGE <- consolidated.[[i]]$AGE*X
   }

I continuously run into errors where R does does not identifyrx.[[i]] or consolidated.[[i]] as a legitimate object. It is a difficult problem to explain, hopefully someone here may be able to offer assistance.

Thank you.

Body:
First a few comments on your question:
when you call rx_files[[i]] with i == 2009 you're looking for the 2009th element of that list, I doubt this list starts at year 1, so you're probably not getting year 2009 by doing so.

When you do rx.[[i]] it seems you're trying to concatenate a name such as rx.2009. it doesn't work this way, [[ is used for lists rx. is not a list.

Please try this and let me know if it's what you want, I can then edit to explain.

library(data.table) # to use the function setnames, execute install.packages("data.table") if you don't have it
rx_files <- as.list(dir(pattern="* - rx.rda"))
consolidated_files <- as.list(dir(pattern="* - consolidated.rda"))
#supposing all these files start with a clean year (4 numeric characters) and that there's only one file per year and filetype
years_rx <- as.numeric(substr(rx_files,1,4)
years_cf <- as.numeric(substr(consolidated_files,1,4)
for(i in c(2009:2014)){
  load(rx_files[[which(years_rx == i)]]) # not used actually, why do you load it ?
  load(consolidated_files[[which(years_cf == i)]])
  eval(parse(text=sprintf("setnames(consolidated.%s,'AGE%sX','AGE')",i,substr(i,3,4))))
}


问:
Not able to fetch location using GPS
I'm trying to make a simple app to show my location coordinates. When I emulate the code ( nexus 6.0 , it works). However, when I use a real device via usb debugging (my htc 10), nothing appears when I press the button to show my coordinates. Any idea why? This is my code:

```<code>    //Location
    textView = (TextView) findViewById(R.id.textView);
    button2 = (Button) findViewById(R.id.button2);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
            System.out.println(location.getLongitude());
            System.out.println(location.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
    };

    configure_button();

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case 10:
            configure_button();
            break;
        default:
            break;
    }
}

void configure_button() {
    // first check for permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
                    , 10);
        }
        return;
    }
    // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    });
}
</code>```

I have this added in my manifest:

```<code>  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
</code>```

答:
You should declare the button2 click listener in oncreate as there is return statement in configure_button() method.

Just declare it right after declaring ids.

```<code>  textView = (TextView) findViewById(R.id.textView);
    button2 = (Button) findViewById(R.id.button2);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    });
   //rest of the code
</code>```

Title: Not able to fetch location using GPS

Body:
I'm trying to make a simple app to show my location coordinates. When I emulate the code ( nexus 6.0 , it works). However, when I use a real device via usb debugging (my htc 10), nothing appears when I press the button to show my coordinates. Any idea why? This is my code:

    //Location
    textView = (TextView) findViewById(R.id.textView);
    button2 = (Button) findViewById(R.id.button2);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
            System.out.println(location.getLongitude());
            System.out.println(location.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
    };

    configure_button();

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case 10:
            configure_button();
            break;
        default:
            break;
    }
}

void configure_button() {
    // first check for permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
                    , 10);
        }
        return;
    }
    // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    });
}

I have this added in my manifest:

  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />

Body:
You should declare the button2 click listener in oncreate as there is return statement in configure_button() method.

Just declare it right after declaring ids.

  textView = (TextView) findViewById(R.id.textView);
    button2 = (Button) findViewById(R.id.button2);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            locationManager.requestLocationUpdates("gps", 5000, 0, listener);
        }
    });
   //rest of the code


问:
How to populate a form in POST method
I have a form on a website, where I need to submit hundreds of records, manually. The form is in POST method.

I tried with the simple: http://.../form?incomingLead__email=MYNAME . but this didn't work.

How can I manipulate the Form submission action to include the values?

Trying with a single field as follow: this is the First Name attribute from the HTML:

```<code><input id="incomingLead__firstName" name="incomingLead__firstName"
class="text" style="" type="text" onkeypress="var _this=this;return
onEnterPressed(event, function()
{document.controller.setValue('/ctx/incomingLead/@firstName',
_this.value, 'incomingLead__firstName');return true;});"
onblur="document.controller.setValue('/ctx/incomingLead/@firstName',
this.value, 'incomingLead__firstName')">
</code>```

The form attribute is:

```<code><form method="post" name="page" class="main-navigation" id="page-form">
</code>```

Submit button:

```<code><button type="button" id="link-link330" onclick="return linklink330();">Submit</button>
</code>```

Validate JS function:

function toValidate() {
  var temp = document.getElementById('temp')
  if (!temp) return document.controller.submit('submit');

  document.controller.setValue("/ctx/vars/iCountProducts", temp.options.length);

  for (var i = 0; i < temp.options.length; i++)
    document.controller.setValue("/ctx/vars/products/product" + i, temp.options[i].value);

  return document.controller.submit('submit');
}```

I think of having an excel file, and concatenate the links I need, at least I can reduce the time form filling data, into 2 clicks: one in excel to open the webform, and than submit.

Is it possible with the data given?

答:
Form populating is only possible if the system you're trying to upload to provides such feature.
Even if it does, it is only one step away from truly manual data entry, so I recommend avoiding it.
Hundreds of records would take a long time.

If your data source is an excel file, you can automate the entire upload process.
Simply read the excel file, process the relevant rows one by one, send a POST request for each one.

Here is an example implementation in PHP:

//open xlsx file
$simple = new SimpleXLSX('power-mosfet.xlsx');

//get rows from the first worksheet
$rows = $simple->rows(1);

//process specific lines (starts from 0)
$fromLine = 2;
$toLine = 8;
for($i = $fromLine; $i<$toLine; $i++){
    //select relevant values
    $data = [
        'name'  => $rows[$i][0], //column 1
        'vdss'  => $rows[$i][1], //column 2
        'rdson' => $rows[$i][2], //column 3
    ];

    //send the data in a post request
    $ch = curl_init('http://example.com/form');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}
```

If PHP isn't in your wheelhouse, just use a programming language that is.
The concept is the same.

Title: How to populate a form in POST method

Body:
I have a form on a website, where I need to submit hundreds of records, manually. The form is in POST method.

I tried with the simple: http://.../form?incomingLead__email=MYNAME . but this didn't work.

How can I manipulate the Form submission action to include the values?

Trying with a single field as follow: this is the First Name attribute from the HTML:

<input id="incomingLead__firstName" name="incomingLead__firstName"
class="text" style="" type="text" onkeypress="var _this=this;return
onEnterPressed(event, function()
{document.controller.setValue('/ctx/incomingLead/@firstName',
_this.value, 'incomingLead__firstName');return true;});"
onblur="document.controller.setValue('/ctx/incomingLead/@firstName',
this.value, 'incomingLead__firstName')">

The form attribute is:

<form method="post" name="page" class="main-navigation" id="page-form">

Submit button:

<button type="button" id="link-link330" onclick="return linklink330();">Submit</button>

Validate JS function:

function toValidate() {
  var temp = document.getElementById('temp')
  if (!temp) return document.controller.submit('submit');

  document.controller.setValue("/ctx/vars/iCountProducts", temp.options.length);

  for (var i = 0; i < temp.options.length; i++)
    document.controller.setValue("/ctx/vars/products/product" + i, temp.options[i].value);

  return document.controller.submit('submit');
}

I think of having an excel file, and concatenate the links I need, at least I can reduce the time form filling data, into 2 clicks: one in excel to open the webform, and than submit.

Is it possible with the data given?

Body:
Form populating is only possible if the system you're trying to upload to provides such feature.
Even if it does, it is only one step away from truly manual data entry, so I recommend avoiding it.
Hundreds of records would take a long time.

If your data source is an excel file, you can automate the entire upload process.
Simply read the excel file, process the relevant rows one by one, send a POST request for each one.

Here is an example implementation in PHP:

//open xlsx file
$simple = new SimpleXLSX('power-mosfet.xlsx');

//get rows from the first worksheet
$rows = $simple->rows(1);

//process specific lines (starts from 0)
$fromLine = 2;
$toLine = 8;
for($i = $fromLine; $i<$toLine; $i++){
    //select relevant values
    $data = [
        'name'  => $rows[$i][0], //column 1
        'vdss'  => $rows[$i][1], //column 2
        'rdson' => $rows[$i][2], //column 3
    ];

    //send the data in a post request
    $ch = curl_init('http://example.com/form');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

If PHP isn't in your wheelhouse, just use a programming language that is.
The concept is the same.


问:
Code=-1005 "The network connection was lost." error
I get this from a request in my app, but i go to my url in safari and the url works fine.

this is my request

```<code>Alamofire.request("my url").responseJSON { response in

        print(response)

        if let JSON = response.result.value {
            print("JSON: \(JSON)")
        }
    }
</code>```

and this is the response

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x60800024dce0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=54, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey= my url, NSErrorFailingURLKey=my url, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=54, NSLocalizedDescription=The network connection was lost.}

I trying reset the simulator, reset my Mac, and all this tricks for bugs. but nothing solve my problem. any help?

答:
I had a very similar problem using the iPhone simulator to run an Alamofire call in a cafe that had a open wifi network that had a "Accept and Connect" screen (a la Starbucks) to connect. Public was very slow and overburdened with traffic, hence I think it may have been timing out.  I ran through tons of trouble shooting to no avail and finally I just moved to my wifi network at home and things work fine now with no changes.  </p>

<p>Not so sure that's the trouble you are having as it's pretty specific, but perhaps this can add to the scope of what you've been troubleshooting :) </p>

Body:
I get this from a request in my app, but i go to my url in safari and the url works fine.

this is my request

Alamofire.request("my url").responseJSON { response in

        print(response)

        if let JSON = response.result.value {
            print("JSON: \(JSON)")
        }
    }

and this is the response

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x60800024dce0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=54, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey= my url, NSErrorFailingURLKey=my url, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=54, NSLocalizedDescription=The network connection was lost.}

I trying reset the simulator, reset my Mac, and all this tricks for bugs. but nothing solve my problem. any help?

Body:
I had a very similar problem using the iPhone simulator to run an Alamofire call in a cafe that had a open wifi network that had a "Accept and Connect" screen (a la Starbucks) to connect. Public was very slow and overburdened with traffic, hence I think it may have been timing out.  I ran through tons of trouble shooting to no avail and finally I just moved to my wifi network at home and things work fine now with no changes.

Not so sure that's the trouble you are having as it's pretty specific, but perhaps this can add to the scope of what you've been troubleshooting :)


问:
ExtJS Carousel Implementation
I'm trying to make a carousel for displaying images, I got most of the functionality from a solution someone in sencha forums came up with. I made a few adjustments to the code and got it working at first glance.

Here's the original code on sencha forums...

http://www.sencha.com/forum/showthread.php?256456-an-Ext-JS-4-carousel-component&p=938789#post938789

This didn't work on ExtJS 4 so I made a few modifications for it to work and also to make it look better (to my eyes). Here's how it looks

I do have a problem or two though...

First off I can't figure out how to add a text over the images I'm displaying, I managed to add that  line of text in the center but I also want to add a date to the images and that should display on top of each image container. I think it's pretty basic, but I can't figure out how... I don't have a full understanding of HTML, so that's not helping.

Secondly, and most important, I'm getting some weird behaviour when I close and reopen the window containing this carousel. I've seen this kind of behaviour before when using the same ID in multiple instances of a view in ExtJS, but I have changed all IDs to generate a new one whenever a new carousel window opens and still experience the same problem.

Here's what happens when I close and reopen the window...

And that happens with every window I open after closing the carousel

And last but not least!! I can't get the keydown event to work on this window, I have no clue why. I've tried setting the listener on the carousel container instead of the window but still get no firing whatsoever.

This is the code I'm using to create the carousel window...

```<code>var win = Ext.create('Ext.view.CarouselWindow');
win.show();
Ext.createWidget('carousel',{
    xPos: win.getSize().width/2,
    yPos: win.getSize().height/4,
    FPS: 70,
    reflHeight: 56,
    height:'100%',
    width:'100%',
    reflGap:2,
    bringToFront:true,
    store:store,
    images:store,
    altBox:'imageNameLabel',
    autoRotate: 'no',
    renderTo: 'carousel-div',
    listeners:{
        keydown:function(){
            console.log('asdasd')
        }
    }
});
</code>```

This is the initComponent of the carousel component, which is rendered in the window.

```<code>initComponent: function(config) {
this.callParent(arguments);

    this.container = this.renderTo ? Ext.get(this.renderTo) : this.up('container');
if (this.xRadius === 0){
    this.xRadius = (this.container.getWidth()/2.3);
}
if (this.yRadius === 0){
    this.yRadius = (this.container.getHeight()/6);
}
this.xCentre = this.xPos;
this.yCentre = this.yPos;

// Start with the first item at the front.
this.rotation = this.destRotation = Math.PI/2;
this.timeDelay = 1000/this.FPS;

// Turn on the infoBox
if(this.altBox !== '')
//      Ext.get(this.altBox).applyStyles({display: 'block'});
if(this.titleBox !== '')
    Ext.get(this.titleBox).applyStyles({display: 'block'});
//
// Turn on relative position for container to allow absolutely positioned elements
// within it to work.
this.container.applyStyles({ position:'relative', overflow:'hidden'});

// Setup the store.
this.initStore();

this.setUpContainerListener();

this.innerWrapper = this.container.createChild({
    tag: 'div',
    style: 'position:absolute;width:100%;height:100%;'
});

this.checkImagesLoaded();
},
</code>```

And here's the Image component that the carousel uses...

```<code> /**
 * @author Aymen ABDALLAH <aymen.abdallah@gmail.com>
 * @docauthor Aymen ABDALLAH
 */
Ext.define('Ext.component.Image', {

config: {
    orgWidth: 400,
    orgHeight: 400,
    reflHeight: 0,
    reflOpacity: 0,
    itemIndex: 0,
    image: null,
    reflection: null,
    container: null,
    alt: '',
    title: '',
    imageSrc: '',
    imageOK: false
},

//  id: '',

constructor: function(config){
    this.initConfig(config);
    this.imageOK = true;
    this.image = new Ext.Element(document.createElement('img'));
    this.image.set({
//          id: this.id,
        src: this.imageSrc,
                    class : 'carousel-image',
        alt: this.alt,
        title: this.title
    });

    this.image.setStyle({position : 'absolute'});   // This seems to reset image width     to 0 on webkit!
},

setUpReflection: function(){
    if (this.reflHeight > 0)
    {
        this.reflection = Ext.create('Ext.component.Reflection', {
            imageHeight: this.orgHeight,
            imageWidth: this.orgWidth,
            image: this.image,
            parent: this.container,
            reflHeight: this.reflHeight,
            reflOpacity: this.reflOpacity
        });
    }
},

generateId: function(){
//      return Ext.data.UuidGenerator.create().generate();
},

getImage: function(){
    return this.image;
}

});
</code>```

I didn't want to flood this with code so I restricted to what I think might be useful, there might be some missing though, in that case just tell me and I'll update the post with the portion of the code you need.

EDIT

Here's a link to sencha fiddle showing the carousel and the error. To see the second error open the carousel by clicking the button, close it with ESC and then try to open it once again. You'll notice it either doesn't show or it shows like the screenshot I posted.

https://fiddle.sencha.com/#fiddle/2iu

EDIT 2

Just found out the problem comes from the images, if I comment these lines:

```<code>this.image = new Ext.Element(document.createElement('img'));
this.image.set({
    id: this.id,
    src: this.imageSrc,
                class : 'carousel-image',
    alt: this.alt,
    title: this.title
});
</code>```

the second error I listed disappears. Of course this is not a solution as the carousel won't display any image this way, but I thought this could be a useful piece of data for anyone interested in helping.

答:
For those who visit this page (I know it's an old post),

The issue isn't actually with the second view, the first view causes a layout error.

The Ext.component.Image class is missing a render function, to fix this add

```<code>render: function () {
    return;
}
</code>```

to the class.

Not sure how to fix the other issue entirely, but you could change the image component to be a form/panel and have text, or use the caption tags.

Title: ExtJS Carousel Implementation

Body:
I'm trying to make a carousel for displaying images, I got most of the functionality from a solution someone in sencha forums came up with. I made a few adjustments to the code and got it working at first glance.

Here's the original code on sencha forums...

http://www.sencha.com/forum/showthread.php?256456-an-Ext-JS-4-carousel-component&p=938789#post938789

This didn't work on ExtJS 4 so I made a few modifications for it to work and also to make it look better (to my eyes). Here's how it looks

I do have a problem or two though...

First off I can't figure out how to add a text over the images I'm displaying, I managed to add that  line of text in the center but I also want to add a date to the images and that should display on top of each image container. I think it's pretty basic, but I can't figure out how... I don't have a full understanding of HTML, so that's not helping.

Secondly, and most important, I'm getting some weird behaviour when I close and reopen the window containing this carousel. I've seen this kind of behaviour before when using the same ID in multiple instances of a view in ExtJS, but I have changed all IDs to generate a new one whenever a new carousel window opens and still experience the same problem.

Here's what happens when I close and reopen the window...

And that happens with every window I open after closing the carousel

And last but not least!! I can't get the keydown event to work on this window, I have no clue why. I've tried setting the listener on the carousel container instead of the window but still get no firing whatsoever.

This is the code I'm using to create the carousel window...

var win = Ext.create('Ext.view.CarouselWindow');
win.show();
Ext.createWidget('carousel',{
    xPos: win.getSize().width/2,
    yPos: win.getSize().height/4,
    FPS: 70,
    reflHeight: 56,
    height:'100%',
    width:'100%',
    reflGap:2,
    bringToFront:true,
    store:store,
    images:store,
    altBox:'imageNameLabel',
    autoRotate: 'no',
    renderTo: 'carousel-div',
    listeners:{
        keydown:function(){
            console.log('asdasd')
        }
    }
});

This is the initComponent of the carousel component, which is rendered in the window.

initComponent: function(config) {
this.callParent(arguments);

    this.container = this.renderTo ? Ext.get(this.renderTo) : this.up('container');
if (this.xRadius === 0){
    this.xRadius = (this.container.getWidth()/2.3);
}
if (this.yRadius === 0){
    this.yRadius = (this.container.getHeight()/6);
}
this.xCentre = this.xPos;
this.yCentre = this.yPos;

// Start with the first item at the front.
this.rotation = this.destRotation = Math.PI/2;
this.timeDelay = 1000/this.FPS;

// Turn on the infoBox
if(this.altBox !== '')
//      Ext.get(this.altBox).applyStyles({display: 'block'});
if(this.titleBox !== '')
    Ext.get(this.titleBox).applyStyles({display: 'block'});
//
// Turn on relative position for container to allow absolutely positioned elements
// within it to work.
this.container.applyStyles({ position:'relative', overflow:'hidden'});

// Setup the store.
this.initStore();

this.setUpContainerListener();

this.innerWrapper = this.container.createChild({
    tag: 'div',
    style: 'position:absolute;width:100%;height:100%;'
});

this.checkImagesLoaded();
},

And here's the Image component that the carousel uses...

 /**
 * @author Aymen ABDALLAH <aymen.abdallah@gmail.com>
 * @docauthor Aymen ABDALLAH
 */
Ext.define('Ext.component.Image', {

config: {
    orgWidth: 400,
    orgHeight: 400,
    reflHeight: 0,
    reflOpacity: 0,
    itemIndex: 0,
    image: null,
    reflection: null,
    container: null,
    alt: '',
    title: '',
    imageSrc: '',
    imageOK: false
},

//  id: '',

constructor: function(config){
    this.initConfig(config);
    this.imageOK = true;
    this.image = new Ext.Element(document.createElement('img'));
    this.image.set({
//          id: this.id,
        src: this.imageSrc,
                    class : 'carousel-image',
        alt: this.alt,
        title: this.title
    });

    this.image.setStyle({position : 'absolute'});   // This seems to reset image width     to 0 on webkit!
},

setUpReflection: function(){
    if (this.reflHeight > 0)
    {
        this.reflection = Ext.create('Ext.component.Reflection', {
            imageHeight: this.orgHeight,
            imageWidth: this.orgWidth,
            image: this.image,
            parent: this.container,
            reflHeight: this.reflHeight,
            reflOpacity: this.reflOpacity
        });
    }
},

generateId: function(){
//      return Ext.data.UuidGenerator.create().generate();
},

getImage: function(){
    return this.image;
}

});

I didn't want to flood this with code so I restricted to what I think might be useful, there might be some missing though, in that case just tell me and I'll update the post with the portion of the code you need.

EDIT

Here's a link to sencha fiddle showing the carousel and the error. To see the second error open the carousel by clicking the button, close it with ESC and then try to open it once again. You'll notice it either doesn't show or it shows like the screenshot I posted.

https://fiddle.sencha.com/#fiddle/2iu

EDIT 2

Just found out the problem comes from the images, if I comment these lines:

this.image = new Ext.Element(document.createElement('img'));
this.image.set({
    id: this.id,
    src: this.imageSrc,
                class : 'carousel-image',
    alt: this.alt,
    title: this.title
});

the second error I listed disappears. Of course this is not a solution as the carousel won't display any image this way, but I thought this could be a useful piece of data for anyone interested in helping.

Body:
For those who visit this page (I know it's an old post),

The issue isn't actually with the second view, the first view causes a layout error.

The Ext.component.Image class is missing a render function, to fix this add

render: function () {
    return;
}

to the class.

Not sure how to fix the other issue entirely, but you could change the image component to be a form/panel and have text, or use the caption tags.


问:
Open a SQL file as a Console in DataGrip
I have a sql file saved off that I want to open and get results back from a database I am connected to in DataGrip. When I open the file, it opens it up as a file scope, and not as a console scope, and I cannot run the sql against the database. I have to open up a new database console, copy my SQL into the database console, and run it from there. Make any changes I want to the SQL, and save it back to the file. I just want to open the file up as a console.

I have to be doing this wrong. What am I missing? How can I open a SQL file from disk in DataGrip and execute the query in a console-like fashion?

Example: I have a SQL file: "customer.sql" that contains "Select top 10 * from customer". When I open up "customer.sql", it opens up as a file in DataGrip with no execution or associated database relationship. I want to run the "customer.sql" contents of "select top 10 * from customer" against one of my database connections. Make my changes to the query "select top 11 * from customer" and save it back to "customer.sql"

答:
There is a new option in DataGrip 2017.2 : Attach console.

You can find via Ctrl+Shift+A or by opening the context menu for a file. After performing this action, this file can be run against the console. Switching consoles will be useful if you want to run the same script in several data sources.


问:
Create an array of arrays with Linq
I've the following XML :

```<code><datarow>
  <datacol><![CDATA[Value1]]></datacol>
  <datacol><![CDATA[Value2]]></datacol>
  <datacol><![CDATA[Value3]]></datacol>
</datarow>
<datarow>
  <datacol><![CDATA[Value5]]></datacol>
  <datacol><![CDATA[Value6]]></datacol>
  <datacol><![CDATA[Value7]]></datacol>
</datarow>
// ...
</code>```

How can I create an bi-dimensional array using linq?

I'll avoid doing :

```<code>foreach("datarow") {
    foreach ("datacol") { ... }
}
</code>```

Thanks !

[EDIT] Final array should be like this:

array[,] = {{ "Value1", "Value2", "Value3"} , { "Value4", "Value5", "Value6"}}

答:
LINQ and multi-dimensional arrays do not mix well.

You can use a traditional foreach loop, but you have to calculate the size of the multi-dimensional array first:

```<code>string[,] result = new string
[
    doc.Elements("datarow").Count(),
    doc.Elements("datarow").Max(d => d.Elements("datacol").Count())
];

int x = 0;
foreach (var datarow in doc.Elements("datarow"))
{
    int y = 0;
    foreach (var datacol in datarow.Elements("datacol"))
    {
        result[x, y] = (string)datacol;
        y++;
    }
    x++;
}
</code>```

But it's really much simpler to create a jagged array (i.e. a one-dimensional array of one-dimensional arrays; LINQ and one-dimensional arrays mix well!):

```<code>string[][] result = doc.Elements("datarow")
                       .Select(d => d.Elements("datacol")
                                     .Select(c => (string)c)
                                     .ToArray())
                       .ToArray();
</code>```

Title: Create an array of arrays with Linq

Body:
I've the following XML :

<datarow>
  <datacol><![CDATA[Value1]]></datacol>
  <datacol><![CDATA[Value2]]></datacol>
  <datacol><![CDATA[Value3]]></datacol>
</datarow>
<datarow>
  <datacol><![CDATA[Value5]]></datacol>
  <datacol><![CDATA[Value6]]></datacol>
  <datacol><![CDATA[Value7]]></datacol>
</datarow>
// ...

How can I create an bi-dimensional array using linq?

I'll avoid doing :

foreach("datarow") {
    foreach ("datacol") { ... }
}

Thanks !

[EDIT] Final array should be like this:

array[,] = {{ "Value1", "Value2", "Value3"} , { "Value4", "Value5", "Value6"}}

Body:
LINQ and multi-dimensional arrays do not mix well.

You can use a traditional foreach loop, but you have to calculate the size of the multi-dimensional array first:

string[,] result = new string
[
    doc.Elements("datarow").Count(),
    doc.Elements("datarow").Max(d => d.Elements("datacol").Count())
];

int x = 0;
foreach (var datarow in doc.Elements("datarow"))
{
    int y = 0;
    foreach (var datacol in datarow.Elements("datacol"))
    {
        result[x, y] = (string)datacol;
        y++;
    }
    x++;
}

But it's really much simpler to create a jagged array (i.e. a one-dimensional array of one-dimensional arrays; LINQ and one-dimensional arrays mix well!):

string[][] result = doc.Elements("datarow")
                       .Select(d => d.Elements("datacol")
                                     .Select(c => (string)c)
                                     .ToArray())
                       .ToArray();


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

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

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

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

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

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

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

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

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

答:
Your option 2 is the correct one. If Chart needs to calculate something based on a piece of data then that piece of data is a prop of Chart, not a prop of Line.

You can make the whole Chart more flexible by making config an array instead of object. It's easier to loop through and you could have any number of lines.

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

<LineChart config={config} />
</code>```

Title: Accessing child props from the parent

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

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

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

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

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

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

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

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

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

Body:
Your option 2 is the correct one. If Chart needs to calculate something based on a piece of data then that piece of data is a prop of Chart, not a prop of Line.

You can make the whole Chart more flexible by making config an array instead of object. It's easier to loop through and you could have any number of lines.

const config = [
    { data: [...] },
    { data: [...], interpolate: 'linear' },
];

<LineChart config={config} />


问:
How to insert a formula into a function so that it can be used to calculate values for consecutive rows
I'm aware that the title may be a little confusing but please allow me to clarify.
I have a column with values

```<code>> df
    Direction
    139
    118
    180
    142
    185
    224
    137
    245
</code>```

I have the following formula

```<code>((pt1 - pt2 + 180)%%360 - 180)
</code>```

I would like to insert this formula to calculate the difference between each consecutive instance
Example:

```<code>((139 - 118 + 180)%%360 - 180) = 21
((118 - 180 + 180)%%360 - 180) = -62
</code>```

Some of the things I've tried

Creating the function

```<code>angle <- function(turn1, turn2) {
  coursediff <- ((turn1 - turn2 + 180)
                 %%360 - 180)
  coursediff
}
angle(118, 180)
## [1] -62
</code>```

Trying to use it for each consecutive row for column Direction, creating a new column named Diff

```<code>df$Diff <- with(df,
     ave(Direction, ID,  FUN=function(angle) c(NA, diff(angle))))
</code>```

Or

```<code>df %>% group_by(ID) %>%
  mutate(gap=angle(c(NA,diff(Direction)), 1))
</code>```

Or

```<code>index <- function(angle) c(0, diff(angle))
DT <- data.table(df)
DT[, Diff := index(Direction), by = "ID"]
</code>```

Or even

```<code>transform(df,
          Diff=unlist(tapply(Direction, ID,
                                function(angle) c(0, diff(Direction)))))
</code>```

All the above attempts are giving me the same answers as if I were to simply take the difference per row, like so

```<code>df$Diff <- c(NA, diff(df$Direction))
</code>```

This is what I get now

```<code>> df
    Direction  Diff  ID
    139        NA    1
    118       -21    1
    180        62    1
    142       -38    1
    185        NA    2
    224        39    2
    137       -87    2
    245        108   2
</code>```

I hope someone can help me out, much appreciated!

答:
You can use ave and diff in base R like this.

```<code>dat$diff <- ave(dat$Direction, dat$ID,
                FUN=function(x) c(NA, (rev((diff(rev(x))) + 180) %% 360) -180))
</code>```

Here, we calculate in the desired order by feeding diff the reversed vector using rev and return the vector in the desired order using rev on the output of diff. Note that we need to use c(NA, ..) to add a missing value for each ID.

which returns

```<code>dat
  Direction Diff ID diff
1       139   NA  1   NA
2       118  -21  1   21
3       180   62  1  -62
4       142  -38  1   38
5       185   NA  2   NA
6       224   39  2  -39
7       137  -87  2   87
8       245  108  2 -108
</code>```

data

```<code>dat <-
structure(list(Direction = c(139L, 118L, 180L, 142L, 185L, 224L,
137L, 245L), Diff = c(NA, -21L, 62L, -38L, NA, 39L, -87L, 108L
), ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L)), .Names = c("Direction",
"Diff", "ID"), row.names = c(NA, -8L), class = "data.frame")
</code>```

Body:
I'm aware that the title may be a little confusing but please allow me to clarify.
I have a column with values

> df
    Direction
    139
    118
    180
    142
    185
    224
    137
    245

I have the following formula

((pt1 - pt2 + 180)%%360 - 180)

I would like to insert this formula to calculate the difference between each consecutive instance
Example:

((139 - 118 + 180)%%360 - 180) = 21
((118 - 180 + 180)%%360 - 180) = -62

Some of the things I've tried

Creating the function

angle <- function(turn1, turn2) {
  coursediff <- ((turn1 - turn2 + 180)
                 %%360 - 180)
  coursediff
}
angle(118, 180)
## [1] -62

Trying to use it for each consecutive row for column Direction, creating a new column named Diff

df$Diff <- with(df,
     ave(Direction, ID,  FUN=function(angle) c(NA, diff(angle))))

Or

df %>% group_by(ID) %>%
  mutate(gap=angle(c(NA,diff(Direction)), 1))

Or

index <- function(angle) c(0, diff(angle))
DT <- data.table(df)
DT[, Diff := index(Direction), by = "ID"]

Or even

transform(df,
          Diff=unlist(tapply(Direction, ID,
                                function(angle) c(0, diff(Direction)))))

All the above attempts are giving me the same answers as if I were to simply take the difference per row, like so

df$Diff <- c(NA, diff(df$Direction))

This is what I get now

> df
    Direction  Diff  ID
    139        NA    1
    118       -21    1
    180        62    1
    142       -38    1
    185        NA    2
    224        39    2
    137       -87    2
    245        108   2

I hope someone can help me out, much appreciated!

Body:
You can use ave and diff in base R like this.

dat$diff <- ave(dat$Direction, dat$ID,
                FUN=function(x) c(NA, (rev((diff(rev(x))) + 180) %% 360) -180))

Here, we calculate in the desired order by feeding diff the reversed vector using rev and return the vector in the desired order using rev on the output of diff. Note that we need to use c(NA, ..) to add a missing value for each ID.

which returns

dat
  Direction Diff ID diff
1       139   NA  1   NA
2       118  -21  1   21
3       180   62  1  -62
4       142  -38  1   38
5       185   NA  2   NA
6       224   39  2  -39
7       137  -87  2   87
8       245  108  2 -108

data

dat <-
structure(list(Direction = c(139L, 118L, 180L, 142L, 185L, 224L,
137L, 245L), Diff = c(NA, -21L, 62L, -38L, NA, 39L, -87L, 108L
), ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L)), .Names = c("Direction",
"Diff", "ID"), row.names = c(NA, -8L), class = "data.frame")


问:
Length specified in network packet

Length specified in network packet payload did not match number of
  bytes read; the connection has been closed. Please contact the vendor
  of the client library. [CLIENT: 218.76.28.18]

Hello mates, I got same error from different [CLIENT: IP addresses]. I have a cloud server and MSSQL Server 2014 intalled on it. But don't have any database at sql server. When i check logs i saw almost 500 error in last 7 days. All errors as above, only with different client IPs. Anyone know why i got this errors? Thanks!

答: If your application is connecting from a server with static IP, you can create a allowed policy for the IP. Rest all connection will be refused automatically. </p>

Title: Length specified in network packet


问:
Prepend dynamic elements with pure javascript
I have the following HTML

```<code><div id="form">
        <div id="test">
            <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>
        </div>
    </div>
</code>```

and I am trying to build an form based on JSON data

```<code>for (i in response[key].request_fields) {
var values = ( () => {
    var out = "";
    for(var e in response[key].request_fields[i].values){
        out += "<li class='item_check'>" +
                    "<input type='checkbox' id='" + response[key].request_fields[i].values[e] + "'>" +
                    "<label for='" + response[key].request_fields[i].values[e] + "'>"
                        + response[key].request_fields[i].values[e] +
                    "</label>" +
                "</li>";
    }
    return out;
})();

document.getElementById("test").innerHTML += "<div class='form_section'>" +
                                                "<label>" + response[key].request_fields[i].label + "</label>" +
                                                "<ul>" + values + "</ul>" +
                                             "</div>";
}
</code>```

It's working properly, except that I need this result to be printed before my textarea.
How can I prepend it ?

答:
You can get the parentNode and use insertBefore function to insert new element

var parent = document.getElementById("test");
var txa = parent.querySelector('textarea');
var div = document.createElement('div');
div.class = 'form_section';
div.innerHTML = "My label text" +
                "

val1

val2

";
parent.insertBefore(div, txa);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="form">
  <div id="test">
    <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>
  </div>
</div></code>```

Body:
I have the following HTML

            <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>

and I am trying to build an form based on JSON data

for (i in response[key].request_fields) {
var values = ( () => {
    var out = "";
    for(var e in response[key].request_fields[i].values){
        out += "
" +
                    "<input type='checkbox' id='" + response[key].request_fields[i].values[e] + "'>" +
                    ""
                        + response[key].request_fields[i].values[e] +
                    "" +
                "
";
    }
    return out;
})();

document.getElementById("test").innerHTML += "
" +
                                                "" + response[key].request_fields[i].label + "" +
                                                "
" + values + "
" +
                                             "
";
}

It's working properly, except that I need this result to be printed before my textarea.
How can I prepend it ?

Body:
You can get the parentNode and use insertBefore function to insert new element

var parent = document.getElementById("test");
var txa = parent.querySelector('textarea');
var div = document.createElement('div');
div.class = 'form_section';
div.innerHTML = "<label>My label text</label>" +
                "<ul><li>val1</li><li>val2</li></ul>";
parent.insertBefore(div, txa);

<div id="form">
  <div id="test">
    <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>
  </div>
</div>


问:
Conditional Panel based on number of user selected inputs
I am trying to get a different number of fields to populate based on the number of entries selected in a selectInput with multiple = TRUE.  So if 1 entry from the "numfields" input is selected, the first conditionalPanel appears, and so on. What I have now shows the inputs I want to be conditional without any user input.

```<code>  a <- c("A","B","C")

  Choices <- as.character(a)

  ui <- fluidPage(
    fluidRow(
      selectInput(inputId = "numfields", label = "Select Entries", choices = Choices, multiple = TRUE, selectize = TRUE),
      conditionalPanel(
          condition = "count(input$numfields) >= 1",
          textInput(inputId = "field1", label = "First One", value = "")
        ),
      conditionalPanel(
        condition = "count(input$numfields) >= 2",
        textInput(inputId = "field2", label = "Second One", value = "")
      ),
      conditionalPanel(
        condition = "count(input$numfields) >= 3",
        textInput(inputId = "field3", label = "Third One", value = "")
      )
      )
    )

  server <- function(input, output, session)
  {}

  shinyApp(ui=ui, server=server)
</code>```

Also, on a related note, Shiny automatically defaults to have no entries selected for selectInput fields where multiple = TRUE.  Is there a way to have it select the first entry like it does when multiple = FALSE?

Any help is appreciated, thank you.

答:
You can set a default selection in a selectInput() using the selected = argument:

```<code>selectInput(inputId = "numfields",
            label = "Select Entries",
            choices = Choices,
            multiple = TRUE,
            selectize = TRUE,
            selected = 'A')
</code>```

The condition = argument in the conditionalPanel() takes a literal that's interpreted as JS rather than R.

To check for the input 'count' you should use input.numfields.length:

```<code>conditionalPanel(
  condition = "input.numfields.length >= 1",
  textInput(inputId = "field1", label = "First One", value = "")
)
</code>```

Below the complete ui:

```<code>ui <- fluidPage(
  fluidRow(
    selectInput(inputId = "numfields",
                label = "Select Entries",
                choices = Choices,
                multiple = TRUE,
                selectize = TRUE,
                selected = 'A'),
    conditionalPanel(
      condition = "input.numfields.length >= 1",
      textInput(inputId = "field1", label = "First One", value = "")
    ),
    conditionalPanel(
      condition = "input.numfields.length >= 2",
      textInput(inputId = "field2", label = "Second One", value = "")
    ),
    conditionalPanel(
      condition = "input.numfields.length >= 3",
      textInput(inputId = "field3", label = "Third One", value = "")
    )
  )
)
</code>```

Body:
I am trying to get a different number of fields to populate based on the number of entries selected in a selectInput with multiple = TRUE.  So if 1 entry from the "numfields" input is selected, the first conditionalPanel appears, and so on. What I have now shows the inputs I want to be conditional without any user input.

  a <- c("A","B","C")

  Choices <- as.character(a)

  ui <- fluidPage(
    fluidRow(
      selectInput(inputId = "numfields", label = "Select Entries", choices = Choices, multiple = TRUE, selectize = TRUE),
      conditionalPanel(
          condition = "count(input$numfields) >= 1",
          textInput(inputId = "field1", label = "First One", value = "")
        ),
      conditionalPanel(
        condition = "count(input$numfields) >= 2",
        textInput(inputId = "field2", label = "Second One", value = "")
      ),
      conditionalPanel(
        condition = "count(input$numfields) >= 3",
        textInput(inputId = "field3", label = "Third One", value = "")
      )
      )
    )

  server <- function(input, output, session)
  {}

  shinyApp(ui=ui, server=server)

Also, on a related note, Shiny automatically defaults to have no entries selected for selectInput fields where multiple = TRUE.  Is there a way to have it select the first entry like it does when multiple = FALSE?

Any help is appreciated, thank you.

Body:
You can set a default selection in a selectInput() using the selected = argument:

selectInput(inputId = "numfields",
            label = "Select Entries",
            choices = Choices,
            multiple = TRUE,
            selectize = TRUE,
            selected = 'A')

The condition = argument in the conditionalPanel() takes a literal that's interpreted as JS rather than R.

To check for the input 'count' you should use input.numfields.length:

conditionalPanel(
  condition = "input.numfields.length >= 1",
  textInput(inputId = "field1", label = "First One", value = "")
)

Below the complete ui:

ui <- fluidPage(
  fluidRow(
    selectInput(inputId = "numfields",
                label = "Select Entries",
                choices = Choices,
                multiple = TRUE,
                selectize = TRUE,
                selected = 'A'),
    conditionalPanel(
      condition = "input.numfields.length >= 1",
      textInput(inputId = "field1", label = "First One", value = "")
    ),
    conditionalPanel(
      condition = "input.numfields.length >= 2",
      textInput(inputId = "field2", label = "Second One", value = "")
    ),
    conditionalPanel(
      condition = "input.numfields.length >= 3",
      textInput(inputId = "field3", label = "Third One", value = "")
    )
  )
)


问:
Error when converting text to CSV
I'm a research assistant at Columbia University and I've been using Open Secret's bulk data on Campaign Lobbying. I've recently ran into an issue with the data in that the .txt files that they provide will not properly convert into .csv files because of formatting errors. I've solved most of the errors caused by extra commas and brackets, however, one error continues to be problematic. In one data-set (containing well over 3-million lines of data), is supposed to contain issue specific information in a single column in a single row. However, the text file is arranged in such a way that some of this text has been seperated by a line break and thus results in some information that is supposed to be present in a single column, has been split between different rows. Attached below is an example of this as presented in EmEditor. I'm wondering if there is a program or code that i can run this through in order to quickly fix these errors? It could be as simple as a line of code that looks at the first character of each line and if it isn't a numerical value, or is a letter or symbol, simply backspaces once in order to place the information on the previous line. I have very little coding experience and any help would be greatly appreciated.

答:
You could use regular expressions.

In the find and replace window, check the 'Use Regular Expressions' box.

Use the below expressions in the find and the replace text box boxes.

Find: \n([^\d])

Replace: \1

This searches all occurences of newline character followed by a non-digit character and replaces it with only the non-digit character, thereby removing the newline character.

Title: Error when converting text to CSV


问:
Chromecast receiver selection doesn't open
I would like to add basic Chromecast functionality to my web page. I am stuck at the second step. I can initialise the Chromecast but when the user clicks on the Chromecast button I can't open the receiver selector. I got this error every occasion:

```<code>{
  code: "session_error"
  description: null
  details: null
}
</code>```

I tried to use the same code as I found here. This code works for me but when I integrate it to my page it just doesn't.
Is there a possibility that Chrome can't detect that a user interaction happened and that is why it doesn't work?
Any other idea how can I solve this?

edit:

I tried multiple chrome cast devices with Google default receiver app ID and it just doesn't work. Those devices work with the linked source page.

Can it cause trouble if the click event is handled in a different JS file? What if it is loaded from a different domain? I can't find any hints in the documentation.

答:
According to Ali Nadaff in this SO post:

Check these; hopefully they get things sorted out:

Make sure you have registered your chromecast device on the developer console. Double check the serial number since sometimes it is hard to read it.

During the chromecast setup, there was a box stating something like "Send the serial number ..", make sure that is checked

Wait 1/2 hour or so and reboot your chromecast

Check whether you can access http://:9222 from a chrome browser on the same wifi network; if you can, then your device is ready for development
As for the area on the image that you have pointed to, that is more for informational purposes at this point

Body:
I would like to add basic Chromecast functionality to my web page. I am stuck at the second step. I can initialise the Chromecast but when the user clicks on the Chromecast button I can't open the receiver selector. I got this error every occasion:

{
  code: "session_error"
  description: null
  details: null
}

I tried to use the same code as I found here. This code works for me but when I integrate it to my page it just doesn't.
Is there a possibility that Chrome can't detect that a user interaction happened and that is why it doesn't work?
Any other idea how can I solve this?

edit:

I tried multiple chrome cast devices with Google default receiver app ID and it just doesn't work. Those devices work with the linked source page.

Can it cause trouble if the click event is handled in a different JS file? What if it is loaded from a different domain? I can't find any hints in the documentation.


问:
get the first 10 google results using googleapi
I need to get the first 10 google results

for example:

```<code>... query = urllib.urlencode({'q' : 'example'})
...
... url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
... % (query)
... search_results = urllib.urlopen(url)
... json = simplejson.loads(search_results.read())
... results = json['responseData']['results']
</code>```

this will give me the results of the first page, but I`d like to get more google results, do anyone know how to do that?

答:
See docs http://code.google.com/apis/websearch/docs/reference.html#_intro_fonje

You’re looking for the start parameter.

There’s no parameter to get more results in one response, but you can iterate via the start parameter.

Body:
I need to get the first 10 google results

for example:

... query = urllib.urlencode({'q' : 'example'})
...
... url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
... % (query)
... search_results = urllib.urlopen(url)
... json = simplejson.loads(search_results.read())
... results = json['responseData']['results']

this will give me the results of the first page, but I`d like to get more google results, do anyone know how to do that?


问:
Switch ViewControllers of different heights in Container View
I have a requirement where I have to load different UI based on selected option in a ViewController. Here is the representation

Option1 and Option2 are radio buttons and user is allowed to select only one option at a time. Based on the selection, below area has to be updated with different textfields.

So, I created a view below the options which acts as a container. Created two ViewControllers with textFields for Option1 and Option2 which will be added a child view controllers to the containerView. Below is the hierarchy of the mainViewController

--> View

------> ScrollView

------------> ContentView

------------------> Label

------------------> Label

------------------> Option1

------------------> Option2

------------------> ContainerView

Based on selected option, I load respective viewController as childViewController to the containerView.

The point to note is, number of fields for option1 and option2 are different and height of the containerView should be adjusted based on the number of subviews in selected option, so that the complete screen is scrollable.

I couldn't able to resize option1 and option2 viewControllers based on the number of fields(subviews) in it.

How can I adjust the height of childViewControllers based on number of fields and set containerViews height?

Or what would be the better approach to achieve such design?

答:
How can I adjust the height of childViewControllers based on number of fields

This depends on the content in the child view controllers.

set containerViews height?

Once you've added the child view to the container. Call containerView.sizeToFit() and it will adjust its size to fit the child view.

Note: Make sure you don't have constraints on the container view restricting its height or it won't be able to adjust.

https://developer.apple.com/documentation/uikit/uiview/1622630-sizetofit


问:
Can you config a widget after it has been created dynamically?
So I have been looking for the answer to this but can't find any examples.

I want to know if you can create several buttons or labels or whatever widget in tkinter with all the same variable name and then be able to target that widget directly after its created.

Here is an example of some code that will create 5 buttons with the same variable name and if you press the button it will print the text on said button.

```<code>import tkinter as tk

btn_names = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"]

class MyButton(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.createButtons()

    def createButtons(self):

        row_count = 0

        for n in range(5):
            someButton = tk.Button(self.parent, text=btn_names[n], command= lambda t=btn_names[n]: self.getText(t))
            someButton.grid(row = row_count, column = 0)
            row_count += 1

    def getText(self, text):
        print(text)

if __name__ == "__main__":
    root = tk.Tk()
    myApp = MyButton(root)

    root.mainloop()
</code>```

Now what I can't figure out is if it is possible to also make changes to said button. Like I now want to change the buttons background and foreground colors but I have no way of targeting the button I want to edit.

I can't just do this:

someButton.config(background = "black", foreground = "white")

as all the buttons are named someButton.

So is it possible to be able to edit a widget created in this manor after it has been created?

答:
I'm not sure this is the best way to do it, but it is possible.

Instead of passing a command to your button when you originally create it, add a  line where you configure the command to your lambda function and pass someButton as an argument. Then in your callback function, ensure you configure the button passed to change its background color.

```<code>import tkinter as tk

btn_names = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th
Button"]

class MyButton(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.createButtons()

    def createButtons(self):

        row_count = 0

        for n in range(5):
            someButton = tk.Button(self.parent, text=btn_names[n])
            someButton.configure(command=lambda t=btn_names[n], btn = someButton: self.getText(t, btn))
            someButton.grid(row = row_count, column = 0)
            row_count += 1

    def getText(self, text, btn):
        print(text)
        btn.configure(background = 'black')

if __name__ == "__main__":
    root = tk.Tk()
    myApp = MyButton(root)

    root.mainloop()
</code>```

Body:
So I have been looking for the answer to this but can't find any examples.

I want to know if you can create several buttons or labels or whatever widget in tkinter with all the same variable name and then be able to target that widget directly after its created.

Here is an example of some code that will create 5 buttons with the same variable name and if you press the button it will print the text on said button.

import tkinter as tk

btn_names = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"]

class MyButton(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.createButtons()

    def createButtons(self):

        row_count = 0

        for n in range(5):
            someButton = tk.Button(self.parent, text=btn_names[n], command= lambda t=btn_names[n]: self.getText(t))
            someButton.grid(row = row_count, column = 0)
            row_count += 1

    def getText(self, text):
        print(text)

if __name__ == "__main__":
    root = tk.Tk()
    myApp = MyButton(root)

    root.mainloop()

Now what I can't figure out is if it is possible to also make changes to said button. Like I now want to change the buttons background and foreground colors but I have no way of targeting the button I want to edit.

I can't just do this:

someButton.config(background = "black", foreground = "white")

as all the buttons are named someButton.

So is it possible to be able to edit a widget created in this manor after it has been created?

Body:
I'm not sure this is the best way to do it, but it is possible.

Instead of passing a command to your button when you originally create it, add a  line where you configure the command to your lambda function and pass someButton as an argument. Then in your callback function, ensure you configure the button passed to change its background color.

import tkinter as tk

btn_names = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th
Button"]

class MyButton(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.createButtons()

    def createButtons(self):

        row_count = 0

        for n in range(5):
            someButton = tk.Button(self.parent, text=btn_names[n])
            someButton.configure(command=lambda t=btn_names[n], btn = someButton: self.getText(t, btn))
            someButton.grid(row = row_count, column = 0)
            row_count += 1

    def getText(self, text, btn):
        print(text)
        btn.configure(background = 'black')

if __name__ == "__main__":
    root = tk.Tk()
    myApp = MyButton(root)

    root.mainloop()


问:
How to create a component with nested Selectors in Angular2
Iam new to angular2, I am trying to build a component with nested selectors. how can I build a component like that. if my question is not clear please see below i need to build a component that can be used like this. Is there any method or approach i can follow. Please help</p>

```<code> <parent [width]='100'>
        <child [title]='hi'></child>
        <child [title]='hello'></child>
 </parent>
</code>```

答:
You can mention the child selectors in the template of parent and import the child components in to Parent</p>

```<code>import { Component,Input } from "@angular/core";
import {childSelector} from 'pathname for childselector file'
@Component({
    selector: "my-app",
    template: `
<childselector1></childselector1>
<childselector2></childselector2>
`
})
export class AppComponent {

}
</code>```

Body:
Iam new to angular2, I am trying to build a component with nested selectors. how can I build a component like that. if my question is not clear please see below i need to build a component that can be used like this. Is there any method or approach i can follow. Please help

 <parent [width]='100'>
        <child [title]='hi'></child>
        <child [title]='hello'></child>
 </parent>

Body:
You can mention the child selectors in the template of parent and import the child components in to Parent

import { Component,Input } from "@angular/core";
import {childSelector} from 'pathname for childselector file'
@Component({
    selector: "my-app",
    template: `
<childselector1></childselector1>
<childselector2></childselector2>
`
})
export class AppComponent {

}


问:
Change "Billing Details" text to "Shipping Details" on WooCommerce checkout page
I currently have a bit of code in my child theme's functions.php file which is supposed to change "Billing Details" to say "Shipping Details" on my WooCommerce checkout page.

However, when I updated to WooCommerce 3.0, the code snippet stopped working. Below is the code I was using.

```<code>function wc_billing_field_strings( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Billing Details' :
            $translated_text = __( 'Shipping Details', 'woocommerce' );
            break;
    }
    return $translated_text;
}

add_filter( 'gettext', 'wc_billing_field_strings', 20, 3 );
</code>```

I would really like a code snippet that works with WooCommerce 3.0+.

答:
```<code>function wc_billing_field_strings( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Billing details' :
            $translated_text = __( 'Billing Info', 'woocommerce' );
            break;
    }
    return $translated_text;
}
add_filter( 'gettext', 'wc_billing_field_strings', 20, 3 );
</code>```

Tested OK with WooCommerce 3.0.6

Body:
I currently have a bit of code in my child theme's functions.php file which is supposed to change "Billing Details" to say "Shipping Details" on my WooCommerce checkout page.

However, when I updated to WooCommerce 3.0, the code snippet stopped working. Below is the code I was using.

function wc_billing_field_strings( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Billing Details' :
            $translated_text = __( 'Shipping Details', 'woocommerce' );
            break;
    }
    return $translated_text;
}

add_filter( 'gettext', 'wc_billing_field_strings', 20, 3 );

I would really like a code snippet that works with WooCommerce 3.0+.

Body:
function wc_billing_field_strings( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Billing details' :
            $translated_text = __( 'Billing Info', 'woocommerce' );
            break;
    }
    return $translated_text;
}
add_filter( 'gettext', 'wc_billing_field_strings', 20, 3 );

Tested OK with WooCommerce 3.0.6


问:
Firebase Auth using phone number returns an internal error
I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.

So I wrote this:

```<code>PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
  if error != nil {
    print("Verification code not sent \(error!)")
  } else {
    print ("Successful.")
  }
</code>```

And I get:

```<code>Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
    code = 500;
    message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
</code>```

Any idea? Should I file a bug against firebase?

I am using iOS SDK 4.0.0 (latest zip I could find.)

UPDATE:

I disabled method swizzling by adding FirebaseAppDelegateProxyEnabled to info.plist and set it to NO

```<code>func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Pass device token to auth.
    Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
</code>```

答:
Double check that the app bundle ID in Xcode matches the bundle ID in Firebase exactly. And by exactly, make sure their case matches - Xcode likes to use mixed case by default for the app name part of the bundle ID.

If you end up changing the bundle ID in Xcode, make sure to manually delete the provisioning profile for the app before generating a new one in Xcode, or it will repeatedly fail (Apple apparently ignores case on profile names).

Body:
I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.

So I wrote this:

PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
  if error != nil {
    print("Verification code not sent \(error!)")
  } else {
    print ("Successful.")
  }

And I get:

Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
    code = 500;
    message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}

Any idea? Should I file a bug against firebase?

I am using iOS SDK 4.0.0 (latest zip I could find.)

UPDATE:

I disabled method swizzling by adding FirebaseAppDelegateProxyEnabled to info.plist and set it to NO

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Pass device token to auth.
    Auth.auth().setAPNSToken(deviceToken, type: .prod)
}


问:
Change node size gephi 0.9.1
I have looked everywhere but I don't seem to able to get the answer for the latest version of Gephi (0.9.1).
All  I want to do is change the node size based on its in-degree for all the nodes on the graph. This used to be something I could do with the ranking tool but since this has been merged into the 'Appearance' tab I can't figure out how to do it.</p>

答:
Weird but works: In Overview, in the Appearance tab, click on the mini icon for color (not for size). Diagonally down to the left, you should see a little icon of some colored blocks. If you mouse over them, the pop-up says,"Switch to ranking". Click that. Then above toe the right, click on the icon for size instead of color this time. Now when you select to modify the node appearance by attribute, it should let you do it by your custom column.

See https://github.com/gephi/gephi/issues/1479, where rbsam wrote in 2016, "On Appearence/Attributes by color you can set the attribute to Partitioning to Ranking on the botton left of the window. If the attribute is set to Partitioning it will not appear on Size attribute. If it is set to Ranking it will appear on Size attribute."

Title: Change node size gephi 0.9.1


问:
Web Development, Domain and Site Hosting
I'm not 100% sure if I'm on the correct section but i'll transfer the post once I know where it's supposed to be but I am looking for advice regarding web development, setting up a domain and hosting it.

I'm currently working on a personal project using Cloud9. Which is an online development environment where I can develop and host. The reason why I chose this is because it has MySQL usability as I retrieve and store data on the project I am working on.

I am now at the point where I want to get a domain and host a site to transfer my project over to a live website with my own domain which also has SQL/MySQL usability.

Any advice or where would be the best place to look up on methods of pursuing this?

Edit: I develop using PHP and JavaScript with MySQL

答: Why not setup your own VPS (Virtual Private Server)? There are many providers..</p>


问:
using legacy project in Eclipse
I wish to use "C" legacy project in the Eclipse. In the project it require "autoreconf
-vi" followed by "./configure" before make to start. My problem is I am not able to do "autoreconf -vi" and "./configure" from the eclipse.

Thanks
Arpit

答:
You should try enabling the autotools features from the Eclipse Linuxtools Plugin: if you have CDT, the Linuxtools plugin should already be available in your eclipse environment. However, you need to enable features from it:

use the following menu: Help / Install New Software

in the search box type "linux", find the plugin and

check the box (+ OK)

finally select at least Linux "Tools/Autotools support for CDT" (also call graph, gcov, gprof, ltt could be interesting but not needed for your problem)

Note: if you do not already have the plugin available, detailed instructions with an update URL are available in the Linux Tools Project/PluginInstallHelp wiki page.

Once you have this plugin installed, you can:

Convert an existing project by: File / New / Convert to a C/C++ Autotools Project / Next / Next / Finish

Edit the project properties as needed: Project / Properties / Autotools / Configure Settings, e.g., to specify configure flags in the advanced tab, platform specifiers for cross compilation etc.

Hope it'll help.

Cheers,

Christophe.

= They did not know it was impossible, so they did it! --Mark Twain =

Title: using legacy project in Eclipse