问:
Is it a bad practice seeking a data in list by index multiple times?
I have like below code,

```<code>override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val view = holder.view
    view.apply {
        name.text = list[position].name
        age.text = list[position].age
        address1.text = list[position].address1
        address2.text = list[position].address2
        zip_code.text = list[position].zip_code
    }
}
</code>```

it's seeking the data multiple times to get each property, like name, age, address1..

And I'm wondered is it better assign the data to a variable and use it? like this,

```<code>val view = holder.view
val data = list[position]
view.apply {
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}
</code>```

Assigning to new variable is cost more?

Please advise me which is better and why?

答:
```<code>val view = holder.view
view.apply { list[position].also { data ->
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}}
</code>```

Body:
I have like below code,

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val view = holder.view
    view.apply {
        name.text = list[position].name
        age.text = list[position].age
        address1.text = list[position].address1
        address2.text = list[position].address2
        zip_code.text = list[position].zip_code
    }
}

it's seeking the data multiple times to get each property, like name, age, address1..

And I'm wondered is it better assign the data to a variable and use it? like this,

val view = holder.view
val data = list[position]
view.apply {
    name.text = data.name
    age.text = data.age
    address1.text = data.address1
    address2.text = data.address2
    zip_code.text = data.zip_code
}

Assigning to new variable is cost more?

Please advise me which is better and why?


来源: stackexchange

问:
Python scikit learn pca.explained_variance_ratio_ cutoff
When choosing the number of principal components (k), we choose k to be the smallest value so that for example, 99% of variance, is retained.

However, in the Python Scikit learn, I am not 100% sure pca.explained_variance_ratio_ = 0.99 is equal to "99% of variance is retained"?  Could anyone enlighten?  Thanks.

The Python Scikit learn PCA manual is here

http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA

答:
Although this question is older than 2 years i want to provide an update on this.
I wanted to do the same and it looks like sklearn now provides this feature out of the box.

As stated in the docs

if 0 < n_components < 1 and svd_solver == ‘full’, select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components

So the code required is now

```<code>my_model = PCA(n_components=0.99, svd_solver='full')
my_model.fit_transform(my_matrix)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Although this question is older than 2 years i want to provide an update on this.
I wanted to do the same and it looks like sklearn now provides this feature out of the box.

As stated in the docs

if 0 < n_components < 1 and svd_solver == ‘full’, select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components

So the code required is now

my_model = PCA(n_components=0.99, svd_solver='full')
my_model.fit_transform(my_matrix)

ContentLicense: CC BY-SA 3.0


问:
Getting tracking code and session settings by API
How can I get the tracking code and session settings, using the Google Analytics Management API?

I am reading this API documentation: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties/list

I was able to get a list of all properties that I have on Google Analytics, but the session settings and tracking code is not returned by this API call.
By session settings I mean the following:
https://support.google.com/analytics/answer/2795871?hl=en

Is there any API endpoint that I can use to get these settings?

答:
Indeed, the session & campaign timeout settings are not present in the webproperty resource (I'm not sure what you mean by tracking code). All you get is this:

```<code>accountId
childLink
childLink.href
childLink.type
created
defaultProfileId
id
industryVertical
internalWebPropertyId
kind
level
name
parentLink
parentLink.href
parentLink.type
permissions
permissions.effective[]
profileCount
selfLink
starred
updated
websiteUrl
</code>```

So unfortunately at this stage you just can't retrieve that info with any of the APIs.

That being said, they released a v4 for the reporting API with more features, so they might also release a v4 for the management API with more features in it.

Body:
Indeed, the session & campaign timeout settings are not present in the webproperty resource (I'm not sure what you mean by tracking code). All you get is this:

accountId
childLink
childLink.href
childLink.type
created
defaultProfileId
id
industryVertical
internalWebPropertyId
kind
level
name
parentLink
parentLink.href
parentLink.type
permissions
permissions.effective[]
profileCount
selfLink
starred
updated
websiteUrl

So unfortunately at this stage you just can't retrieve that info with any of the APIs.

That being said, they released a v4 for the reporting API with more features, so they might also release a v4 for the management API with more features in it.


问:
How to update variable every full hour without refresh page by user?
Controller:

```<code>$number = rand(1, 100);
</code>```

View:

```<code><div id="lucky">
   Your lucky number: <?php echo $number ?>.
</div>
</code>```

How can I update the value for $number every hour without manually refreshing the page? I can use setInterval from JavaScript/jQuery, but I would like do it exactly at full hour (0:00, 1:00, 2:00 etc...). What is the best way to do this? I can use PHP, CRON, JS and JS frameworks...

答:
Try  finding  out what time it is now, figure out how long it is until the next full hour, then wait that long:

```<code>function doSomething() {
    var d = new Date(),
        h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + 1, 0, 0, 0),
        e = h - d;
    if (e > 100) { // some arbitrary time period
        window.setTimeout(doSomething, e);
    }
    // your code(May be an ajax call to show lucky num)
}
</code>```

The check for e < 100 is just to make sure you don't do setTimeout on something like 5 ms and get it a crazy loop.

Body:
Controller:

$number = rand(1, 100);

View:

   Your lucky number: <?php echo $number ?>.

How can I update the value for $number every hour without manually refreshing the page? I can use setInterval from JavaScript/jQuery, but I would like do it exactly at full hour (0:00, 1:00, 2:00 etc...). What is the best way to do this? I can use PHP, CRON, JS and JS frameworks...

Body:
Try  finding  out what time it is now, figure out how long it is until the next full hour, then wait that long:

function doSomething() {
    var d = new Date(),
        h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + 1, 0, 0, 0),
        e = h - d;
    if (e > 100) { // some arbitrary time period
        window.setTimeout(doSomething, e);
    }
    // your code(May be an ajax call to show lucky num)
}

The check for e < 100 is just to make sure you don't do setTimeout on something like 5 ms and get it a crazy loop.


问:
maskind dataframe elements in pandas
I have a square matrix as a dataframe and I want to project all the values above the diagonal into a series. My idea was to mask all elements below the diagonal and then dump the dataframe into a series but it dumps the NaN values as well. Here is the example:

```<code>users=[1,2,3,4,5]
cols=range(1,6)

matrix=pd.DataFrame(np.random.randn(len(users),len(cols)), index=users,columns=cols)
mask = np.ones(matrix.shape,dtype='bool')
mask[np.triu_indices(len(matrix))] = False
series=matrix.mask(mask).values.ravel()
</code>```

Into the series I get all the upper tiangle values as well as all the NaN values corresponding to the lower triangle. Obviously I understood something wrong: I had understood that by masking some elements in a dataframe masked elements would not be used. Anybody know how I could do that?

Title: maskind dataframe elements in pandas

Body:
I have a square matrix as a dataframe and I want to project all the values above the diagonal into a series. My idea was to mask all elements below the diagonal and then dump the dataframe into a series but it dumps the NaN values as well. Here is the example:

users=[1,2,3,4,5]
cols=range(1,6)

matrix=pd.DataFrame(np.random.randn(len(users),len(cols)), index=users,columns=cols)
mask = np.ones(matrix.shape,dtype='bool')
mask[np.triu_indices(len(matrix))] = False
series=matrix.mask(mask).values.ravel()

Into the series I get all the upper tiangle values as well as all the NaN values corresponding to the lower triangle. Obviously I understood something wrong: I had understood that by masking some elements in a dataframe masked elements would not be used. Anybody know how I could do that?

Body:
Option 1

Use pd.DataFrame.stack as it will dump np.nan for you.

matrix.mask(mask).stack().values

array([ 0.6022148 , -0.19275783, -0.54066832,  1.95690678,  0.23993172,
        0.27107843,  2.29409865, -0.70446894, -0.93153835, -0.26430007,
       -0.29887114,  1.83132652,  1.54226746,  0.50651577, -0.51001179])

Option 2

Use np.where to identify the locations within the mask

i, j = np.where(~mask)
matrix.values[i, j]

array([ 0.6022148 , -0.19275783, -0.54066832,  1.95690678,  0.23993172,
        0.27107843,  2.29409865, -0.70446894, -0.93153835, -0.26430007,
       -0.29887114,  1.83132652,  1.54226746,  0.50651577, -0.51001179])

Option 2B

Skip the mask and stick with the upper triangle.

i, j = np.triu_indices(len(matrix))
matrix.values[i, j]

array([ 0.6022148 , -0.19275783, -0.54066832,  1.95690678,  0.23993172,
        0.27107843,  2.29409865, -0.70446894, -0.93153835, -0.26430007,
       -0.29887114,  1.83132652,  1.54226746,  0.50651577, -0.51001179])


问:
How to extract array of names from array of email ids
Given this input array:

```<code>var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];
</code>```

I to output an array that looks like this:

```<code>["ramu","ravi","karthik"];
</code>```

I have tried this, but it doesn't produce the correct result:

```<code>names = data.map(s => s.split('@'));
</code>```

答:
Use array map:

var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];
var newData = data.map(s => s.split('@')[0]);
console.log(newData);```

Body:
Given this input array:

var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];

I to output an array that looks like this:

["ramu","ravi","karthik"];

I have tried this, but it doesn't produce the correct result:

names = data.map(s => s.split('@'));


问:
Choco Solver math expression generation
I want to use Choco solver to write a Java program that generates math problems that satisfy a number of constraints.
The problems have to take the following form:

```<code>x @ y ∆ z = r
</code>```

Where:

x, y & z are positive integers, not necessarily different from one another, with one of them being 2 digits long and the other two 1 digit long

@ & ∆ are operators +, - or * (note that both can also stand for the same operator)

r is a positive 1-digit integer

I want to generate these math problems "on demand" (as in, one at the time) and they need to be randomised (i.e. there no should be no pattern or fixed order across the generated problems).

It has been well over 10 years since I have done constraint (satisfaction) programming, but I believe C(S)P (preferably by means of Choco), is a suitable tool to apply here.
Is this correct and can someone help me get started?

答:
You certainly can model such a problem with a CP solver like choco.
You need to have a look at the documentation and tutorials for more details, but you will need :

to create a Model,

to declare integer variables (IntVar) for x, y and z,

to link them with constraints, I would suggest to use IntVar expression API to ease declaration. Such API allows to build arithmetical, logical and relational expressions like.

Here is a simple example:

```<code>Model model = new Model();
IntVar x = model.intVar(0, 9);
IntVar y = model.intVar(0, 9);
IntVar z = model.intVar(0, 9);
int r = 10;
x.add(y).sub(z).eq(r).post();
model.getSolver().showSolutions(
    () -> String.format("%d + %d - %d = %d",
            x.getValue(), y.getValue(), z.getValue(), r));
model.getSolver().findAllSolutions();
</code>```

The way add,sub and mul are combined depends on your random selector.
Then, you can try to encode the expression with a table constraints or let the solver choose.

Title: Choco Solver math expression generation

Body:
I want to use Choco solver to write a Java program that generates math problems that satisfy a number of constraints.
The problems have to take the following form:

x @ y ∆ z = r

Where:

x, y & z are positive integers, not necessarily different from one another, with one of them being 2 digits long and the other two 1 digit long

@ & ∆ are operators +, - or * (note that both can also stand for the same operator)

r is a positive 1-digit integer

I want to generate these math problems "on demand" (as in, one at the time) and they need to be randomised (i.e. there no should be no pattern or fixed order across the generated problems).

It has been well over 10 years since I have done constraint (satisfaction) programming, but I believe C(S)P (preferably by means of Choco), is a suitable tool to apply here.
Is this correct and can someone help me get started?

Body:
You certainly can model such a problem with a CP solver like choco.
You need to have a look at the documentation and tutorials for more details, but you will need :

to create a Model,

to declare integer variables (IntVar) for x, y and z,

to link them with constraints, I would suggest to use IntVar expression API to ease declaration. Such API allows to build arithmetical, logical and relational expressions like.

Here is a simple example:

Model model = new Model();
IntVar x = model.intVar(0, 9);
IntVar y = model.intVar(0, 9);
IntVar z = model.intVar(0, 9);
int r = 10;
x.add(y).sub(z).eq(r).post();
model.getSolver().showSolutions(
    () -> String.format("%d + %d - %d = %d",
            x.getValue(), y.getValue(), z.getValue(), r));
model.getSolver().findAllSolutions();

The way add,sub and mul are combined depends on your random selector.
Then, you can try to encode the expression with a table constraints or let the solver choose.


问:
Looping through an array to get index of item - swift
I am trying to loop through an array of names to get the index of a certain string. I then want to set the index of my UIPicker to the said string.

I have the following code however this causes the app to crash due:

```<code>let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
        scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)
</code>```

When debugging the index is getting a value of index 6176573120 which of course isn't in the range of my UIPicker so causes the crash.

Any ideas on why this may be happening?

Using the suggested answer throws the following error:

```<code>unrecognized selector sent to instance 0x101134af0'
</code>```

There is definitely a match in assetArray[0] with the name that is being passed through.

Doing a bit more investigation trying to run the following line of code alone gives the same error:

```<code>scroll_owners.selectRow(0, inComponent: 0, animated: true)
</code>```

Does this mean I'm missing a delegate method?

Asset Array and Name Array:

```<code>var assetArray : [Asset] = []

var nameArray = [String]()
</code>```

EDIT:

```<code>    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
}

    self.scroll_owners.delegate = self
    self.scroll_owners.dataSource = self
</code>```

I've tried to get this working another way - I know this is an ugly way of doing it I'm just trying to see why the accepted swift way isn't working:

```<code>            var i : Int = 0
        while (nameArray[i] != name)
        {
            print(nameArray[i])
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: 0, animated: true)
</code>```

This section of code crashes and the while loops is never entered due to the index being out of bounds - does this mean the issue could be with nameArray?

答:
i think the problem is that .index doesn't return an IndexPath.
But selectRow needs an indexPath as parameter.

.index
.selectRow

Body:
I am trying to loop through an array of names to get the index of a certain string. I then want to set the index of my UIPicker to the said string.

I have the following code however this causes the app to crash due:

let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
        scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)

When debugging the index is getting a value of index 6176573120 which of course isn't in the range of my UIPicker so causes the crash.

Any ideas on why this may be happening?

Using the suggested answer throws the following error:

unrecognized selector sent to instance 0x101134af0'

There is definitely a match in assetArray[0] with the name that is being passed through.

Doing a bit more investigation trying to run the following line of code alone gives the same error:

scroll_owners.selectRow(0, inComponent: 0, animated: true)

Does this mean I'm missing a delegate method?

Asset Array and Name Array:

var assetArray : [Asset] = []

var nameArray = [String]()

EDIT:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
}

    self.scroll_owners.delegate = self
    self.scroll_owners.dataSource = self

I've tried to get this working another way - I know this is an ugly way of doing it I'm just trying to see why the accepted swift way isn't working:

            var i : Int = 0
        while (nameArray[i] != name)
        {
            print(nameArray[i])
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: 0, animated: true)

This section of code crashes and the while loops is never entered due to the index being out of bounds - does this mean the issue could be with nameArray?


问:
Updating data in multiple places without reloading the page
How to update data in multiple places without reloading the page in Vue.js?

This is my example.

When I add a new application, a new reminder is created. How to use this data in different places on the page?

Important: all elements are in different components.

答:
Use Vuex or a global event bus depending on the complexity of your application.

If your application is starting to become more enriched with Vue components that need to communicate beyond simple child/parent and parent/child communications, then Vuex should be a good fit.

I am not going to go into depth about the technicalities because that information can be found in the documentation. Good luck.


问:
SAPUI5 Binding Context for array hierarchy
I have a questions object which contains an answers array

```<code>var oModel = new JSONModel({
    questions: [{
        order: 1,
        title: "",
        answers: [{
            sequence: 1,
            label: "Yes",
        }, {
            sequence: 3,
            label: "N/A",
        }]
    }]
});
</code>```

And the context set as follows

```<code>this.getView().setModel(oModel, "viewmodel");
var oContext = oModel.createBindingContext("/questions/0/");
this.getView().setBindingContext(oContext, "viewmodel");
</code>```

In my view, I can bind questions fine

```<code><Input value="{viewmodel>title}"/>
</code>```

However, updating the answers binding updates ALL the answer arrays in EVERY questions context!, e.g. below i'm binding to my current context (questions/0/) but update the label will update the answers for all questions....

```<code><f:Form id="formCustomRadio" editable="true" visible="true" formContainers="{viewmodel>answers}">
    <f:layout>
        <f:ResponsiveGridLayout/>
    </f:layout>
    <f:formContainers>
        <f:FormContainer title="Answer {viewmodel>sequence}">
            <f:formElements>
                    <f:FormElement label=" {i18n>radioLabel}">
                        <f:fields>
                            <Input value="{viewmodel>label}"/>
                        </f:fields>
</code>```

Any ideas?

答:
The issue was related to the the array push when creating new questions...

```<code>questionData.questions.push({
    order: questionData.questions.length + 1,
    title: questionData.questions[questionData.questions.length - 1].title,
    answers: questionData.questions[questionData.questions.length - 1].answers
});
</code>```

As answers is an array of objects , you can't simply push to it as this creates duplicate references. That's the reason answers where duplicated after each update. Solution was to push each answer separately in a for loop.

```<code>    for (var i = 0; i < answerArray.length; i++) {

            questionData.questions[newIndex].answers.push({
                sequence: answerArray[i].sequence,
                label: answerArray[i].label,
                points: answerArray[i].points,
                imageFlag: answerArray[i].imageFlag,
                image: answerArray[i].image,
                mandatoryComments: answerArray[i].mandatoryComments,
                additionalQuestion: answerArray[i].additionalQuestion
            });
        }
</code>```

Body:
I have a questions object which contains an answers array

var oModel = new JSONModel({
    questions: [{
        order: 1,
        title: "",
        answers: [{
            sequence: 1,
            label: "Yes",
        }, {
            sequence: 3,
            label: "N/A",
        }]
    }]
});

And the context set as follows

this.getView().setModel(oModel, "viewmodel");
var oContext = oModel.createBindingContext("/questions/0/");
this.getView().setBindingContext(oContext, "viewmodel");

In my view, I can bind questions fine

<Input value="{viewmodel>title}"/>

However, updating the answers binding updates ALL the answer arrays in EVERY questions context!, e.g. below i'm binding to my current context (questions/0/) but update the label will update the answers for all questions....

<f:Form id="formCustomRadio" editable="true" visible="true" formContainers="{viewmodel>answers}">
    <f:layout>
        <f:ResponsiveGridLayout/>
    </f:layout>
    <f:formContainers>
        <f:FormContainer title="Answer {viewmodel>sequence}">
            <f:formElements>
                    <f:FormElement label=" {i18n>radioLabel}">
                        <f:fields>
                            <Input value="{viewmodel>label}"/>
                        </f:fields>

Any ideas?

Body:
The issue was related to the the array push when creating new questions...

questionData.questions.push({
    order: questionData.questions.length + 1,
    title: questionData.questions[questionData.questions.length - 1].title,
    answers: questionData.questions[questionData.questions.length - 1].answers
});

As answers is an array of objects , you can't simply push to it as this creates duplicate references. That's the reason answers where duplicated after each update. Solution was to push each answer separately in a for loop.

    for (var i = 0; i < answerArray.length; i++) {

            questionData.questions[newIndex].answers.push({
                sequence: answerArray[i].sequence,
                label: answerArray[i].label,
                points: answerArray[i].points,
                imageFlag: answerArray[i].imageFlag,
                image: answerArray[i].image,
                mandatoryComments: answerArray[i].mandatoryComments,
                additionalQuestion: answerArray[i].additionalQuestion
            });
        }


问:
iot core error when use ProcessLauncher.RunToCompletionAsync execute process
I want to run another program from my program
my code is

```<code>    var options = new ProcessLauncherOptions();
            var standardOutput = new InMemoryRandomAccessStream();
            var standardError = new InMemoryRandomAccessStream();
            options.StandardOutput = standardOutput;
            options.StandardError = standardError;
             await ProcessLauncher.RunToCompletionAsync(@"C:\Data\Users\DefaultAccount\AppData\Local\DevelopmentFiles\930e206e-dd28-4760-84b2-f3a1f74801feVS.Debug_ARM.Mostafa.Bagheri\Jamsaz.InjectionWeights.exe", "", options);
</code>```

when i run in vs 2017 get following error

This application can only run in the context of an app container. (Exception from HRESULT: 0x8007109B)
  Error Image

答:
You may need including the executable application with the AppX package. For detailed steps, you can reference this tutorial:

External process launcher.

Body:
I want to run another program from my program
my code is

    var options = new ProcessLauncherOptions();
            var standardOutput = new InMemoryRandomAccessStream();
            var standardError = new InMemoryRandomAccessStream();
            options.StandardOutput = standardOutput;
            options.StandardError = standardError;
             await ProcessLauncher.RunToCompletionAsync(@"C:\Data\Users\DefaultAccount\AppData\Local\DevelopmentFiles\930e206e-dd28-4760-84b2-f3a1f74801feVS.Debug_ARM.Mostafa.Bagheri\Jamsaz.InjectionWeights.exe", "", options);

when i run in vs 2017 get following error

This application can only run in the context of an app container. (Exception from HRESULT: 0x8007109B)
  Error Image


问:
Behat Scenario Outline Float values
Consider the following scenario for API testing

```<code>Given I am using the API Service
When  I send the <request> as <method> to <endpoint> endpoint with <key> having value <value>
Then  The response status code is 200

Examples:
  | request    | method | endpoint       | key            | value          |
  | "All Keys" | "POST" | "endpointName" | "numericField" | 15             |
  | "All Keys" | "POST" | "endpointName" | "numericField" | 15.12345       |
</code>```

The above example creates a request with the specified parameters.

My problem is that while the integer (15) value is passed to the function accordingly, the float (15.12345) is converted into a string ("15.12345"). This happens straight as the function is called; it is not modified later on during another step.

Is there a way to keep the float value from turning into a string?

As requested, the send request step method is:

```<code>    $data = $this->fulfilmentOptions->getDataValue($request);
    $uri = $this->getMinkParameter('base_url') . $this->setEndpoint($endpoint);

    array_walk_recursive($data, function(&$item, $originalKey) use ($key, $value) {
        if ($originalKey === $key) {
            $item = $value;
        }
    });

    try {
        $this->response = $this->client->request($method, $uri, [
            'headers' => $this->fulfilmentOptions->getDataValue('CreateOrder API Headers'),
            'body' => json_encode($data)
        ]);
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        $this->response = $e->getResponse();
    }

    $this->responseContent = $this->response->getBody()->getContents();
</code>```

答: One way of fixing the issue is to use floatval method for 'value' key to make sure you get the right type.

Title: Behat Scenario Outline Float values

Body:
Consider the following scenario for API testing

Given I am using the API Service
When  I send the <request> as <method> to <endpoint> endpoint with <key> having value <value>
Then  The response status code is 200

Examples:
  | request    | method | endpoint       | key            | value          |
  | "All Keys" | "POST" | "endpointName" | "numericField" | 15             |
  | "All Keys" | "POST" | "endpointName" | "numericField" | 15.12345       |

The above example creates a request with the specified parameters.

My problem is that while the integer (15) value is passed to the function accordingly, the float (15.12345) is converted into a string ("15.12345"). This happens straight as the function is called; it is not modified later on during another step.

Is there a way to keep the float value from turning into a string?

As requested, the send request step method is:

    $data = $this->fulfilmentOptions->getDataValue($request);
    $uri = $this->getMinkParameter('base_url') . $this->setEndpoint($endpoint);

    array_walk_recursive($data, function(&$item, $originalKey) use ($key, $value) {
        if ($originalKey === $key) {
            $item = $value;
        }
    });

    try {
        $this->response = $this->client->request($method, $uri, [
            'headers' => $this->fulfilmentOptions->getDataValue('CreateOrder API Headers'),
            'body' => json_encode($data)
        ]);
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        $this->response = $e->getResponse();
    }

    $this->responseContent = $this->response->getBody()->getContents();


问:
How can we detect the region settings from iPhone in Xamarin Forms?
I am working on localizing a Xamarin Forms app now.

In iOS the user can change the Region settings without changing the device language, right? How can we detect this region settings in Xamarin Forms? I tried the following code to get the current culture, but the region setting doesn't do anything to the CurrentCulture unless we change the language settings.

```<code>var culture = CultureInfo.CurrentCulture
</code>```

I need to display a decimal value in the app which is supposed to be displayed as 123.456 in US region and 123,456 is France region. I get 123,456 only when I change the language settings.

I can get the current locale using NSLocale which gives me en_FR. But if I use this to create a new CultureInfo it throws System.Globalization.CultureNotFoundException exception.

```<code>            var culture = new CultureInfo("en_FR");
</code>```

答:
You might want to try NSLocale.CurrentLocale.

Also,

Your application can be notified of changes in the system local by using the NSLocale.CurrentLocaleDidChangeNotification as the notification to monitor with NSNotificationCenter.

Body:
I am working on localizing a Xamarin Forms app now.

In iOS the user can change the Region settings without changing the device language, right? How can we detect this region settings in Xamarin Forms? I tried the following code to get the current culture, but the region setting doesn't do anything to the CurrentCulture unless we change the language settings.

var culture = CultureInfo.CurrentCulture

I need to display a decimal value in the app which is supposed to be displayed as 123.456 in US region and 123,456 is France region. I get 123,456 only when I change the language settings.

I can get the current locale using NSLocale which gives me en_FR. But if I use this to create a new CultureInfo it throws System.Globalization.CultureNotFoundException exception.

            var culture = new CultureInfo("en_FR");


问:
git-svn branching without copying every subdirectory
Our project's trunk looks something like:

```<code>trunk/foo
trunk/bar
trunk/baz
</code>```

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

```<code>branches/branch1/foo
branches/branch2/foo
</code>```

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

```<code>branches/branch1/foo
branches/branch1/bar
</code>```

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

答:
not sure the exact syntax for this, nor do i know if this will work, but I think you could try to make the three different folders git submodules.

can you point the git clones to each trunk individually and clone them that way?

ContentLicense: CC BY-SA 2.5

Body:
Our project's trunk looks something like:

trunk/foo
trunk/bar
trunk/baz

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

branches/branch1/foo
branches/branch2/foo

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

branches/branch1/foo
branches/branch1/bar

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.


问:
Show Workbench output as MySQL table format
so

```<code>+----------+-------------+----------------+----------------------+
| actor_id | first_name  | last_name      | last_update          |
+----------+-------------+----------------+----------------------+
|        1 | PENELOPE    | GUINESS        | 2006-02-15 4:34:33   |
|        2 | NICK        | WAHLBERG       | 2006-02-15 4:34:33   |
|        3 | ED          | CHASE          | 2006-02-15 4:34:33   |
+----------+-------------+----------------+----------------------+
</code>```

instead of

Edit for clarity:
I want the actual text output since I don't have access to the DB via command line and am currently only working with workbench.

Right-clicking the output on workbench only allows you to grab the data as CSV or TSV which doesn't look as nice when posted on chats like slack, or comment systems like Jira.

答:
You can get pure text output by running your query via another menu entry/hot key:

which will give you output like this:

Body:
so

+----------+-------------+----------------+----------------------+
| actor_id | first_name  | last_name      | last_update          |
+----------+-------------+----------------+----------------------+
|        1 | PENELOPE    | GUINESS        | 2006-02-15 4:34:33   |
|        2 | NICK        | WAHLBERG       | 2006-02-15 4:34:33   |
|        3 | ED          | CHASE          | 2006-02-15 4:34:33   |
+----------+-------------+----------------+----------------------+

instead of

Edit for clarity:
I want the actual text output since I don't have access to the DB via command line and am currently only working with workbench.

Right-clicking the output on workbench only allows you to grab the data as CSV or TSV which doesn't look as nice when posted on chats like slack, or comment systems like Jira.


问:
Gradle projects depending on artifacts created by sibling projects
I have this Gradle setup with four projects, a parent with three children, where a Java Servlet JSON 'backend' is built into a war-file, and then a static HTML5 'frontend' consuming this is built into a zip. Both these "installs" their artifcats to the local maven repo.

The third sibling project 'merger' depends on these two artifacts, to build a "merged" war by simply "zipping them together".

However, once I had this up and running as intended, I obviously had to test the bootstrap-scenario by deleting the artifacts from the local repo.

Now I suddenly get "Artifact 'no.company:frontend:1.0-SNAPSHOT@zip' not found".

Is it not possible to depend on artifacts which will be produced by the current build?

Edit:

Based on another idea (and the reply from Peter discouraging this Maven logic), this version looks promising, not traversing Maven (note: it works!):

```<code>// ## From frontend's build.gradle:
task zipFrontend(dependsOn: 'buildFrontend',  type: Zip) {
    from ('dist/')
}

// ## From backend's build.gradle:
apply plugin: 'war'

// ## From merger's build.gradle:
task mergeFrontAndBack(dependsOn: [':backend:war',
                                   ':frontend:zipFrontend'], type: War) {
    from zipTree(project(':frontend').tasks['zipFrontend'].archivePath)
    from zipTree(project(':backend').tasks['war'].archivePath)
    destinationDir(buildDir)
}
</code>```

Edit 2:

Based upon Peter's comment about not reaching into siblings' project structure and his concrete suggestions, here's the resulting piece (note: it works!):

```<code>// ## From frontend's build.gradle:
task zipFrontend(dependsOn: 'buildFrontend',  type: Zip) {
    from ('dist/')
}
configurations { zip }
artifacts { zip zipFrontend }

// ## From backend's build.gradle:
apply plugin: 'war'
configurations { jsonOnlyWar }
artifacts { jsonOnlyWar war }

// ## From merger's build.gradle:
configurations { merge }
dependencies {
    merge project(path: ':backend', configuration: 'jsonOnlyWar')
    merge project(path: ':frontend', configuration: 'zip')
}
task mergeFrontAndBack(dependsOn: configurations.merge, type: War) {
    from { configurations.merge.collect { zipTree(it) } }
    destinationDir(buildDir)
}
</code>```

答: Using this post and ideas from elsewhere I made a github project - https://github.com/istomisgood/WarNode</p>

Body:
I have this Gradle setup with four projects, a parent with three children, where a Java Servlet JSON 'backend' is built into a war-file, and then a static HTML5 'frontend' consuming this is built into a zip. Both these "installs" their artifcats to the local maven repo.

The third sibling project 'merger' depends on these two artifacts, to build a "merged" war by simply "zipping them together".

However, once I had this up and running as intended, I obviously had to test the bootstrap-scenario by deleting the artifacts from the local repo.

Now I suddenly get "Artifact 'no.company:frontend:1.0-SNAPSHOT@zip' not found".

Is it not possible to depend on artifacts which will be produced by the current build?

Edit:

Based on another idea (and the reply from Peter discouraging this Maven logic), this version looks promising, not traversing Maven (note: it works!):

// ## From frontend's build.gradle:
task zipFrontend(dependsOn: 'buildFrontend',  type: Zip) {
    from ('dist/')
}

// ## From backend's build.gradle:
apply plugin: 'war'

// ## From merger's build.gradle:
task mergeFrontAndBack(dependsOn: [':backend:war',
                                   ':frontend:zipFrontend'], type: War) {
    from zipTree(project(':frontend').tasks['zipFrontend'].archivePath)
    from zipTree(project(':backend').tasks['war'].archivePath)
    destinationDir(buildDir)
}

Edit 2:

Based upon Peter's comment about not reaching into siblings' project structure and his concrete suggestions, here's the resulting piece (note: it works!):

// ## From frontend's build.gradle:
task zipFrontend(dependsOn: 'buildFrontend',  type: Zip) {
    from ('dist/')
}
configurations { zip }
artifacts { zip zipFrontend }

// ## From backend's build.gradle:
apply plugin: 'war'
configurations { jsonOnlyWar }
artifacts { jsonOnlyWar war }

// ## From merger's build.gradle:
configurations { merge }
dependencies {
    merge project(path: ':backend', configuration: 'jsonOnlyWar')
    merge project(path: ':frontend', configuration: 'zip')
}
task mergeFrontAndBack(dependsOn: configurations.merge, type: War) {
    from { configurations.merge.collect { zipTree(it) } }
    destinationDir(buildDir)
}


答:
You need to use map, that will go thru each item. In each item, use split() to split the data w.r.t @. After split(), you would get an array. You need to return 0th element of that array:

var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];

var getNames = data.map(function(item){
  return item.split('@')[0];
});

console.log(getNames);```

Title: How to extract array of names from array of email ids


问:
Jailbroken iPhone 3G with iOS 4.2.1 can't be debugged with XCode
I'm trying to debug my applications with XCode 3.2.5 and jailbroken iPhone 3G with iOS 4.2.1.

When I start debug with enabled breakpoints, application can't start (it stucks on 'Default.png' screen) and I get Data Formatters temporarily unavailable, will re-try after a 'continue'. (Can't find dlopen function, so it is not possible to load shared libraries.) message in GDB.

When I start debug without enabled breakpoints, application starts without problems.

I tried to do steps decribed there, but without any results.

When I used iOS 4.1 there was a problem with reboots.

On every connect of the iPhone Organiser displays this message:

**Unknown iOS detected** Xcode does not have debugging information for the version of iOS on the device named “iPhone”. Xcode can collect debugging data from the device to enable development with this version of iOS. This process only needs to be done once per iOS version, and will take several minutes.

Thanks for any help!

答:
Additional suggestion besides Fnord's suggestion is to make sure that multitasking, or the "Reenable Functionality" in PwnageTool is not enabled for iPhone 3G jailbroken device.

I'm not sure if this has an effect though. But, it's reasonable to do this if we really want to test it on a real world condition of iPhone 3G.


问:
Radio Buttons don't appear on screen when added programatically
I have the following code in a button click handler:

```<code>LinearLayout linearLayoutParent = FindViewById<LinearLayout>(Resource.Id.linearLayoutParent);
LinearLayout linearLayoutFileTransferVia = new LinearLayout(this);
TextView labelFileTransferViaInfo = new TextView(this);
labelFileTransferViaInfo.LayoutParameters = lp;
labelFileTransferViaInfo.Text = "Choose file transfer via to FTP Server";
labelFileTransferViaInfo.SetTextAppearance(Android.Resource.Style.TextAppearanceLarge);
RadioButton rbWiFi = new RadioButton(this);
RadioButton rb3G = new RadioButton(this);
RadioGroup radioGroupFileTransferType = new RadioGroup(this);
radioGroupFileTransferType.Orientation = Orientation.Horizontal;
rbWiFi.Text = "Wi-Fi";
rb3G.Text = "3G";
radioGroupFileTransferType.AddView(rbWiFi);
radioGroupFileTransferType.AddView(rb3G);
linearLayoutFileTransferVia.AddView(labelFileTransferViaInfo);
linearLayoutFileTransferVia.AddView(radioGroupFileTransferType);
linearLayoutParent.AddView(linearLayoutFileTransferVia);
</code>```

When I click the button labelFileTransferViaInfo appears on screen but radioGroupFileTransferType doesn't. What do you think is the problem for that to happen?

答:
I think you need to add LayoutParams just like that

```<code>            LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.MATCH_PARENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);

radioGroupFileTransferType.AddView(rbWiFi, layoutParams);
radioGroupFileTransferType.AddView(rb3G, layoutParams);
</code>```

Body:
I have the following code in a button click handler:

LinearLayout linearLayoutParent = FindViewById<LinearLayout>(Resource.Id.linearLayoutParent);
LinearLayout linearLayoutFileTransferVia = new LinearLayout(this);
TextView labelFileTransferViaInfo = new TextView(this);
labelFileTransferViaInfo.LayoutParameters = lp;
labelFileTransferViaInfo.Text = "Choose file transfer via to FTP Server";
labelFileTransferViaInfo.SetTextAppearance(Android.Resource.Style.TextAppearanceLarge);
RadioButton rbWiFi = new RadioButton(this);
RadioButton rb3G = new RadioButton(this);
RadioGroup radioGroupFileTransferType = new RadioGroup(this);
radioGroupFileTransferType.Orientation = Orientation.Horizontal;
rbWiFi.Text = "Wi-Fi";
rb3G.Text = "3G";
radioGroupFileTransferType.AddView(rbWiFi);
radioGroupFileTransferType.AddView(rb3G);
linearLayoutFileTransferVia.AddView(labelFileTransferViaInfo);
linearLayoutFileTransferVia.AddView(radioGroupFileTransferType);
linearLayoutParent.AddView(linearLayoutFileTransferVia);

When I click the button labelFileTransferViaInfo appears on screen but radioGroupFileTransferType doesn't. What do you think is the problem for that to happen?

Body:
I think you need to add LayoutParams just like that

            LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.MATCH_PARENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);

radioGroupFileTransferType.AddView(rbWiFi, layoutParams);
radioGroupFileTransferType.AddView(rb3G, layoutParams);


问:
How to post form data to ASP.NET web api controller in reactjs
I am new to React and I have been trying to implement a simple "employee details" crud application. I was able to get the data from database and display it in table format. But I am not able to post the data from form to database. It will be very helpful if you some one could provide me a detailed jsx code to post data from form to controller. And also controller side code to save data to database. Please find my code below.

This is my model (used entity framework):

```<code>public partial class EmployeeTable
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string Designation { get; set; }
        public long Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
</code>```

Controller:

```<code>namespace ReactModelApp.Controllers
{
    [RoutePrefix("api/Employee")]
    public class EmployeeController : ApiController
    {
        EmployeeEntities db = new EmployeeEntities();

        [Route("GetEmployeeList")]
        public IQueryable<EmployeeTable> GetEmployeeList()
        {
            return db.EmployeeTables.AsQueryable();
        }

        [Route("InputEmployee")]

        public HttpResponseMessage InputEmployee([FromBody]EmployeeTable Employee)
        {
            try
            {
                using (EmployeeEntities entities = new EmployeeEntities())
                {
                    entities.EmployeeTables.Add(Employee);
                    entities.SaveChanges();
                    var message = Request.CreateResponse(HttpStatusCode.Created, Employee);
                    message.Headers.Location = new Uri(Request.RequestUri + Employee.EmployeeID.ToString());
                    return message;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    }
}
</code>```

React.jsx code for displaying data from database:

```<code>var EmployeeRow = React.createClass({

      render: function () {
          return(
              <tr>
                  <td>{this.props.item.EmployeeID}</td>
                  <td>{this.props.item.FirstName}</td>
                  <td>{this.props.item.LastName}</td>
                  <td>{this.props.item.Gender}</td>
                  <td>{this.props.item.Designation}</td>
                  <td>{this.props.item.Salary}</td>
                  <td>{this.props.item.City}</td>
                  <td>{this.props.item.Country}</td>
              </tr>

              );
      }
  });

  var EmployeeTable = React.createClass({

      getInitialState: function(){

          return{
              result:[]
          }
      },
      componentWillMount: function(){

          var xhr = new XMLHttpRequest();
          xhr.open('get', this.props.url, true);
          xhr.onload = function () {
              var response = JSON.parse(xhr.responseText);

              this.setState({ result: response });

          }.bind(this);
          xhr.send();
      },
      render: function(){
          var rows = [];
          this.state.result.forEach(function (item) {
              rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
      });
  return (<table className="table">
     <thead>
         <tr>
            <th>EmployeeID</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Gender</th>
            <th>Designation</th>
            <th>Salary</th>
            <th>City</th>
            <th>Country</th>
         </tr>
     </thead>

      <tbody>
          {rows}
      </tbody>

  </table>);
  }

  });

  ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
          document.getElementById('grid'))
</code>```

Form React jsx code:

```<code>var InputValues=React.createClass({
  handleClick:function(){

},

  render:function(){
    return(
      <div>
          <form>
          <label id="firstname">First Name </label><br/>
          <input type="text"  placeholder="Enter First Name" ref="firstName"   />
          <br/><br/><label id="lastname">Last Name: </label><br/>
          <input type="text"  placeholder="Enter Last Name"  ref="lastName"   />
          <br/><br/><label id="gender">Gender: </label><br/>
          <input type="text"  placeholder="Gender"  ref="gender"   />
          <br/><br/><label id="designation">Designation: </label><br/>
          <input type="text"  placeholder="Enter Designation"  ref="designation"   />
          <br/><br/><label id="salary">Salary: </label><br/>
          <input type="number"  placeholder="Enter Salary"  ref="salary"   />
          <br/><br/><label id="city">City: </label><br/>
          <input type="text"  placeholder="Enter City"  ref="city"   />
          <br/><br/><label id="country">Country: </label><br/>
          <input type="text"  placeholder="Enter Country"  ref="country"   />
          <p>
            <button type="button" onClick={this.handleClick}>Submit</button>
          </p>
        </form>
      </div>
    );
  }
});
</code>```

答:
It seems you are using very outdated version of React. You had several issues in your code(I was just looking the InputValues component).

In order for label to work as expected you need to have matching htmlFor attribute on label and id attribute on input.

Handling form submission via click on button will not trigger handler when user submits the form with keyboard, thats why it is better to handle it with onSubmit.

I also updated your React syntax to match the current one, where refs are defined in a whole new way where the string ref was dropped more than a year ago, more details on link https://reactjs.org/docs/refs-and-the-dom.html

I imagine you are following a tutorial, but urge you to find one with newer syntax since you will have a hard time adjusting later on.

Anyway here is the code that will call your backend service and provide it with form data.

```<code>class InputValues extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = new FormData();
    data.append('firstName', this.firstName.value);
    data.append('lastname', this.lastname.value);
    data.append('gender', this.gender.value);
    data.append('designation', this.designation.value);
    data.append('salary', this.salary.value);
    data.append('city', this.city.value);
    data.append('country', this.country.value);
    var xhr = new XMLHttpRequest();
    xhr.open('post', this.props.url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
      if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        // Do something on success
      }
    }
    xhr.send(data);
  }

  render() {
    return(
      <div>
          <form onSubmit={this.handleSubmit}>
          <label htmlFor="firstname">First Name </label><br/>
          <input id="firstname" type="text"  placeholder="Enter First Name" ref={(firstName) => this.firstName = firstName} />
          <br/><br/>
          <label htmlFor="lastname">Last Name: </label><br/>
          <input id="lastname" type="text"  placeholder="Enter Last Name"  ref={(lastname) => this.lastname = lastname} />
          <br/><br/>
          <label htmlFor="gender">Gender: </label><br/>
          <input id="gender" type="text"  placeholder="Gender"  ref={(gender) => this.gender = gender} />
          <br/><br/>
          <label htmlFor="designation">Designation: </label><br/>
          <input id="designation" type="text"  placeholder="Enter Designation" ref={(designation) => this.designation = designation} />
          <br/><br/>
          <label htmlFor="salary">Salary: </label><br/>
          <input id="salary" type="number"  placeholder="Enter Salary" ref={(salary) => this.salary = salary} />
          <br/><br/>
          <label htmlFor="city">City: </label><br/>
          <input id="city" type="text"  placeholder="Enter City" ref={(city) => this.city = city} />
          <br/><br/>
          <label htmlFor="country">Country: </label><br/>
          <input id="country" type="text"  placeholder="Enter Country" ref={(country) => this.country = country} />
          <p>
            <button type="submit">Submit</button>
          </p>
        </form>
      </div>
    );
  }
};
</code>```

Hope that helps!

Body:
I am new to React and I have been trying to implement a simple "employee details" crud application. I was able to get the data from database and display it in table format. But I am not able to post the data from form to database. It will be very helpful if you some one could provide me a detailed jsx code to post data from form to controller. And also controller side code to save data to database. Please find my code below.

This is my model (used entity framework):

public partial class EmployeeTable
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string Designation { get; set; }
        public long Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

Controller:

namespace ReactModelApp.Controllers
{
    [RoutePrefix("api/Employee")]
    public class EmployeeController : ApiController
    {
        EmployeeEntities db = new EmployeeEntities();

        [Route("GetEmployeeList")]
        public IQueryable<EmployeeTable> GetEmployeeList()
        {
            return db.EmployeeTables.AsQueryable();
        }

        [Route("InputEmployee")]

        public HttpResponseMessage InputEmployee([FromBody]EmployeeTable Employee)
        {
            try
            {
                using (EmployeeEntities entities = new EmployeeEntities())
                {
                    entities.EmployeeTables.Add(Employee);
                    entities.SaveChanges();
                    var message = Request.CreateResponse(HttpStatusCode.Created, Employee);
                    message.Headers.Location = new Uri(Request.RequestUri + Employee.EmployeeID.ToString());
                    return message;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    }
}

React.jsx code for displaying data from database:

var EmployeeRow = React.createClass({

      render: function () {
          return(

                  {this.props.item.EmployeeID}
                  {this.props.item.FirstName}
                  {this.props.item.LastName}
                  {this.props.item.Gender}
                  {this.props.item.Designation}
                  {this.props.item.Salary}
                  {this.props.item.City}
                  {this.props.item.Country}

              );
      }
  });

  var EmployeeTable = React.createClass({

      getInitialState: function(){

          return{
              result:[]
          }
      },
      componentWillMount: function(){

          var xhr = new XMLHttpRequest();
          xhr.open('get', this.props.url, true);
          xhr.onload = function () {
              var response = JSON.parse(xhr.responseText);

              this.setState({ result: response });

          }.bind(this);
          xhr.send();
      },
      render: function(){
          var rows = [];
          this.state.result.forEach(function (item) {
              rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
      });
  return (

            EmployeeID
            FirstName
            LastName
            Gender
            Designation
            Salary
            City
            Country

          {rows}

);
  }

  });

  ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
          document.getElementById('grid'))

Form React jsx code:

var InputValues=React.createClass({
  handleClick:function(){

},

  render:function(){
    return(

          <form>
          First Name

          <input type="text"  placeholder="Enter First Name" ref="firstName"   />

Last Name:

          <input type="text"  placeholder="Enter Last Name"  ref="lastName"   />

Gender:

          <input type="text"  placeholder="Gender"  ref="gender"   />

Designation:

          <input type="text"  placeholder="Enter Designation"  ref="designation"   />

Salary:

          <input type="number"  placeholder="Enter Salary"  ref="salary"   />

City:

          <input type="text"  placeholder="Enter City"  ref="city"   />

Country:

          <input type="text"  placeholder="Enter Country"  ref="country"   />

            <button type="button" onClick={this.handleClick}>Submit</button>

        </form>

    );
  }
});

Body:
It seems you are using very outdated version of React. You had several issues in your code(I was just looking the InputValues component).

In order for label to work as expected you need to have matching htmlFor attribute on label and id attribute on input.

Handling form submission via click on button will not trigger handler when user submits the form with keyboard, thats why it is better to handle it with onSubmit.

I also updated your React syntax to match the current one, where refs are defined in a whole new way where the string ref was dropped more than a year ago, more details on link https://reactjs.org/docs/refs-and-the-dom.html

I imagine you are following a tutorial, but urge you to find one with newer syntax since you will have a hard time adjusting later on.

Anyway here is the code that will call your backend service and provide it with form data.

class InputValues extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = new FormData();
    data.append('firstName', this.firstName.value);
    data.append('lastname', this.lastname.value);
    data.append('gender', this.gender.value);
    data.append('designation', this.designation.value);
    data.append('salary', this.salary.value);
    data.append('city', this.city.value);
    data.append('country', this.country.value);
    var xhr = new XMLHttpRequest();
    xhr.open('post', this.props.url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
      if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        // Do something on success
      }
    }
    xhr.send(data);
  }

  render() {
    return(
      <div>
          <form onSubmit={this.handleSubmit}>
          <label htmlFor="firstname">First Name </label><br/>
          <input id="firstname" type="text"  placeholder="Enter First Name" ref={(firstName) => this.firstName = firstName} />
          <br/><br/>
          <label htmlFor="lastname">Last Name: </label><br/>
          <input id="lastname" type="text"  placeholder="Enter Last Name"  ref={(lastname) => this.lastname = lastname} />
          <br/><br/>
          <label htmlFor="gender">Gender: </label><br/>
          <input id="gender" type="text"  placeholder="Gender"  ref={(gender) => this.gender = gender} />
          <br/><br/>
          <label htmlFor="designation">Designation: </label><br/>
          <input id="designation" type="text"  placeholder="Enter Designation" ref={(designation) => this.designation = designation} />
          <br/><br/>
          <label htmlFor="salary">Salary: </label><br/>
          <input id="salary" type="number"  placeholder="Enter Salary" ref={(salary) => this.salary = salary} />
          <br/><br/>
          <label htmlFor="city">City: </label><br/>
          <input id="city" type="text"  placeholder="Enter City" ref={(city) => this.city = city} />
          <br/><br/>
          <label htmlFor="country">Country: </label><br/>
          <input id="country" type="text"  placeholder="Enter Country" ref={(country) => this.country = country} />
          <p>
            <button type="submit">Submit</button>
          </p>
        </form>
      </div>
    );
  }
};

Hope that helps!


问:
Clojure core.async. How to download lazily with go block inside with-open?
It`s a continuation of my previous question How to produce a lazy sequence by portion in clojure?

I want download data from a database by portions. Initially I download first 500 rows and then I send a request to fetch next 500 rows and so on until I receive all data from a server.

I wrote the code:

```<code>(jdbc/atomic conn
 (with-open [cursor (jdbc/fetch-lazy conn [sql_query])]
   (let [lazyseq (jdbc/cursor->lazyseq cursor)
         counter (atom 1)]
     (swap! lazyseq_maps assoc :session_id {:get_next? (chan 1) :over_500 (chan 1) :data []})
     (>!! (:get_next? (:session_id @lazyseq_maps)) true)
     (go
       (doseq [row lazyseq]
         (swap! counter inc)
         (when (<! (:get_next? (:session_id @lazyseq_maps)))
           (swap! lazyseq_maps update-in [:session_id :data] conj row)
           (if (not= 0 (mod @counter 500))
             (>! (:get_next? (:session_id @lazyseq_maps)) true)
             (>! (:over_500 (:session_id @lazyseq_maps)) true))))
        ;
        (close! (:get_next? (:session_id @lazyseq_maps)))
        (close! (:over_500 (:session_id @lazyseq_maps)))
        (.close conn))

     (when (<!! (:over_500 (:session_id @lazyseq_maps))) {:message "over 500 rows"
                                                          :id :session_id
                                                          :data (:data (:session_id @lazyseq_maps))}))))
</code>```

I fetch rows with help of the doseq cycle. When doseq passed 500 rows I park the cycle (when (<! (:get_next? (:session_id @lazyseq_maps))) and wait for a signal from outside to retrieve next 500 rows.

But here I have a problem. When I send the signal, the program throws error "Resultset is closed". I.e connection is closed outside with-open scope. But I don`t understand why, because go block is placed inside with-open scope. Can you help me solve the problem?

答:
(go ...) returns immediately, therefore, so does (with-open ...).

You may want to do it the other way around:

(go (with-open ...))

However, do note that this process will hold on to a database connection (a scarce resource!) for a potentially very long time, which may not be desirable, and kind of goes against the benefit of having 'lightweight' threads thanks to go blocks. Here are some alternatives to consider:

Maybe you could re-open a database connection for each batch?

Maybe you could eagerly stream the whole results set to an external store (e.g AWS S3) and have the client poll against that?

Body:
It`s a continuation of my previous question How to produce a lazy sequence by portion in clojure?

I want download data from a database by portions. Initially I download first 500 rows and then I send a request to fetch next 500 rows and so on until I receive all data from a server.

I wrote the code:

(jdbc/atomic conn
 (with-open [cursor (jdbc/fetch-lazy conn [sql_query])]
   (let [lazyseq (jdbc/cursor->lazyseq cursor)
         counter (atom 1)]
     (swap! lazyseq_maps assoc :session_id {:get_next? (chan 1) :over_500 (chan 1) :data []})
     (>!! (:get_next? (:session_id @lazyseq_maps)) true)
     (go
       (doseq [row lazyseq]
         (swap! counter inc)
         (when (<! (:get_next? (:session_id @lazyseq_maps)))
           (swap! lazyseq_maps update-in [:session_id :data] conj row)
           (if (not= 0 (mod @counter 500))
             (>! (:get_next? (:session_id @lazyseq_maps)) true)
             (>! (:over_500 (:session_id @lazyseq_maps)) true))))
        ;
        (close! (:get_next? (:session_id @lazyseq_maps)))
        (close! (:over_500 (:session_id @lazyseq_maps)))
        (.close conn))

     (when (<!! (:over_500 (:session_id @lazyseq_maps))) {:message "over 500 rows"
                                                          :id :session_id
                                                          :data (:data (:session_id @lazyseq_maps))}))))

I fetch rows with help of the doseq cycle. When doseq passed 500 rows I park the cycle (when (<! (:get_next? (:session_id @lazyseq_maps))) and wait for a signal from outside to retrieve next 500 rows.

But here I have a problem. When I send the signal, the program throws error "Resultset is closed". I.e connection is closed outside with-open scope. But I don`t understand why, because go block is placed inside with-open scope. Can you help me solve the problem?


问:
How to kill a process except one?
I have few processes starting with string apple. So my processes names are apple1, apple2, apple3 till apple10. Now I use command "pkill -f apple". But it kills all processes starting with apple. I want apple2 not to get killed with the above command. So can someone tell me how the above command can be modified? </p>

答:
This works for excluding the apple2 pid from the list and kill others , Not sure if your problem will be solved with this.</p>

```<code>ps -aef | grep apple | grep -v apple2 | awk '{print $2}'|while read pid
do
kill -9 $pid
done
</code>```

Title: How to kill a process except one?

Body:
This works for excluding the apple2 pid from the list and kill others , Not sure if your problem will be solved with this.

ps -aef | grep apple | grep -v apple2 | awk '{print $2}'|while read pid
do
kill -9 $pid
done


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
It depends on what you need.
In my case, I had a situation where speed was paramount as I was performing intense processing on thousands of rows in a DataSet, so I chose to write a piece of code that cached the column indexes by name.
Then, in the loop code I used the cached indexes. This gave a reasonable performance increase over using the column name directly.

Your mileage may vary, of course. My situation was a rather contrived and unusual case, but in that instance it worked rather well.

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

OwnerDisplayName: Andrew Rollings


问:
C#'s equivalent of Java's <? extends Base> in generics
In Java, I can do the following: (assume Subclass extends Base):

```<code>ArrayList<? extends Base> aList = new ArrayList<Subclass>();
</code>```

What is the equivalent in C# .NET? There is no ? extends keyword apparently and this does not work:

```<code>List<Base> aList = new List<Subclass>();
</code>```

答: There is no exact equivalent (since the type system doesn't work in quite the same way, with type erasure and all), but you can get very similar functionality with in and out using covariance and contravariance.

Body:
In Java, I can do the following: (assume Subclass extends Base):

ArrayList<? extends Base> aList = new ArrayList<Subclass>();

What is the equivalent in C# .NET? There is no ? extends keyword apparently and this does not work:

List<Base> aList = new List<Subclass>();


问:
Generate all combinations of string by space
Say i have a string A B C D - i want to end up with a List<List<String>> which will contain the following combinations:

```<code>[A,B,D,C]
[A,B C D]
[A B, C D]
[A B C, D]
[A, B C, D]
etc...
</code>```

found a bunch of answered questions with similar requests where people asked for all combinations based on substring of a single string but was unable to tweak it to my needs.

Ay help would be much appreciated!

答:
You can try to do it by recursion.
Have 2 strings, left and right. Shift the rightmost character to the right string, repeat until there's only 1 character in left string. Everytime you do so, apply the same function to the right string.

So if you have "ABCD", that gives you:

```<code>"ABCD"
"ABC" f("D")
"AB" f("CD")
"A" f("BCD")
</code>```

Fully expended you get:

```<code>f("ABCD") {
    "ABCD"
    "ABC" f("D")
        f("D") {
            "D"
        }
    "AB" f("CD")
        f("CD") {
            "CD"
            "C" f("D")
                f("D") {
                    "D"
                }
        }
    "A" f("BCD")
        f("BCD") {
            "BCD"
            "BC" f("D")
                f("D") {
                    "D"
                }
            "B" f("CD")
                f("CD") {
                    "CD"
                    "C" f("D")
                        f("D") {
                            "D"
                        }
                }
        }
}
</code>```

which gives you:

```<code>[["ABCD"],
["ABC", "D"],
["AB", "CD"],
["AB", "C", "D"],
["A", "BCD"],
["A", "BC", "D"],
["A", "B", "CD"],
["A", "B", "C", "D"]]
</code>```

Body:
Say i have a string A B C D - i want to end up with a List<List<String>> which will contain the following combinations:

[A,B,D,C]
[A,B C D]
[A B, C D]
[A B C, D]
[A, B C, D]
etc...

found a bunch of answered questions with similar requests where people asked for all combinations based on substring of a single string but was unable to tweak it to my needs.

Ay help would be much appreciated!

Body:
You can try to do it by recursion.
Have 2 strings, left and right. Shift the rightmost character to the right string, repeat until there's only 1 character in left string. Everytime you do so, apply the same function to the right string.

So if you have "ABCD", that gives you:

"ABCD"
"ABC" f("D")
"AB" f("CD")
"A" f("BCD")

Fully expended you get:

f("ABCD") {
    "ABCD"
    "ABC" f("D")
        f("D") {
            "D"
        }
    "AB" f("CD")
        f("CD") {
            "CD"
            "C" f("D")
                f("D") {
                    "D"
                }
        }
    "A" f("BCD")
        f("BCD") {
            "BCD"
            "BC" f("D")
                f("D") {
                    "D"
                }
            "B" f("CD")
                f("CD") {
                    "CD"
                    "C" f("D")
                        f("D") {
                            "D"
                        }
                }
        }
}

which gives you:

[["ABCD"],
["ABC", "D"],
["AB", "CD"],
["AB", "C", "D"],
["A", "BCD"],
["A", "BC", "D"],
["A", "B", "CD"],
["A", "B", "C", "D"]]


问:
How can I make an image function as a button, and make it perform an action when clicked ( start a keyframe event, run a script)?
I've just started coding at school, and our teacher is horrible. I have to teach myself how to code, and for that reason, I've come here seeking help :). I've created this website using some simple html and css, and what I would like now is for the image I'm using in my navigation bar to act as a button, and when pressed, do something cool, like make an animation, or start a keyframe event where a few keyframes that I've set will trigger (like blinking text) or maybe even run a cool javascript. This is mostly for show, but at the same time, I'm here to learn. If my code is poorly written, feel free to correct it. Thank you.

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="icon" href="bilde.png">
    <meta charset="UTF-8">
    <title>Bully</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/stil2.css">
</center>
<center><ul class="navigation">
   <li><a href="bully2.html">Home</a></li>
  <li><a href="contact.html">Contact</a></li>
 <li><a href="" target="_blank">
         [This is that I want to use as a button ->] <img src="bilde.png" alt="Emblem" style="width:120px;height:120px;border:0";>
        </a>
  <li><a href="orbok2.html">Gallery</a></li>
  <li><a href="Lore.html">Lore</a></li>
</ul>

<ul class="flex-container">
    <li class="flex-item" style="font-size:42px;"><h1>~Breaking News~</h1>
  <li class="flex-item"><h1><ins>26. October, 2017.</ins></h1><br><a style="font-size:32px;">The release of the videogame "Bully 2" has just been confirmed, according to a variety of different reliable sources. Spokesperson Bad Andy from Bullworth Chess Club confirmed the release date of Bully 2 to be on January 1st of 2019. "Bully's long-awaited sequel will be a tremendous success in today's videogame-industry," said Andy in an interview with Russel Barro, owner of The Bullworth Herald.<br></a><h2>~Jimmy Hopkins~</h2></li>
  <center><ul class="flex-container">
  <center><li class="flex-item"><h1><ins>18. October, 2017.</ins></h1><br><a style="font-size:32px;">Fire alarm was set off at 11:24 by unknown student or person. Faculty and staff encourage all students to send in clues and tips about the incident to: Bullworthacademy@edu.com</a><br><h2>~Staff~</h2></li>
  <center><ul class="flex-container">
  <center><li class="flex-item"><h1><ins>Bully 2 "confirmed" by R* insider?</ins></h1><br><a style="font-size:32px;">Trusted gtaforum.com-admin "Yan2295" made a post on April 21st saying this: <br> <br> </a>
  <img src="yan.png" style="border:2.5px solid black;width:65%;height:250px;">
  </p><br><h2>~Russel Hustle~</h2></li>
</div>
</ul>

</body>
</html>

CSS
@import "compass/css3";

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
  }
body{
  background-image:url("brun.jpeg");
  background-repeat:no-repeat;
  background-size:1270px;
  background-attachment:fixed;
}

.flex-container {
  padding:0;
  margin:0;
  width:1000px;
  list-style: none;
  flex-direction:column;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row-wrap;
  justify-content: center;
}

.flex-item {
  background-color: rgba(0, 0, 0, 0.25);
  margin-top: 0px;
  margin-bottom:0px;
  margin-left:0;
  border-top:0px solid ;
  border-left:3px solid rgba(0, 0, 0, 1);
  border-bottom:0px solid ;
  border-right:3px solid rgba(0, 0, 0, 1);
  border-radius:0px;
  padding-bottom:100px;
  padding-top:100px;

  line-height:40px;
  color:rgba(252, 174, 26, 255);
  font-weight: bold;
  font-size: 26px;
  font-family:NarcissusOpenSG;
  text-align:center;
  flex-grow: 0;
  justify-content:space-around;
  animation-name:text;
  animation-iteration-count:infinite;
  animation-duration:2s;
  animation-direction:alternate;
}
@keyframes jtext{

from {
  color:rgba(252, 174, 26, 255);
}
to{
    color:rgba(0, 0, 0, 0.5);
}
}
.navigation {
  list-style: none;
  border-top:3px solid black;
  border-bottom:0px solid black;
  width:994px;
  border-right:3px solid black;
  border-left:3px solid black;
  margin-top:5px;
  margin-bottom:0px;
  text-align:center;
  align-items:center;
  padding:0;
  border-top-left-radius:50px;
  border-top-right-radius:50px;
  background-color: rgba(0, 0, 0, 0.25);

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content:space-around;
  font-family:NarcissusOpenSG;
  font-size:28px;
}

.navigation a {
  text-decoration: none;
  display: block;
  padding:0;
  padding: 1em;
  opacity:0.5;
  transition-duration:0.5s;
  color:rgba(252, 174, 26, 255);
}

.navigation a:hover {
  color;
  background:;
  opacity:1;
  animation-duration:1.5s;
  animation-iteration-count:infinite;
  animation-name:blink;
  animation-direction:alternate;
}
keyframes blink {

from {
opacity:0.75;
  }

to {
opacity:0;
}
}
@media all and (max-width: 800px) {
  .navigation {
    justify-content: space-around;
  }
}

@media all and (max-width: 600px) {
  .navigation {
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
  }

  .navigation a {
    text-align: center;
    padding:10px;
    border-top: 1px solid rgba(255,255,255,0.3);
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }

  .navigation li:last-of-type a {
    border-bottom: 0;
}
</code>```

答:
There are ways of doing this:

Add an anchor tag like this

put the image element here

Write a click function in javascript for the element with an id

document.getElementById("myId").onclick=function() { /* some code here */ }

Body:
I've just started coding at school, and our teacher is horrible. I have to teach myself how to code, and for that reason, I've come here seeking help :). I've created this website using some simple html and css, and what I would like now is for the image I'm using in my navigation bar to act as a button, and when pressed, do something cool, like make an animation, or start a keyframe event where a few keyframes that I've set will trigger (like blinking text) or maybe even run a cool javascript. This is mostly for show, but at the same time, I'm here to learn. If my code is poorly written, feel free to correct it. Thank you.

HTML

<!DOCTYPE html>

    <link rel="icon" href="bilde.png">
    <meta charset="UTF-8">
    <title>Bully</title>

<link rel="stylesheet" type="text/css" href="css/stil2.css">

Home

Contact

         [This is that I want to use as a button ->]

Gallery

Lore

~Breaking News~

26. October, 2017.

The release of the videogame "Bully 2" has just been confirmed, according to a variety of different reliable sources. Spokesperson Bad Andy from Bullworth Chess Club confirmed the release date of Bully 2 to be on January 1st of 2019. "Bully's long-awaited sequel will be a tremendous success in today's videogame-industry," said Andy in an interview with Russel Barro, owner of The Bullworth Herald.

~Jimmy Hopkins~

18. October, 2017.

Fire alarm was set off at 11:24 by unknown student or person. Faculty and staff encourage all students to send in clues and tips about the incident to: Bullworthacademy@edu.com

~Staff~

Bully 2 "confirmed" by R* insider?

Trusted gtaforum.com-admin "Yan2295" made a post on April 21st saying this:

~Russel Hustle~

CSS
@import "compass/css3";

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
  }
body{
  background-image:url("brun.jpeg");
  background-repeat:no-repeat;
  background-size:1270px;
  background-attachment:fixed;
}

.flex-container {
  padding:0;
  margin:0;
  width:1000px;
  list-style: none;
  flex-direction:column;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row-wrap;
  justify-content: center;
}

.flex-item {
  background-color: rgba(0, 0, 0, 0.25);
  margin-top: 0px;
  margin-bottom:0px;
  margin-left:0;
  border-top:0px solid ;
  border-left:3px solid rgba(0, 0, 0, 1);
  border-bottom:0px solid ;
  border-right:3px solid rgba(0, 0, 0, 1);
  border-radius:0px;
  padding-bottom:100px;
  padding-top:100px;

  line-height:40px;
  color:rgba(252, 174, 26, 255);
  font-weight: bold;
  font-size: 26px;
  font-family:NarcissusOpenSG;
  text-align:center;
  flex-grow: 0;
  justify-content:space-around;
  animation-name:text;
  animation-iteration-count:infinite;
  animation-duration:2s;
  animation-direction:alternate;
}
@keyframes jtext{

from {
  color:rgba(252, 174, 26, 255);
}
to{
    color:rgba(0, 0, 0, 0.5);
}
}
.navigation {
  list-style: none;
  border-top:3px solid black;
  border-bottom:0px solid black;
  width:994px;
  border-right:3px solid black;
  border-left:3px solid black;
  margin-top:5px;
  margin-bottom:0px;
  text-align:center;
  align-items:center;
  padding:0;
  border-top-left-radius:50px;
  border-top-right-radius:50px;
  background-color: rgba(0, 0, 0, 0.25);

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content:space-around;
  font-family:NarcissusOpenSG;
  font-size:28px;
}

.navigation a {
  text-decoration: none;
  display: block;
  padding:0;
  padding: 1em;
  opacity:0.5;
  transition-duration:0.5s;
  color:rgba(252, 174, 26, 255);
}

.navigation a:hover {
  color;
  background:;
  opacity:1;
  animation-duration:1.5s;
  animation-iteration-count:infinite;
  animation-name:blink;
  animation-direction:alternate;
}
keyframes blink {

from {
opacity:0.75;
  }

to {
opacity:0;
}
}
@media all and (max-width: 800px) {
  .navigation {
    justify-content: space-around;
  }
}

@media all and (max-width: 600px) {
  .navigation {
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
  }

  .navigation a {
    text-align: center;
    padding:10px;
    border-top: 1px solid rgba(255,255,255,0.3);
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }

  .navigation li:last-of-type a {
    border-bottom: 0;
}

Body:
There are ways of doing this:

Add an anchor tag like this

<a type="button" href="the url" id="myId">put the image element here</a>

Write a click function in javascript for the element with an id

document.getElementById("myId").onclick=function() { /* some code here */ }


问:
Try-except loop either succeeds first time or runs forever
I'm using requests get, and fairly often an exception is raised (json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)).  I want to loop until it's successful, and not discriminate on the exception type (yet).  My code will either succeed first time (exit the loop) or keep looping indefinitely.</p>

```<code>def loop_json(self,url):
    result = None
    print(url)
    while result == None:
        try:
            print('trying')
            response = requests.get(url).json()
            result = 1
        except:
            time.sleep(3)
            pass
    return response
</code>```

答:
I'll just write this here so it doesn't become a really long comment thread - it is indeed a 400 error that's returned.  I've posted an imgur url with the response I get.  This only happens sometimes - I ran it 4 times, the first 3 times I got a 200 response and everything was fine, the 4th I got a 400 response.  Nothing changed, and the loop still stays looping once I get the 400

https://imgur.com/a/xChgC

Body:
I'm using requests get, and fairly often an exception is raised (json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)).  I want to loop until it's successful, and not discriminate on the exception type (yet).  My code will either succeed first time (exit the loop) or keep looping indefinitely.

def loop_json(self,url):
    result = None
    print(url)
    while result == None:
        try:
            print('trying')
            response = requests.get(url).json()
            result = 1
        except:
            time.sleep(3)
            pass
    return response


问:
How to read XML attributes in order using Java?
My background in C#. I am facing behavioral difference while retrieving attribute count in JAVA compared to C#.

XML:

```<code>    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <book xmlns:v="urn:schemas-microsoft-com:vml" style="width:149.65pt"
    xmlns:w="urn:schemas-microsoft-com:office:office">
    <v:object w:dxaOrig="1440" w:dyaOrig="1440">
    </v:object>
    </book>
</code>```

In C#, the ‘Xmlns’ tag is considered as the attribute and hence while retrieving the attribute count the value is 3 for the above Xml element ‘book’. Whereas in JAVA (as per my understating, correct me if am wrong) ‘Xmlns’ is not an attribute, it is used as namespace declaration and it is also considered as reserved XML  pseudo-attribute to declare a namespace. So the attribute count for above case will be 1 in JAVA. I can retrieve the ‘xmlns’ tag as namespace count which is 2.

C# Code:

```<code>    for(int i=0;i<reader.AttributeCount;i++)
    {
    //Here the attribute count is 3
    }
</code>```

Java Code:

```<code>    for (int i = 0; i < reader.getAttributeCount(); i++) {
    //Here the attribute count is 1  }
</code>```

I have included a wrapper class for “XmlReader” to process attributes as in C# . Please refer the  wrapper method I have used to retrieve attribute count to meet c# behavior.

Java:

```<code>    public int getAttributeCount()
    {
    if (_reader.getEventType() == XMLStreamConstants.START_ELEMENT
            || _reader.getEventType() == XMLStreamConstants.ATTRIBUTE) {
        int i = 0;
        i = _reader.getAttributeCount();
        if (_reader.getNamespaceCount() > 0) {
            i += _reader.getNamespaceCount();

        }
        return i; //now the count will be 3.
        } else {
        return 0;
        }
        }
</code>```

My concern is I would like to know how to read the element”book” attributes in order as in C#. Since ‘xmlns’ tag is considered as namespace, it is only possible to process namespace and attribute separately and it’s difficult to know which is in first while iterating the attribute count. Kindly let me know your suggestions in this?

答:
You can't ask "are namespace declarations considered to be attributes in Java" because Java provides many libraries and models for processing XML, and they are all different.

In the DOM, which is available in slightly different form on many platforms including Java and C#, namespace declarations are treated as attributes. But the DOM is ancient and predates namespaces, and there are many more modern APIs for processing XML in Java. You example uses StAX; there is also SAX, JDOM2, XOM, etc etc. In most of the more modern models, namespaces and attributes are treated as separate things, so counting attributes will not include the namespace declarations.

Body:
My background in C#. I am facing behavioral difference while retrieving attribute count in JAVA compared to C#.

XML:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <book xmlns:v="urn:schemas-microsoft-com:vml" style="width:149.65pt"
    xmlns:w="urn:schemas-microsoft-com:office:office">
    <v:object w:dxaOrig="1440" w:dyaOrig="1440">
    </v:object>
    </book>

In C#, the ‘Xmlns’ tag is considered as the attribute and hence while retrieving the attribute count the value is 3 for the above Xml element ‘book’. Whereas in JAVA (as per my understating, correct me if am wrong) ‘Xmlns’ is not an attribute, it is used as namespace declaration and it is also considered as reserved XML  pseudo-attribute to declare a namespace. So the attribute count for above case will be 1 in JAVA. I can retrieve the ‘xmlns’ tag as namespace count which is 2.

C# Code:

    for(int i=0;i<reader.AttributeCount;i++)
    {
    //Here the attribute count is 3
    }

Java Code:

    for (int i = 0; i < reader.getAttributeCount(); i++) {
    //Here the attribute count is 1  }

I have included a wrapper class for “XmlReader” to process attributes as in C# . Please refer the  wrapper method I have used to retrieve attribute count to meet c# behavior.

Java:

    public int getAttributeCount()
    {
    if (_reader.getEventType() == XMLStreamConstants.START_ELEMENT
            || _reader.getEventType() == XMLStreamConstants.ATTRIBUTE) {
        int i = 0;
        i = _reader.getAttributeCount();
        if (_reader.getNamespaceCount() > 0) {
            i += _reader.getNamespaceCount();

        }
        return i; //now the count will be 3.
        } else {
        return 0;
        }
        }

My concern is I would like to know how to read the element”book” attributes in order as in C#. Since ‘xmlns’ tag is considered as namespace, it is only possible to process namespace and attribute separately and it’s difficult to know which is in first while iterating the attribute count. Kindly let me know your suggestions in this?


问:
Context switch in Interrupt handlers
Why can't a context switch happen when an interrupt handler is executing ? More specifically, in the linux kernel, interrupt handlers run in the context of the process that was interrupted. Why is it not possible to do a context switch in the interrupt handler to schedule another process ?</p>

答:
On a multiprocessor, a context switch can certainly happen while an interrupt handler is executing. In fact, it would be difficult to prevent.

On a single-CPU machine, by definition it can only be running one thread of control at a time. It only has one register set, one ALU, etc. So if the interrupt handler is running there simply are no resources with which to execute a context switch.

Now, if you mean, can the interrupt handler actually call the context switch code and make one happen, well, I suppose on some systems that could be made to work. But for most, this wouldn't have much value and would be difficult to arrange. The CPU is running at elevated priority, and this priority cannot be lowered or synchronization between interrupt levels is lost. Critical sections in the OS are already synchronizing against interrupt execution and this would introduce complexities. Furthermore, a context switch happens by changing stacks, much like in a threaded user mode program, so it's hard to imagine how this might happen when the interrupt stack is needed for a return from the interrupt.

Title: Context switch in Interrupt handlers


答:
If your image is of a proper size, you can set it as a background for that particular "a" tag.

So it should be something like this:

```<code><li><a  class="funImage" href="" target="_blank"></a></li>
</code>```

And then in your css you could do something like this:

```<code>.funImage{display: inline-block;
          background-image: url("bilde.png");
          height: /*Set height accordingly*/;
          width: /*Set width accordingly*/;
         }
</code>```

Hope that works :)

Title: How can I make an image function as a button, and make it perform an action when clicked ( start a keyframe event, run a script)?

Body:
If your image is of a proper size, you can set it as a background for that particular "a" tag.

So it should be something like this:

<li><a  class="funImage" href="" target="_blank"></a></li>

And then in your css you could do something like this:

.funImage{display: inline-block;
          background-image: url("bilde.png");
          height: /*Set height accordingly*/;
          width: /*Set width accordingly*/;
         }

Hope that works :)