问:
RuntimeException when trying to shape corner of Cardview
I have a CardView and I wanted to shape the corners of the cardview, I found a xml code snippet here and added it to my cardview and get this error, please look at the comment in the test.xml layout

EDIT: When I change background of the cardview to "#ffffff" (white) it works. It only crashes when I use  card_view:cardBackgroundColor="@drawable/ic_corner_color"

EDIT 2: I want the corners look like this in the picture in the question, click

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.app/com.example.user.app.Test}: android.view.InflateException: Binary XML file line #14: Error inflating class android.support.v7.widget.CardView

This is my test.xml layout

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:tag="cards main container">

        <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_viewtest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            card_view:cardBackgroundColor="@drawable/ic_corner_color" **// here is the error**
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="5dp"
            card_view:cardUseCompatPadding="true"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="12dp"
                    android:layout_weight="2"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <android.support.v7.widget.Toolbar
                        android:id="@+id/toolbar2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.96"
                        android:background="#ffffff"
                        android:minHeight="?attr/actionBarSize"
                        android:theme="?attr/actionBarTheme">

                        <ImageView
                            android:id="@+id/imageViewtest"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_margin="5dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_drive_eta_black_24dp"
                            android:tag="image_tag" />

                    </android.support.v7.widget.Toolbar>

                    <TextView
                        android:id="@+id/textViewNametest"
                        android:layout_width="340dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="10dp"

                        android:layout_weight="0.96"
                        android:text="some
                        android:textAppearance="?android:attr/textAppearanceLarge" />

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</ScrollView>
</code>```

My ic_corner_color.xml, which is in the drawable folder, looks like this:

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#ffffff" />
<stroke android:width="1dip" android:color="#00ff00"/>
<corners android:radius="20dip"/>
</code>```

答: I'm fairly sure cardBackgroundColor expects a color, not a drawable. Change it to @color/mycolor.

Body:
I have a CardView and I wanted to shape the corners of the cardview, I found a xml code snippet here and added it to my cardview and get this error, please look at the comment in the test.xml layout

EDIT: When I change background of the cardview to "#ffffff" (white) it works. It only crashes when I use  card_view:cardBackgroundColor="@drawable/ic_corner_color"

EDIT 2: I want the corners look like this in the picture in the question, click

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.app/com.example.user.app.Test}: android.view.InflateException: Binary XML file line #14: Error inflating class android.support.v7.widget.CardView

This is my test.xml layout

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:tag="cards main container">

        <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_viewtest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            card_view:cardBackgroundColor="@drawable/ic_corner_color" **// here is the error**
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="5dp"
            card_view:cardUseCompatPadding="true"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="12dp"
                    android:layout_weight="2"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <android.support.v7.widget.Toolbar
                        android:id="@+id/toolbar2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.96"
                        android:background="#ffffff"
                        android:minHeight="?attr/actionBarSize"
                        android:theme="?attr/actionBarTheme">

                        <ImageView
                            android:id="@+id/imageViewtest"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_margin="5dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_drive_eta_black_24dp"
                            android:tag="image_tag" />

                    </android.support.v7.widget.Toolbar>

                    <TextView
                        android:id="@+id/textViewNametest"
                        android:layout_width="340dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="10dp"

                        android:layout_weight="0.96"
                        android:text="some
                        android:textAppearance="?android:attr/textAppearanceLarge" />

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</ScrollView>

My ic_corner_color.xml, which is in the drawable folder, looks like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#ffffff" />
<stroke android:width="1dip" android:color="#00ff00"/>
<corners android:radius="20dip"/>


来源: stackexchange

问:
How to change a text based onclick with JavaScript?
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

```<code><p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func();">ES</a> - <a href="#" id="EN" onclick="func();">EN</a> - <a href="#" id="JP" onclick="func();">JP</a>
</code>```

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

答:
Pass this to you function for get clicked element.

Then set it's id to you p tag using innerHTML.

See e.g.

function func(ele){
    var demo = document.getElementById('demo');
    demo.innerHTML = "This message should be edited to "+ele.id+".";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo">This message should be edited.<p>
ES - EN - JP</code>```

ContentLicense: CC BY-SA 3.0

Body:
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

This message should be edited.

ES - EN - JP

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

Body:
Pass this to you function for get clicked element.

Then set it's id to you p tag using innerHTML.

See e.g.

function func(ele){
    var demo = document.getElementById('demo');
    demo.innerHTML = "This message should be edited to "+ele.id+".";
}

<p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func(this);">ES</a> - <a href="#" id="EN" onclick="func(this);">EN</a> - <a href="#" id="JP" onclick="func(this);">JP</a>


问:
Accessing the Vue within jquery ajax
I have a vue object and in the mounted method I test for a scroll event on the browser

```<code>mounted() {

self= this;

 $(window).scroll(function(){
          $.get("/works?start="+$('#loaded_max').val(), function(loaded){
            self.work = loaded;
            console.log(self);
          });

    });
</code>```

console.log(self) //returns window

console.log(this) //returns ajax

How do I access the vue object? Specifically the data so I can update the variable.

答:
Self appears to be window, any other variable works

so

```<code> mounted() {

let myvue = this;

 $(window).scroll(function(){
          $.get("/works?start="+$('#loaded_max').val(), function(loaded){
            myvue.work = loaded;
            console.log(myvue.work);
          });

    });
</code>```

I have always used that technique to reference the 'current object' when scope is an issue but it obviously has issues when you need to reference something other than the window.

Title: Accessing the Vue within jquery ajax

Body:
I have a vue object and in the mounted method I test for a scroll event on the browser

mounted() {

self= this;

 $(window).scroll(function(){
          $.get("/works?start="+$('#loaded_max').val(), function(loaded){
            self.work = loaded;
            console.log(self);
          });

    });

console.log(self) //returns window

console.log(this) //returns ajax

How do I access the vue object? Specifically the data so I can update the variable.

Body:
Self appears to be window, any other variable works

so

 mounted() {

let myvue = this;

 $(window).scroll(function(){
          $.get("/works?start="+$('#loaded_max').val(), function(loaded){
            myvue.work = loaded;
            console.log(myvue.work);
          });

    });

I have always used that technique to reference the 'current object' when scope is an issue but it obviously has issues when you need to reference something other than the window.


问:
how to get values from the array with the help of for loop
In my ios app,
i have some data in one array,now i want to print that data with the help of NSlog in viewdidload , but i want to show that data inside one for loop...so i didn't get what should be my for loop.

i want to get values from the array with the help of using for...loop... how can i do that ?

```<code>storedDataArray = [[NSMutableArray alloc]init];

[storedDataArray addObject:@"Kaushal"];

[storedDataArray addObject:@"Bhaumik"];

[storedDataArray addObject:@"Arpit"];

[storedDataArray addObject:@"Swapnil"];

[storedDataArray addObject:@"Megha"];

[storedDataArray addObject:@"Ravi"];

for (int i=0; i<=6; i++) {
    NSLog(@"hello %d",storedDataArray);
}
</code>```

答:
is not

```<code>for (int i=0; i<=6; i++) {
NSLog(@"hello %d",storedDataArray);
}
</code>```

it is

```<code>for (int i=0; i<storedDataArray.count; i++) {
NSLog(@"hello %@",storedDataArray[i]);
}
</code>```

fast enumration

```<code>for (NSString *name in storedDataArray) {
NSLog(@"hello %@",name);
}
</code>```

Body:
In my ios app,
i have some data in one array,now i want to print that data with the help of NSlog in viewdidload , but i want to show that data inside one for loop...so i didn't get what should be my for loop.

i want to get values from the array with the help of using for...loop... how can i do that ?

storedDataArray = [[NSMutableArray alloc]init];

[storedDataArray addObject:@"Kaushal"];

[storedDataArray addObject:@"Bhaumik"];

[storedDataArray addObject:@"Arpit"];

[storedDataArray addObject:@"Swapnil"];

[storedDataArray addObject:@"Megha"];

[storedDataArray addObject:@"Ravi"];

for (int i=0; i<=6; i++) {
    NSLog(@"hello %d",storedDataArray);
}

Body:
is not

for (int i=0; i<=6; i++) {
NSLog(@"hello %d",storedDataArray);
}

it is

for (int i=0; i<storedDataArray.count; i++) {
NSLog(@"hello %@",storedDataArray[i]);
}

fast enumration

for (NSString *name in storedDataArray) {
NSLog(@"hello %@",name);
}


问:
How can I store firebase user's uid in React?
I'm working on a react web application where users can sign up with an email and a password. After signing up, each user will have access to their profile data. Below is a my firebase data structure:

```<code>users:{
   generatedUserUID:{
            name: "User1"
            profileImage: "http://via.placeholder.com/350x150"
            }
     }
</code>```

What would be the best way to store the user's uid when the user is signed in so that it can be used throughout the project. Currently, I'm using the browser's localStorage, but I'm concerned that if the client browser doesn't support localStorage then the app will be rendered useless. So, I'm looking for an alternative and not have to depend on localStorage entirely. Any help is appreciated. Thank you.

答:
You could use a library like Redux to manage data in your application. Redux helps you manage the state of your application.

More info here : http://redux.js.org/docs/basics/UsageWithReact.html

Body:
I'm working on a react web application where users can sign up with an email and a password. After signing up, each user will have access to their profile data. Below is a my firebase data structure:

users:{
   generatedUserUID:{
            name: "User1"
            profileImage: "http://via.placeholder.com/350x150"
            }
     }

What would be the best way to store the user's uid when the user is signed in so that it can be used throughout the project. Currently, I'm using the browser's localStorage, but I'm concerned that if the client browser doesn't support localStorage then the app will be rendered useless. So, I'm looking for an alternative and not have to depend on localStorage entirely. Any help is appreciated. Thank you.


问:
Docker failing to load apparmor profile upon ubuntu host boot
I have a container x that fails to start automatically upon host boot.

The last message in the container's log is:

set apparmor profile docker-default: no such file or directory

The same container x runs fine if I manually run "docker start x"

Any ideas on what's wrong with my environment ?

答:
Apparently, installing apparmor is not enough, since the problem happens even with apparmor installed. More exactly, the error happens because of the docker daemon being loaded before apparmor set its config as explained here.

Full solution:

```<code>sudo apt-get install apparmor
</code>```

and:

```<code>sudo service apparmor restart # Just in case
sudo service docker restart
</code>```

Should work after that. At least, for me it did.

Body:
Apparently, installing apparmor is not enough, since the problem happens even with apparmor installed. More exactly, the error happens because of the docker daemon being loaded before apparmor set its config as explained here.

Full solution:

sudo apt-get install apparmor

and:

sudo service apparmor restart # Just in case
sudo service docker restart

Should work after that. At least, for me it did.


问:
Why does Axios (with async/await) return a full promise?
I have a problem with async/await. Here is my code:

import axios from 'axios'

export default async function getRequestedData (requestAddress, params) {
   return await axios.get(requestAddress, {params: params})
}```

But instead of the result it returns a full promise, so the data is heavily nested inside a promise:

答:
You have to return the data:</p>

```<code>const response = await axios.get(requestAddress, {params: params})
return response.data;
</code>```

Body:
I have a problem with async/await. Here is my code:

import axios from 'axios'

export default async function getRequestedData (requestAddress, params) {
   return await axios.get(requestAddress, {params: params})
}

But instead of the result it returns a full promise, so the data is heavily nested inside a promise:

Body:
You have to return the data:

const response = await axios.get(requestAddress, {params: params})
return response.data;


问:
End loop with counter and condition
In Python I can implement a loop with step counter and a stop condition as a classical case of for loop :

```<code>for i in range(50):
    result = fun(i)
    print(i, result)
    if result == 0:
        break
</code>```

where fun(x) is some arbitrary function from integers to integers.

I always in doubts if that is the best way to code it (Pythonically, and in terms of readability and efficiency) or is it better to run it as a while loop:

```<code>i = 0
result = 1
while result != 0 and i < 50:
    result = fun(i)
    print(i, result)
    i += 1
</code>```

which approach is better? In particular - I'm concerned about the usage of break statement which doesn't feel right.

答:
There is a minute difference in performance. As the while loop performs an extra boolean check at every iteration, it is slightly slower.

However, for most functions you would like to assess, there is an alternative to using a loop in the first place, which is way faster. See example attached below. And I am certain there are more optimal implementations..

```<code>import time

def fun(step):
    return step == 50000000

t1 = time.time()
for i in range(500000000):
    result = fun(i)
#    print(i, result)
    if result == 1:
        break
print("time elapsed", time.time() - t1)

t2 = time.time()
i = 0
result = 0
while result != 1 and i < 50000000:
    result = fun(i)
#    print(i, result)
    i += 1

print("and here", time.time() - t2)

import numpy as np

t3 = time.time()

foo = np.arange(500000000)
i = np.where(foo == 50000000)
print("Alternative", time.time()-t3)
</code>```

time elapsed 11.082087516784668

and here 14.429940938949585

Alternative 1.4022133350372314

If you want to/have to use a loop however, the for-loop is in general the more Pythonic way to go, as is explained in this nice answer to a related question

EDIT: Chris Rands's answer below explains it from the C-code point of view, and uses a more accurate (although on such macro-levels as I forced this example to be, that would not really matter) timing module. Do read his answer as well.

Title: End loop with counter and condition

Body:
In Python I can implement a loop with step counter and a stop condition as a classical case of for loop :

for i in range(50):
    result = fun(i)
    print(i, result)
    if result == 0:
        break

where fun(x) is some arbitrary function from integers to integers.

I always in doubts if that is the best way to code it (Pythonically, and in terms of readability and efficiency) or is it better to run it as a while loop:

i = 0
result = 1
while result != 0 and i < 50:
    result = fun(i)
    print(i, result)
    i += 1

which approach is better? In particular - I'm concerned about the usage of break statement which doesn't feel right.

Body:
There is a minute difference in performance. As the while loop performs an extra boolean check at every iteration, it is slightly slower.

However, for most functions you would like to assess, there is an alternative to using a loop in the first place, which is way faster. See example attached below. And I am certain there are more optimal implementations..

import time

def fun(step):
    return step == 50000000

t1 = time.time()
for i in range(500000000):
    result = fun(i)
#    print(i, result)
    if result == 1:
        break
print("time elapsed", time.time() - t1)

t2 = time.time()
i = 0
result = 0
while result != 1 and i < 50000000:
    result = fun(i)
#    print(i, result)
    i += 1

print("and here", time.time() - t2)

import numpy as np

t3 = time.time()

foo = np.arange(500000000)
i = np.where(foo == 50000000)
print("Alternative", time.time()-t3)

time elapsed 11.082087516784668

and here 14.429940938949585

Alternative 1.4022133350372314

If you want to/have to use a loop however, the for-loop is in general the more Pythonic way to go, as is explained in this nice answer to a related question

EDIT: Chris Rands's answer below explains it from the C-code point of view, and uses a more accurate (although on such macro-levels as I forced this example to be, that would not really matter) timing module. Do read his answer as well.


问:
PostgreSQL: find out if a row has been created by the current transaction
Is it possible to find out if a row in a table has been created by the current transaction (and therefore is not yet visible for other transactions, because the current transaction is still active)?

My use case: I am adding event logging to the database. This is done in plpgsql triggers. A row in the event table looks like this: (event id:serial, event action:text, count:integer:default 1).

Now, the reasoning behind my question: If a certain row has been created by this transaction (most likely in another trigger), I could increment the count instead of creating a new row in the event table.

答:
You could just look for logging entries like this:

```<code>SELECT ...
FROM tablename
WHERE xmin = current_txid() % (2^32)::bigint;
</code>```

That will find all rows added or modified in the current transaction.

The downside is that this will force a sequential scan of the whole table, and you cannot avoid that since you cannot have an index on a system column.

So you could add an extra column xid to your table that is filled with txid_current()::bigint whenever a row is inserted or updated. Such a column can be indexed and efficiently used in a search:

```<code>SELECT ...
FROM tablename
WHERE xid = current_txid();
</code>```

Body:
You could just look for logging entries like this:

SELECT ...
FROM tablename
WHERE xmin = current_txid() % (2^32)::bigint;

That will find all rows added or modified in the current transaction.

The downside is that this will force a sequential scan of the whole table, and you cannot avoid that since you cannot have an index on a system column.

So you could add an extra column xid to your table that is filled with txid_current()::bigint whenever a row is inserted or updated. Such a column can be indexed and efficiently used in a search:

SELECT ...
FROM tablename
WHERE xid = current_txid();


问:
Can RxJava and RxJava 2 coexist in the same Android project?
I have a project that uses RxJava 1. Now I'm building a module component, and thinking of starting with RxJava 2.

When perform gradle sync, all good. However during compilation I got the following error

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForProductionDebug'.
  com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
      File1: /Users/user.name/.gradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.2.5/b423532b5a3c949cbb799468f83bf566032fe98d/rxjava-1.2.5.jar
      File2: /Users/user.name/.gradle/caches/modules-2/files-2.1/io.reactivex.rxjava2/rxjava/2.0.1/57f850a6b317e5582f1dbaff10a9e7d7e1fcdcfb/rxjava-2.0.1.jar

Is there anyway I could have them coexist in a single project (but different library), or this is a definitely no-no?

i.e. on one, I have

```<code>compile 'io.reactivex:rxjava:1.2.5'
compile 'io.reactivex:rxandroid:1.2.1'
</code>```

on the other one I have

```<code>compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
</code>```

答:
You need to exclude some rx properties.
Add this:

```<code>android {
...
packagingOptions {
    exclude 'META-INF/rxjava.properties'
    }
}
</code>```

To your app build gradle

Body:
I have a project that uses RxJava 1. Now I'm building a module component, and thinking of starting with RxJava 2.

When perform gradle sync, all good. However during compilation I got the following error

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForProductionDebug'.
  com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
      File1: /Users/user.name/.gradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.2.5/b423532b5a3c949cbb799468f83bf566032fe98d/rxjava-1.2.5.jar
      File2: /Users/user.name/.gradle/caches/modules-2/files-2.1/io.reactivex.rxjava2/rxjava/2.0.1/57f850a6b317e5582f1dbaff10a9e7d7e1fcdcfb/rxjava-2.0.1.jar

Is there anyway I could have them coexist in a single project (but different library), or this is a definitely no-no?

i.e. on one, I have

compile 'io.reactivex:rxjava:1.2.5'
compile 'io.reactivex:rxandroid:1.2.1'

on the other one I have

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

Body:
You need to exclude some rx properties.
Add this:

android {
...
packagingOptions {
    exclude 'META-INF/rxjava.properties'
    }
}

To your app build gradle


问:
how to use an array in php mysql query?
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

```<code>$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";
</code>```

Can anyone help me with this?

答:
Always use prepared statements to prevent SQL injection. The following code can be used as a starting point to solve your problem (needs the PDO library, http://php.net/manual/en/book.pdo.php).</p>

```<code>$user_query = $_REQUEST['user_query'];                      // you should better use $_GET or $_POST explicitly
$user_query = preg_replace('#\s{2,}#', ' ', $user_query);   // replace multiple spaces with a single space
$keywords = explode(' ', $user_query);                      // create the keywords array
$placeholders = array_fill(0, count($keywords), '?');       // create the placeholders array

$sql = 'SELECT *
        FROM sites
        WHERE site_keywords IN (' . implode(', ', $placeholders) . ')
        ORDER BY rank DESC';

$stmt = $db->prepare($sql);
$stmt->execute($keywords);
$result = $stmt->fetchAll();
</code>```

Title: how to use an array in php mysql query?

Body:
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Can anyone help me with this?

Body:
Always use prepared statements to prevent SQL injection. The following code can be used as a starting point to solve your problem (needs the PDO library, http://php.net/manual/en/book.pdo.php).

$user_query = $_REQUEST['user_query'];                      // you should better use $_GET or $_POST explicitly
$user_query = preg_replace('#\s{2,}#', ' ', $user_query);   // replace multiple spaces with a single space
$keywords = explode(' ', $user_query);                      // create the keywords array
$placeholders = array_fill(0, count($keywords), '?');       // create the placeholders array

$sql = 'SELECT *
        FROM sites
        WHERE site_keywords IN (' . implode(', ', $placeholders) . ')
        ORDER BY rank DESC';

$stmt = $db->prepare($sql);
$stmt->execute($keywords);
$result = $stmt->fetchAll();


问:
Wrap code to a usable method in Android
am trying to create a clickable text amidst so block of text, i was lucky to find out the code on stackoverflow that works for me, but the issue is that have many other text where i want to apply the clicking. my question now is that if it's possible to bundle the below code in a reuse-able method that i can call and pass the needed parameters and how

```<code>SpannableString ss = new SpannableString("Android is a Software stack");
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            startActivity(new Intent(MainActivity.this, NextActivity.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(clickableSpan, 10, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new StyleSpan(Typeface.ITALIC), 10, 27, 0);

    TextView textView = (TextView) findViewById(R.id.hello);
    textView.setText(ss);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setHighlightColor(Color.TRANSPARENT);
</code>```

Below is what i have resolve to use, any suggestion on how to make it better?

```<code>    TextView textView = (TextView) findViewById(R.id.one) ;
    String s="This link has many clickable text which are link one, link two
    and the last whick is link three";
    SpannableString ss = new SpannableString(s);
    String one ="link one";
    String two ="link two";
    String three ="link three";
    int firstIndex = s.indexOf(one);
    int secondIndex = s.indexOf(two);
    int thirdIndex = s.indexOf(three);

    ClickableSpan firstClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(MainActivity.this, a.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ClickableSpan secondClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(MainActivity.this, b.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ClickableSpan thirdClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(MainActivity.this, c.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(firstClick,firstIndex, firstIndex+one.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(secondClick,secondIndex, secondIndex+two.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(thirdClick,thirdIndex, thirdIndex+three.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setLinksClickable(true);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(ss, TextView.BufferType.SPANNABLE);
</code>```

答:
Assuming you always need to start some Activity when the user clicks a part of text, it could look like that:

```<code>@UiThread
public static void setClickable(@NonNull TextView tv,
                                @NonNull SpannableString ss,
                                int start, int end,
                                @NonNull final Context from, @NonNull final Class to){

    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            from.startActivity(new Intent(from, to));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new StyleSpan(Typeface.ITALIC), start, end, 0);
    tv.setText(ss);
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    tv.setHighlightColor(Color.TRANSPARENT);
}
</code>```

Usage example (based on your given use-case, called from an Activity):

```<code>    SpannableString ss = new SpannableString("Android is a Software stack");
    TextView textView = (TextView) findViewById(R.id.hello);
    setClickable(textView, ss, 10, 27, this, NextActivity.class);
</code>```

Notes: Context.startActivity() is available starting with API 16, below that API you'd need to use an Activity instance instead of Context. Also feel free to add/remove the parameters accodring to your needs. The example above will work from any class and aims to give you some basic idea how to implement what you need.

Title: Wrap code to a usable method in Android

Body:
am trying to create a clickable text amidst so block of text, i was lucky to find out the code on stackoverflow that works for me, but the issue is that have many other text where i want to apply the clicking. my question now is that if it's possible to bundle the below code in a reuse-able method that i can call and pass the needed parameters and how

SpannableString ss = new SpannableString("Android is a Software stack");
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            startActivity(new Intent(MainActivity.this, NextActivity.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(clickableSpan, 10, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new StyleSpan(Typeface.ITALIC), 10, 27, 0);

    TextView textView = (TextView) findViewById(R.id.hello);
    textView.setText(ss);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setHighlightColor(Color.TRANSPARENT);

Below is what i have resolve to use, any suggestion on how to make it better?

    TextView textView = (TextView) findViewById(R.id.one) ;
    String s="This link has many clickable text which are link one, link two
    and the last whick is link three";
    SpannableString ss = new SpannableString(s);
    String one ="link one";
    String two ="link two";
    String three ="link three";
    int firstIndex = s.indexOf(one);
    int secondIndex = s.indexOf(two);
    int thirdIndex = s.indexOf(three);

    ClickableSpan firstClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(MainActivity.this, a.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ClickableSpan secondClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(MainActivity.this, b.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ClickableSpan thirdClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(MainActivity.this, c.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(firstClick,firstIndex, firstIndex+one.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(secondClick,secondIndex, secondIndex+two.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(thirdClick,thirdIndex, thirdIndex+three.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setLinksClickable(true);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(ss, TextView.BufferType.SPANNABLE);

Body:
Assuming you always need to start some Activity when the user clicks a part of text, it could look like that:

@UiThread
public static void setClickable(@NonNull TextView tv,
                                @NonNull SpannableString ss,
                                int start, int end,
                                @NonNull final Context from, @NonNull final Class to){

    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            from.startActivity(new Intent(from, to));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new StyleSpan(Typeface.ITALIC), start, end, 0);
    tv.setText(ss);
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    tv.setHighlightColor(Color.TRANSPARENT);
}

Usage example (based on your given use-case, called from an Activity):

    SpannableString ss = new SpannableString("Android is a Software stack");
    TextView textView = (TextView) findViewById(R.id.hello);
    setClickable(textView, ss, 10, 27, this, NextActivity.class);

Notes: Context.startActivity() is available starting with API 16, below that API you'd need to use an Activity instance instead of Context. Also feel free to add/remove the parameters accodring to your needs. The example above will work from any class and aims to give you some basic idea how to implement what you need.


问:
Send a file from facebook messenger (api.ai)
I'm creating a bot for facebook messenger with api.ai,in the doc says that i must to write the following code on the 'custom payload' option:

```<code>"message":{
    "attachment":{
      "type":"file",
      "payload":{
        "url":"https://petersapparel.com/bin/receipt.pdf"
      }
    }
}
</code>```

but it doesnt work, someone know if I missed something? The url that I use works correctly.

答:
Have you tried the sample in dev docs?

https://developers.facebook.com/docs/messenger-platform/send-api-reference/file-attachment

```<code>curl -X POST -H "Content-Type: application/json" -d '{
  "recipient":{
    "id":"USER_ID"
  },
  "message":{
    "attachment":{
      "type":"file",
      "payload":{
        "url":"https://petersapparel.com/bin/receipt.pdf"
      }
    }
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"
</code>```

Body:
I'm creating a bot for facebook messenger with api.ai,in the doc says that i must to write the following code on the 'custom payload' option:

"message":{
    "attachment":{
      "type":"file",
      "payload":{
        "url":"https://petersapparel.com/bin/receipt.pdf"
      }
    }
}

but it doesnt work, someone know if I missed something? The url that I use works correctly.

Body:
Have you tried the sample in dev docs?

https://developers.facebook.com/docs/messenger-platform/send-api-reference/file-attachment

curl -X POST -H "Content-Type: application/json" -d '{
  "recipient":{
    "id":"USER_ID"
  },
  "message":{
    "attachment":{
      "type":"file",
      "payload":{
        "url":"https://petersapparel.com/bin/receipt.pdf"
      }
    }
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"


问:
How does SPARK read data and manage in Memory
Can anyone please help me understanding how does SPARK read hdfs data and manage it in main memory?

In other words,

If I create 3 RDD, first RDD from hadoop file and do some transformation on it and create a second RDD and again do some transformation on the 2nd RDD and create a 3rd RDD then call some action on 3rd RDD.

How many times data will be read from hdfs?

Will all three RDD data stay in Memory if we don't call the cache or persist explicitly? i.e. when an action is executing on the 3rd RDD that time whether 1st RDD data remains in memory

答: If you don't cache RDD3 then Spark will read data from HDFS otherwise it will read from memory.</p>


问:
Trying to avoid nesting Select statements but getting error "Conversion failed when converting the varchar value to datatype int"
The first part of my code below defines the field 'LCO'.  I am trying to use that field in the second part to check if result of the SELECT is greater than the 'LCO' corresponding field.

```<code>SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT
         ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                 FROM M1_HB.dbo.JobOperations JobOperations
                 WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                   AND JobOperations.jmoProductionComplete = -1
                 ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
    FROM M1_HB.dbo.WorkCenters WorkCenters,
         M1_Hb.dbo.JobOperations JobOperations
    WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
      AND JobOperations.jmoProductionComplete=0
      AND JobOperations.jmoJobID =Jobs.jmpJobID
      AND JobOperations.jmoJobOperationID > 'LCO'
    ORDER BY JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID
</code>```

I am getting an error

Conversion failed when converting the varchar value to datatype int

If I nest the first SELECT into the second (ie replace > 'LCO' with > (Select Isnull((Select Top 1 .....)) like below then it works.

```<code>SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                    FROM M1_HB.dbo.JobOperations JobOperations
                    WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                      AND JobOperations.jmoProductionComplete = -1
                    ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
     FROM M1_HB.dbo.WorkCenters WorkCenters,
          M1_Hb.dbo.JobOperations JobOperations
     WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
       AND JobOperations.jmoProductionComplete = 0
       AND JobOperations.jmoJobID = Jobs.jmpJobID
       AND JobOperations.jmoJobOperationID > (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                                                             FROM M1_HB.dbo.JobOperations JobOperations
                                                             WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                                                               AND JobOperations.jmoProductionComplete = -1
                                                             ORDER BY JobOperations.jmoJobOperationID DESC), 0))
     ORDER BY
         JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID
</code>```

What do I need to do to my first code to make it work?  I tried using CAST() in various ways, but without success

答: First of all, AND JobOperations.jmoJobOperationID > 'LCO' tries to compare the obviously int value jmoJobOperationID against the string 'LCO' and for this tries to convert 'LCO' to int - therefore the error message. Furthermore, you can not access an alias of a column in the same query in which the alias is defined. Last but not least, why don't you want to use nested queries?

Body:
The first part of my code below defines the field 'LCO'.  I am trying to use that field in the second part to check if result of the SELECT is greater than the 'LCO' corresponding field.

SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT
         ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                 FROM M1_HB.dbo.JobOperations JobOperations
                 WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                   AND JobOperations.jmoProductionComplete = -1
                 ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
    FROM M1_HB.dbo.WorkCenters WorkCenters,
         M1_Hb.dbo.JobOperations JobOperations
    WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
      AND JobOperations.jmoProductionComplete=0
      AND JobOperations.jmoJobID =Jobs.jmpJobID
      AND JobOperations.jmoJobOperationID > 'LCO'
    ORDER BY JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID

I am getting an error

Conversion failed when converting the varchar value to datatype int

If I nest the first SELECT into the second (ie replace > 'LCO' with > (Select Isnull((Select Top 1 .....)) like below then it works.

SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                    FROM M1_HB.dbo.JobOperations JobOperations
                    WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                      AND JobOperations.jmoProductionComplete = -1
                    ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
     FROM M1_HB.dbo.WorkCenters WorkCenters,
          M1_Hb.dbo.JobOperations JobOperations
     WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
       AND JobOperations.jmoProductionComplete = 0
       AND JobOperations.jmoJobID = Jobs.jmpJobID
       AND JobOperations.jmoJobOperationID > (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                                                             FROM M1_HB.dbo.JobOperations JobOperations
                                                             WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                                                               AND JobOperations.jmoProductionComplete = -1
                                                             ORDER BY JobOperations.jmoJobOperationID DESC), 0))
     ORDER BY
         JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID

What do I need to do to my first code to make it work?  I tried using CAST() in various ways, but without success


问:
Apple Pay with Woocommerce (Stripe) "Unable to verify domain - Forbidden"
Everything is setup and I have .well-known folder in my root directory with file.

My Stripe account is activated and my domain is added under Apple Pay tab.

Now when I enable Stripe, I get this notification:

Apple Pay domain verification failed. Please check the log to see the
  issue.

When I check the error log, I see:

Error: Unable to verify domain - Forbidden

My hosting is on OVH.

答:
Have you added Domain Verification file into the .well-known/ folder.

If not please find it in your Stripe dashboard download it or here and upload to .well-known/ folder.

Make sure that you need to access your verification file by your URL https://example.com/.well-known/apple-developer-merchantid-domain-association


问:
Gradle how to use plugin in an included common build script
project A:

```<code>   apply from : 'common.gradle'
</code>```

common.gradle

```<code>plugins {
    id 'com.eriwen.gradle.js' version '2.14.1'
}

apply plugin: 'js'

import com.eriwen.gradle.js.tasks.MinifyJsTask;

task minify(type: MinifyJsTask) {
   ...
}
</code>```

Error

```<code>Only Project build scripts can contain plugins {} blocks
</code>```

If the plugins block moved to project A,

Error

```<code>unable to resolve class com.eriwen.gradle.js.tasks.MinifyJsTask
</code>```

How to use an plugin (from public responsitory) in an included build script (called script plugin)?

答:
Here is one way to do it. (I used this page as a resource, but not sure if it is still accurate.) With Gradle 4.0:

Given build.gradle:

```<code>apply from: 'common.gradle'
</code>```

here is common.gradle:

```<code>buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "com.eriwen:gradle-js-plugin:2.14.1"
  }
}

apply plugin: com.eriwen.gradle.js.JsPlugin

task minify(type: com.eriwen.gradle.js.tasks.MinifyJsTask) {
    // ...
}
</code>```

Body:
project A:

   apply from : 'common.gradle'

common.gradle

plugins {
    id 'com.eriwen.gradle.js' version '2.14.1'
}

apply plugin: 'js'

import com.eriwen.gradle.js.tasks.MinifyJsTask;

task minify(type: MinifyJsTask) {
   ...
}

Error

Only Project build scripts can contain plugins {} blocks

If the plugins block moved to project A,

Error

unable to resolve class com.eriwen.gradle.js.tasks.MinifyJsTask

How to use an plugin (from public responsitory) in an included build script (called script plugin)?

Body:
Here is one way to do it. (I used this page as a resource, but not sure if it is still accurate.) With Gradle 4.0:

Given build.gradle:

apply from: 'common.gradle'

here is common.gradle:

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "com.eriwen:gradle-js-plugin:2.14.1"
  }
}

apply plugin: com.eriwen.gradle.js.JsPlugin

task minify(type: com.eriwen.gradle.js.tasks.MinifyJsTask) {
    // ...
}


问:
Java Play 2.2.6 : index.scala.html update not reflecting in controller.Application
I am new to Java Play and am working with version 2.2.6 as I'm on a windows machine and was unable to get the newest version working correctly.

I am working through the tutorial for version 2.2.6, here, and have encountered a problem in the section called "Rendering the First Page," located approximately two thirds of the way down in the tutorial.

The tutorial shows how to make a simple "to do list" application in Java Play which has a Form where the user can submit "to do" items, which then appear on screen, and also delete them.

In "Rendering the First Page," the tutorial instructs the user to add the following code to the controller "Application.java" :

```<code>public static Result tasks(){
    return ok(views.html.index.render(models.Task.all(), taskForm);
}
</code>```

So, at this point, my Application.java looks like this:

```<code>package controllers;

import java.util.ArrayList;
import java.util.List;

import com.sun.javafx.tk.Toolkit.Task;

import play.*;
import play.mvc.*;
import play.data.*;
import models.*;

import views.html.*;

public class Application extends Controller {

    static Form<Task> taskForm = Form.form(Task.class);

  public static Result index() {
    return ok("Hello World");
  }

  public static Result tasks() {
        return ok(
                views.html.index.render(models.Tasks.all(), taskForm)
                );
      }

  public static Result newTask() {
        return TODO;
      }

  public static Result deleteTask(Long id) {
        return TODO;
      }
}
</code>```

Eclipse immediately underlines the word "render" in red, and I get the following error when I hover over it: "the method render(String) in the type index is not applicable for the arguments (List, Form)"

The tutorial had me create a model called Task.java, and if you look at the top of Application.java, it also had me "import com.sun.javafx.tk.Toolkit.Task," which I'm not really sure what it does.

Here's my model, Task.java:

```<code>package models;

import java.util.*;

import play.data.validation.Constraints.*;

public class Task {

    public Long id;

    @Required
    public String label;

    public static List<Task> all(){
        return new ArrayList<Task>();
    }

    public static void create(Task task){

    }

    public static void delete(Long id){

    }
}
</code>```

So, all that being said, here's what I think the problem is:

"render"'s parameter(s) is/are defined in the view "index.scala.html", in scala

When you first create a blank Java application in java play, it auto-fills index.scala.html with the following lines of code:

```<code>@(message: String)

@main("Welcome to Play") {

    @play20.welcome(message, style = "Java")

}
</code>```

The tutorial had me delete all of that from index.scala.html, which like I said is a view, and had me replace it with this code:

```<code>@(tasks: List[Task], taskForm: Form[Task])

@import helper._

@main("Todo list") {

    <h1>@tasks.size() task(s)</h1>

    <ul>
        @for(task <- tasks) {
            <li>
                @task.label

                @form(routes.Application.deleteTask(task.id)) {
                    <input type="submit" value="Delete">
                }
            </li>
        }
    </ul>

    <h2>Add a new task</h2>

    @form(routes.Application.newTask()) {

        @inputText(taskForm("label"))

        <input type="submit" value="Create">

    }

}
</code>```

Now, the very first line in index.scala.html is what tells the controller what params "render" takes. As you can see, when you make a blank Java Play application, it starts out being @(message: String). I changed it to be @(tasks: List[Task], taskForm[Task]). So it should know that those are the params that "render" should take. But for some reason, it still thinks that "render" is supposed to take a String, and gives me an error.

I've been scouring the internet for hours and tried many solutions that have been offered before posting my own question.

Here's some things I've tried:

adding these lines to build.sbt (with spaces in between):

EclipseKeys.projectFlavor := EclipseProjectFlavor.Java

EclipseKeys.preTasks := Seq(compile in Compile)

and then closing out eclipse. from the command line in my project's directory, running "play clean-all" "play compile" "play eclipse", and then re-importing the project into eclipse.

refreshing everything in eclipse

ignoring the error and running "play debug run" and then going to localhost:9000 (one person said that this happened to them and that they just ignored the error in the IDE and that it worked fine on the server), but instead I just got the same error at localhost as I got in Eclipse, which I screen shotted:

At this point I have no idea how to proceed. My best guess like I said is that the problem is that the application for some reason doesn't "know" that I updated "index.scala.html" thereby changing the parameters that "render" takes, but I don't know why it doesn't "know" it.

Sorry this was so long; I wanted to make sure I'd included everything.

If anyone has any ideas that would be great, thank you.

答:
in your controller you're importing a javafx Task class:

```<code>import com.sun.javafx.tk.Toolkit.Task;
</code>```

but your view is expect your model class:

```<code>models.Task
</code>```

change javafx Task import to models.Task import.

Body:
I am new to Java Play and am working with version 2.2.6 as I'm on a windows machine and was unable to get the newest version working correctly.

I am working through the tutorial for version 2.2.6, here, and have encountered a problem in the section called "Rendering the First Page," located approximately two thirds of the way down in the tutorial.

The tutorial shows how to make a simple "to do list" application in Java Play which has a Form where the user can submit "to do" items, which then appear on screen, and also delete them.

In "Rendering the First Page," the tutorial instructs the user to add the following code to the controller "Application.java" :

public static Result tasks(){
    return ok(views.html.index.render(models.Task.all(), taskForm);
}

So, at this point, my Application.java looks like this:

package controllers;

import java.util.ArrayList;
import java.util.List;

import com.sun.javafx.tk.Toolkit.Task;

import play.*;
import play.mvc.*;
import play.data.*;
import models.*;

import views.html.*;

public class Application extends Controller {

    static Form<Task> taskForm = Form.form(Task.class);

  public static Result index() {
    return ok("Hello World");
  }

  public static Result tasks() {
        return ok(
                views.html.index.render(models.Tasks.all(), taskForm)
                );
      }

  public static Result newTask() {
        return TODO;
      }

  public static Result deleteTask(Long id) {
        return TODO;
      }
}

Eclipse immediately underlines the word "render" in red, and I get the following error when I hover over it: "the method render(String) in the type index is not applicable for the arguments (List, Form)"

The tutorial had me create a model called Task.java, and if you look at the top of Application.java, it also had me "import com.sun.javafx.tk.Toolkit.Task," which I'm not really sure what it does.

Here's my model, Task.java:

package models;

import java.util.*;

import play.data.validation.Constraints.*;

public class Task {

    public Long id;

    @Required
    public String label;

    public static List<Task> all(){
        return new ArrayList<Task>();
    }

    public static void create(Task task){

    }

    public static void delete(Long id){

    }
}

So, all that being said, here's what I think the problem is:

"render"'s parameter(s) is/are defined in the view "index.scala.html", in scala

When you first create a blank Java application in java play, it auto-fills index.scala.html with the following lines of code:

@(message: String)

@main("Welcome to Play") {

    @play20.welcome(message, style = "Java")

}

The tutorial had me delete all of that from index.scala.html, which like I said is a view, and had me replace it with this code:

@(tasks: List[Task], taskForm: Form[Task])

@import helper._

@main("Todo list") {

@tasks.size() task(s)

        @for(task <- tasks) {

                @task.label

                @form(routes.Application.deleteTask(task.id)) {
                    <input type="submit" value="Delete">
                }

        }

Add a new task

    @form(routes.Application.newTask()) {

        @inputText(taskForm("label"))

        <input type="submit" value="Create">

    }

}

Now, the very first line in index.scala.html is what tells the controller what params "render" takes. As you can see, when you make a blank Java Play application, it starts out being @(message: String). I changed it to be @(tasks: List[Task], taskForm[Task]). So it should know that those are the params that "render" should take. But for some reason, it still thinks that "render" is supposed to take a String, and gives me an error.

I've been scouring the internet for hours and tried many solutions that have been offered before posting my own question.

Here's some things I've tried:

adding these lines to build.sbt (with spaces in between):

EclipseKeys.projectFlavor := EclipseProjectFlavor.Java

EclipseKeys.preTasks := Seq(compile in Compile)

and then closing out eclipse. from the command line in my project's directory, running "play clean-all" "play compile" "play eclipse", and then re-importing the project into eclipse.

refreshing everything in eclipse

ignoring the error and running "play debug run" and then going to localhost:9000 (one person said that this happened to them and that they just ignored the error in the IDE and that it worked fine on the server), but instead I just got the same error at localhost as I got in Eclipse, which I screen shotted:

At this point I have no idea how to proceed. My best guess like I said is that the problem is that the application for some reason doesn't "know" that I updated "index.scala.html" thereby changing the parameters that "render" takes, but I don't know why it doesn't "know" it.

Sorry this was so long; I wanted to make sure I'd included everything.

If anyone has any ideas that would be great, thank you.

Body:
in your controller you're importing a javafx Task class:

import com.sun.javafx.tk.Toolkit.Task;

but your view is expect your model class:

models.Task

change javafx Task import to models.Task import.


问:
"Could not find Developer Disk Image"
Recently I've been getting the error: "Could not find Developer Disk Image"

I think this happens since I have updated iOS to 9.1 on the iPhone.
How can I fix the problem and make Xcode support iOS 9.1 devices?

答:
Older XCode version has no developer disk image for newer iOS version.
If you don't want upgrade XCode you can find
ready developer disk images for latest versions in this answer: https://stackoverflow.com/a/39865199/286361

Title: "Could not find Developer Disk Image"


问:
segmentation violation Segmentation fault c++ with values in numerator array
I'm trying to calculate a ratio and it works when my numerator array is full with 0, but when I have values in the numerator array breaks the program.

```<code>223 Double_t *ratio_calculations(int bin_numbers, Double_t *flux_data)
224 {
225         Double_t *ratio;
226         for(int n = 0; n <bin_numbers; n++)
227         {
228                 if(0 < flux_data[n])
229                 {
230
231                         ratio[n] = ygraph.axis_array[n]/flux_data[n];
232                 }
233         }
234         return ratio;
235 }
</code>```

I have no idea why it happens, and yes I have checked the lengths of my arrays and they are the same as the value of bin_numbers.

答:
You need determine the correct size for ratio, allocate the memory, and finally, make sure you fill ratio
correctly as you filter invalid data with the if statement:

```<code>Double_t *ratio_calculations(int bin_numbers, Double_t *flux_data) {
  // get correct size
  int sz = 0;
  for (int n = 0; n < bin_numbers; n++) {
    if (flux_data[n] > 0) sz++;
  }
  Double_t *ratio = new Double_t[sz];
  // allocate with non-n index, as n increments even when data is invalid (flux_data[n] < 0)
  int r_idx = 0
  for (int n = 0; n <bin_numbers; n++) {
    if (flux_data[n] > 0) {
      ratio[r_idx] = ygraph.axis_array[n]/flux_data[n];
      r_idx++;
    }
  }
  return ratio;
}
</code>```

Body:
I'm trying to calculate a ratio and it works when my numerator array is full with 0, but when I have values in the numerator array breaks the program.

223 Double_t *ratio_calculations(int bin_numbers, Double_t *flux_data)
224 {
225         Double_t *ratio;
226         for(int n = 0; n <bin_numbers; n++)
227         {
228                 if(0 < flux_data[n])
229                 {
230
231                         ratio[n] = ygraph.axis_array[n]/flux_data[n];
232                 }
233         }
234         return ratio;
235 }

I have no idea why it happens, and yes I have checked the lengths of my arrays and they are the same as the value of bin_numbers.

Body:
You need determine the correct size for ratio, allocate the memory, and finally, make sure you fill ratio
correctly as you filter invalid data with the if statement:

Double_t *ratio_calculations(int bin_numbers, Double_t *flux_data) {
  // get correct size
  int sz = 0;
  for (int n = 0; n < bin_numbers; n++) {
    if (flux_data[n] > 0) sz++;
  }
  Double_t *ratio = new Double_t[sz];
  // allocate with non-n index, as n increments even when data is invalid (flux_data[n] < 0)
  int r_idx = 0
  for (int n = 0; n <bin_numbers; n++) {
    if (flux_data[n] > 0) {
      ratio[r_idx] = ygraph.axis_array[n]/flux_data[n];
      r_idx++;
    }
  }
  return ratio;
}


问:
C# loop - break vs. continue
In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

Example:

```<code>foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}
</code>```

答:
All have given a very good explanation. I am still posting my answer just to give an example if that can help.

```<code>// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
</code>```

Here is the output:

0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

```<code>//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
</code>```

Here is the output:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed]  will not be displayed as there is continue when i == 3

ContentLicense: CC BY-SA 4.0

Title: C# loop - break vs. continue

Body:
In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

Example:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}

Body:
All have given a very good explanation. I am still posting my answer just to give an example if that can help.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed]  will not be displayed as there is continue when i == 3


问:
Jquery Click this or that and toggle class
Im stuck on toggeling a class when there is a click event on either the parent or child item. It is about a navigation menu that can be clickable on the entire bar or just the icon.

Current situation: (according to the fiddle)
When you click on the red block, the class is-active will be toggled on the .hamburger-menu class. Allowing the icon to transition via CSS.
But when you click on the hamburger icon it does not toggle the class.

How can the class is-active be toggled when there is a click event on either the #menuContainer or the .hamburger-menu div?

jQuery(function($) {
  $(document).ready(function() {
    $("#menuContainer, .hamburger-menu").click(function() {
      $(".hamburger-menu").toggleClass("is-active");
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}</code>```

```

答:
The issue is because you've added the click event handler to two elements, #menuContainer and .hamburger-menu. The latter is a child of the former, so when you click that the handler fires twice. This means that the class is toggled on, then immediately off again (or vice versa)

To fix this issue, call stopPropagation() on the event. This stops the event bubbling up the DOM and being handled twice.

jQuery(function($) { // Note you only need one document.ready handler here
  $("#menuContainer, .hamburger-menu").click(function(e) {
    e.stopPropagation();
    $(".hamburger-menu").toggleClass("is-active");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}</code>```

```

Body:
Im stuck on toggeling a class when there is a click event on either the parent or child item. It is about a navigation menu that can be clickable on the entire bar or just the icon.

Current situation: (according to the fiddle)
When you click on the red block, the class is-active will be toggled on the .hamburger-menu class. Allowing the icon to transition via CSS.
But when you click on the hamburger icon it does not toggle the class.

How can the class is-active be toggled when there is a click event on either the #menuContainer or the .hamburger-menu div?

jQuery(function($) {
  $(document).ready(function() {
    $("#menuContainer, .hamburger-menu").click(function() {
      $(".hamburger-menu").toggleClass("is-active");
    });
  });
});

.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}

Body:
The issue is because you've added the click event handler to two elements, #menuContainer and .hamburger-menu. The latter is a child of the former, so when you click that the handler fires twice. This means that the class is toggled on, then immediately off again (or vice versa)

To fix this issue, call stopPropagation() on the event. This stops the event bubbling up the DOM and being handled twice.

jQuery(function($) { // Note you only need one document.ready handler here
  $("#menuContainer, .hamburger-menu").click(function(e) {
    e.stopPropagation();
    $(".hamburger-menu").toggleClass("is-active");
  });
});

.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menuContainer" class="menu-trigger menu_container">
  <div class="hamburger-menu">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>


问:
How do I strip only the string part from a list in Python?
I have a list that looks like:

```<code>{
    'J2EE': 0.0202219636,
    'financial': 0.2439565346,
    'Guru': 0.0202219636,
    'AWS': 0.0202219636,
    'next generation': 0.12072663160000001,
    'Machine Learning': 0.2025762767,
    'technology': 0.066936981
}
</code>```

How do I extract only the text parts and make my list look like:

```<code>['J2EE', 'financial', 'Guru', 'AWS', ...]
</code>```

Should I use Regular expressions?

答:
What you have there is a dictionary, not a list, and what you want are the keys:</p>

```<code>your_dict = {'J2EE': 0.0202219636, 'financial': 0.2439565346, 'Guru': 0.0202219636, 'AWS': 0.0202219636, 'next generation': 0.12072663160000001, 'Machine Learning': 0.2025762767, 'technology': 0.066936981}
your_dict_keys = your_dict.keys()
</code>```

Body:
I have a list that looks like:

{
    'J2EE': 0.0202219636,
    'financial': 0.2439565346,
    'Guru': 0.0202219636,
    'AWS': 0.0202219636,
    'next generation': 0.12072663160000001,
    'Machine Learning': 0.2025762767,
    'technology': 0.066936981
}

How do I extract only the text parts and make my list look like:

['J2EE', 'financial', 'Guru', 'AWS', ...]

Should I use Regular expressions?

Body:
What you have there is a dictionary, not a list, and what you want are the keys:

your_dict = {'J2EE': 0.0202219636, 'financial': 0.2439565346, 'Guru': 0.0202219636, 'AWS': 0.0202219636, 'next generation': 0.12072663160000001, 'Machine Learning': 0.2025762767, 'technology': 0.066936981}
your_dict_keys = your_dict.keys()


问:
how to get values from the array with the help of for loop
In my ios app,
i have some data in one array,now i want to print that data with the help of NSlog in viewdidload , but i want to show that data inside one for loop...so i didn't get what should be my for loop.

i want to get values from the array with the help of using for...loop... how can i do that ?

```<code>storedDataArray = [[NSMutableArray alloc]init];

[storedDataArray addObject:@"Kaushal"];

[storedDataArray addObject:@"Bhaumik"];

[storedDataArray addObject:@"Arpit"];

[storedDataArray addObject:@"Swapnil"];

[storedDataArray addObject:@"Megha"];

[storedDataArray addObject:@"Ravi"];

for (int i=0; i<=6; i++) {
    NSLog(@"hello %d",storedDataArray);
}
</code>```

答:
You have to add index in storedDataArray

```<code>for (int i=0; i<storedDataArray.count; i++) {
    NSLog(@"hello %@",storedDataArray[i]);
}
</code>```

Or you can do without index

```<code>for (NSString *str in storedDataArray) {
    NSLog(@"hello %@",str);
}
</code>```

Body:
In my ios app,
i have some data in one array,now i want to print that data with the help of NSlog in viewdidload , but i want to show that data inside one for loop...so i didn't get what should be my for loop.

i want to get values from the array with the help of using for...loop... how can i do that ?

storedDataArray = [[NSMutableArray alloc]init];

[storedDataArray addObject:@"Kaushal"];

[storedDataArray addObject:@"Bhaumik"];

[storedDataArray addObject:@"Arpit"];

[storedDataArray addObject:@"Swapnil"];

[storedDataArray addObject:@"Megha"];

[storedDataArray addObject:@"Ravi"];

for (int i=0; i<=6; i++) {
    NSLog(@"hello %d",storedDataArray);
}

Body:
You have to add index in storedDataArray

for (int i=0; i<storedDataArray.count; i++) {
    NSLog(@"hello %@",storedDataArray[i]);
}

Or you can do without index

for (NSString *str in storedDataArray) {
    NSLog(@"hello %@",str);
}


问:
Pandas insert value into dataframe with loc
I have a dataframe that is called dfDays that look like this:

```<code>siren   Groupe  nomination_frequence    demission_frequence depart_frequence    modification_frequence  deces_frequence confirmation_frequence  sansprecision_frequence nbJoursMoyenne  ecart_type  nbJoursDernierEvenementExtraction
0   XXX Dirigeants  1   0   0   0   0   0   0   None    NaN 2345
1   XXX Autres  2   0   2   0   0   0   0   191 270.586 1217
2   XXX Dirigeants  0   0   0   0   0   0   3   281 281 1283
3   XXX Dirigeants  2   2   0   0   0   0   0   61  86.7384 1583
4   XXX Dirigeants  1   1   0   0   0   0   5   93  136.118 1283
</code>```

I'm adding into a new datadrame called dfNew the values of the dfDays but adding a category according to the "groupe"

Let's assume the final dataframe that I want to obtain is : (dont look at the values)

```<code>    siren   Dirigeants_nomination_frequence Dirigeants_demission_frequence  Dirigeants_depart_frequence Dirigeants_modification_frequence   Dirigeants_deces_frequence  Dirigeants_confirmation_frequence   Dirigeants_sansprecision_frequence  MembresDuConseil_nomination_frequence   MembresDuConseil_demission_frequence    ... mouvement_ecart_type    Dirigeants_nbJoursMoyenne   Dirigeants_ecart_type   Dirigeants_nbJoursDernierEvenementExtraction    Autres_nbJoursMoyenne   Autres_ecart_type   Autres_nbJoursDernierEvenementExtraction    MembresDuConseil_nbJoursMoyenne MembresDuConseil_ecart_type MembresDuConseil_nbJoursDernierEvenementExtraction
0   XXX 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 NaN NaN 2345.0  NaN NaN 0.0 NaN NaN 0.0
3   XXX 0.0 0.0 0.0 0.0 0.0 0.0 3.0 0.0 0.0 ... 0.0 281.0   281.000000  1283.0  191.0   270.586195  1217.0  NaN NaN 0.0
11  XXX 2.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 61.0    86.738432   1583.0  NaN NaN 0.0 NaN NaN 0.0
16  XXX 1.0 1.0 0.0 0.0 0.0 0.0 5.0 0.0 0.0 ... 0.0 93.0    136.118413  1283.0  NaN NaN 0.0 NaN NaN 0.0
</code>```

Here is my code in order to do that:

```<code>liste_nom = ['nomination_frequence','demission_frequence','depart_frequence','modification_frequence','deces_frequence','confirmation_frequence','sansprecision_frequence',
             'nbJoursMoyenne','ecart_type', 'nbJoursDernierEvenementExtraction']

for index, row in dfDays.iterrows():
    #print(row)
    name = row['Groupe']
    siren = row['siren']
    index = dfRight[dfRight['siren'] == siren].index[0]

    print(dfNew.columns)
    for value in liste_nom:
        #print(row)
        #print(row[value])
        dfNew.loc[index, name + '_' + value] = row[value]
print(dfNew.columns)
</code>```

My problem is that before using the first .loc with index my columns look like this in dfNew:

```<code>Index(['siren', 'Dirigeants_nomination_frequence',
       'Dirigeants_demission_frequence', 'Dirigeants_depart_frequence',
       'Dirigeants_modification_frequence', 'Dirigeants_deces_frequence',
       'Dirigeants_confirmation_frequence',
       'Dirigeants_sansprecision_frequence',
       'MembresDuConseil_nomination_frequence',
       'MembresDuConseil_demission_frequence',
       'MembresDuConseil_depart_frequence',
       'MembresDuConseil_modification_frequence',
       'MembresDuConseil_deces_frequence',
       'MembresDuConseil_confirmation_frequence',
       'MembresDuConseil_sansprecision_frequence',
       'Autres_nomination_frequence', 'Autres_demission_frequence',
       'Autres_depart_frequence', 'Autres_modification_frequence',
       'Autres_deces_frequence', 'Autres_confirmation_frequence',
       'Autres_sansprecision_frequence', 'mouvements_nbJoursMoyenne',
       'mouvement_ecart_type'],
      dtype='object')
</code>```

But after I'm using .loc multiple time the column are swapped and look like this:

```<code>Index(['siren', 'Dirigeants_nomination_frequence',
       'Dirigeants_demission_frequence', 'Dirigeants_depart_frequence',
       'Dirigeants_modification_frequence', 'Dirigeants_deces_frequence',
       'Dirigeants_confirmation_frequence',
       'Dirigeants_sansprecision_frequence',
       'MembresDuConseil_nomination_frequence',
       'MembresDuConseil_demission_frequence',
       'MembresDuConseil_depart_frequence',
       'MembresDuConseil_modification_frequence',
       'MembresDuConseil_deces_frequence',
       'MembresDuConseil_confirmation_frequence',
       'MembresDuConseil_sansprecision_frequence',
       'Autres_nomination_frequence', 'Autres_demission_frequence',
       'Autres_depart_frequence', 'Autres_modification_frequence',
       'Autres_deces_frequence', 'Autres_confirmation_frequence',
       'Autres_sansprecision_frequence', 'mouvements_nbJoursMoyenne',
       'mouvement_ecart_type', 'Dirigeants_nbJoursMoyenne',
       'Dirigeants_ecart_type', 'Dirigeants_nbJoursDernierEvenementExtraction',
       'Autres_nbJoursMoyenne', 'Autres_ecart_type',
       'Autres_nbJoursDernierEvenementExtraction',
       'MembresDuConseil_nbJoursMoyenne', 'MembresDuConseil_ecart_type',
       'MembresDuConseil_nbJoursDernierEvenementExtraction'],
      dtype='object')
</code>```

I dont understand how the use of .loc is able to swap the order of my columns ?
Thank's for reading.

答:
I think you need pivot for reshape and then flatten Multiindex in columns by map with join:

```<code>print (df)
  siren      Groupe  nomination_frequence  demission_frequence
1     b      Autres                2.0000                  191
2     c  Dirigeants              281.0000                 1283
3     d  Dirigeants               86.7384                 1583
4     e  Dirigeants              136.1180                 1283
</code>```

First filter columns by list:

```<code>liste_nom = ['nomination_frequence','demission_frequence', ...] + ['siren','Groupe']

df = df[liste_nom]

df = df.pivot(index='siren', columns='Groupe')
df.columns = df.columns.map('_'.join)
print (df)
       nomination_frequence_Autres  nomination_frequence_Dirigeants  \
siren
b                              2.0                              NaN
c                              NaN                         281.0000
d                              NaN                          86.7384
e                              NaN                         136.1180

       demission_frequence_Autres  demission_frequence_Dirigeants
siren
b                           191.0                             NaN
c                             NaN                          1283.0
d                             NaN                          1583.0
e                             NaN                          1283.0
</code>```

but if get:

ValueError: Index contains duplicate entries, cannot reshape

it means there are duplicates in columns pairs for new indexes and columns.

So need pivot_table with some aggregate function like mean:

```<code>print (df)
  siren      Groupe  nomination_frequence  demission_frequence
1     b      Autres                2.0000                  191 <-same b,Autres
1     b      Autres                5.0000                   50 <-same b,Autres
2     c  Dirigeants              281.0000                 1283
3     d  Dirigeants               86.7384                 1583
4     e  Dirigeants              136.1180                 1283

liste_nom = ['nomination_frequence','demission_frequence', ...] + ['siren','Groupe']

df = df[liste_nom]

df = df.pivot_table(index='siren', columns='Groupe', aggfunc='mean')
df.columns = df.columns.map('_'.join)
print (df)
       demission_frequence_Autres  demission_frequence_Dirigeants  \
siren
b                           120.5                             NaN (191 + 50)/2 = 120.5
c                             NaN                          1283.0
d                             NaN                          1583.0
e                             NaN                          1283.0

       nomination_frequence_Autres  nomination_frequence_Dirigeants
siren
b                              3.5                              NaN
c                              NaN                         281.0000
d                              NaN                          86.7384
e                              NaN                         136.1180
</code>```

But if need change columns names by swapping and sorting:

```<code>liste_nom = ['nomination_frequence','demission_frequence'] + ['siren','Groupe']
df = df[liste_nom]
df = df.pivot_table(index='siren', columns='Groupe', aggfunc='mean')
df = df.swaplevel(0,1, axis=1).sort_index(axis=1)
df.columns = df.columns.map('_'.join)
print (df)
       Autres_demission_frequence  Autres_nomination_frequence  \
siren
b                           120.5                          3.5
c                             NaN                          NaN
d                             NaN                          NaN
e                             NaN                          NaN

       Dirigeants_demission_frequence  Dirigeants_nomination_frequence
siren
b                                 NaN                              NaN
c                              1283.0                         281.0000
d                              1583.0                          86.7384
e                              1283.0                         136.1180
</code>```

Body:
I have a dataframe that is called dfDays that look like this:

siren   Groupe  nomination_frequence    demission_frequence depart_frequence    modification_frequence  deces_frequence confirmation_frequence  sansprecision_frequence nbJoursMoyenne  ecart_type  nbJoursDernierEvenementExtraction
0   XXX Dirigeants  1   0   0   0   0   0   0   None    NaN 2345
1   XXX Autres  2   0   2   0   0   0   0   191 270.586 1217
2   XXX Dirigeants  0   0   0   0   0   0   3   281 281 1283
3   XXX Dirigeants  2   2   0   0   0   0   0   61  86.7384 1583
4   XXX Dirigeants  1   1   0   0   0   0   5   93  136.118 1283

I'm adding into a new datadrame called dfNew the values of the dfDays but adding a category according to the "groupe"

Let's assume the final dataframe that I want to obtain is : (dont look at the values)

    siren   Dirigeants_nomination_frequence Dirigeants_demission_frequence  Dirigeants_depart_frequence Dirigeants_modification_frequence   Dirigeants_deces_frequence  Dirigeants_confirmation_frequence   Dirigeants_sansprecision_frequence  MembresDuConseil_nomination_frequence   MembresDuConseil_demission_frequence    ... mouvement_ecart_type    Dirigeants_nbJoursMoyenne   Dirigeants_ecart_type   Dirigeants_nbJoursDernierEvenementExtraction    Autres_nbJoursMoyenne   Autres_ecart_type   Autres_nbJoursDernierEvenementExtraction    MembresDuConseil_nbJoursMoyenne MembresDuConseil_ecart_type MembresDuConseil_nbJoursDernierEvenementExtraction
0   XXX 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 NaN NaN 2345.0  NaN NaN 0.0 NaN NaN 0.0
3   XXX 0.0 0.0 0.0 0.0 0.0 0.0 3.0 0.0 0.0 ... 0.0 281.0   281.000000  1283.0  191.0   270.586195  1217.0  NaN NaN 0.0
11  XXX 2.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 61.0    86.738432   1583.0  NaN NaN 0.0 NaN NaN 0.0
16  XXX 1.0 1.0 0.0 0.0 0.0 0.0 5.0 0.0 0.0 ... 0.0 93.0    136.118413  1283.0  NaN NaN 0.0 NaN NaN 0.0

Here is my code in order to do that:

liste_nom = ['nomination_frequence','demission_frequence','depart_frequence','modification_frequence','deces_frequence','confirmation_frequence','sansprecision_frequence',
             'nbJoursMoyenne','ecart_type', 'nbJoursDernierEvenementExtraction']

for index, row in dfDays.iterrows():
    #print(row)
    name = row['Groupe']
    siren = row['siren']
    index = dfRight[dfRight['siren'] == siren].index[0]

    print(dfNew.columns)
    for value in liste_nom:
        #print(row)
        #print(row[value])
        dfNew.loc[index, name + '_' + value] = row[value]
print(dfNew.columns)

My problem is that before using the first .loc with index my columns look like this in dfNew:

Index(['siren', 'Dirigeants_nomination_frequence',
       'Dirigeants_demission_frequence', 'Dirigeants_depart_frequence',
       'Dirigeants_modification_frequence', 'Dirigeants_deces_frequence',
       'Dirigeants_confirmation_frequence',
       'Dirigeants_sansprecision_frequence',
       'MembresDuConseil_nomination_frequence',
       'MembresDuConseil_demission_frequence',
       'MembresDuConseil_depart_frequence',
       'MembresDuConseil_modification_frequence',
       'MembresDuConseil_deces_frequence',
       'MembresDuConseil_confirmation_frequence',
       'MembresDuConseil_sansprecision_frequence',
       'Autres_nomination_frequence', 'Autres_demission_frequence',
       'Autres_depart_frequence', 'Autres_modification_frequence',
       'Autres_deces_frequence', 'Autres_confirmation_frequence',
       'Autres_sansprecision_frequence', 'mouvements_nbJoursMoyenne',
       'mouvement_ecart_type'],
      dtype='object')

But after I'm using .loc multiple time the column are swapped and look like this:

Index(['siren', 'Dirigeants_nomination_frequence',
       'Dirigeants_demission_frequence', 'Dirigeants_depart_frequence',
       'Dirigeants_modification_frequence', 'Dirigeants_deces_frequence',
       'Dirigeants_confirmation_frequence',
       'Dirigeants_sansprecision_frequence',
       'MembresDuConseil_nomination_frequence',
       'MembresDuConseil_demission_frequence',
       'MembresDuConseil_depart_frequence',
       'MembresDuConseil_modification_frequence',
       'MembresDuConseil_deces_frequence',
       'MembresDuConseil_confirmation_frequence',
       'MembresDuConseil_sansprecision_frequence',
       'Autres_nomination_frequence', 'Autres_demission_frequence',
       'Autres_depart_frequence', 'Autres_modification_frequence',
       'Autres_deces_frequence', 'Autres_confirmation_frequence',
       'Autres_sansprecision_frequence', 'mouvements_nbJoursMoyenne',
       'mouvement_ecart_type', 'Dirigeants_nbJoursMoyenne',
       'Dirigeants_ecart_type', 'Dirigeants_nbJoursDernierEvenementExtraction',
       'Autres_nbJoursMoyenne', 'Autres_ecart_type',
       'Autres_nbJoursDernierEvenementExtraction',
       'MembresDuConseil_nbJoursMoyenne', 'MembresDuConseil_ecart_type',
       'MembresDuConseil_nbJoursDernierEvenementExtraction'],
      dtype='object')

I dont understand how the use of .loc is able to swap the order of my columns ?
Thank's for reading.

Body:
I think you need pivot for reshape and then flatten Multiindex in columns by map with join:

print (df)
  siren      Groupe  nomination_frequence  demission_frequence
1     b      Autres                2.0000                  191
2     c  Dirigeants              281.0000                 1283
3     d  Dirigeants               86.7384                 1583
4     e  Dirigeants              136.1180                 1283

First filter columns by list:

liste_nom = ['nomination_frequence','demission_frequence', ...] + ['siren','Groupe']

df = df[liste_nom]

df = df.pivot(index='siren', columns='Groupe')
df.columns = df.columns.map('_'.join)
print (df)
       nomination_frequence_Autres  nomination_frequence_Dirigeants  \
siren
b                              2.0                              NaN
c                              NaN                         281.0000
d                              NaN                          86.7384
e                              NaN                         136.1180

       demission_frequence_Autres  demission_frequence_Dirigeants
siren
b                           191.0                             NaN
c                             NaN                          1283.0
d                             NaN                          1583.0
e                             NaN                          1283.0

but if get:

ValueError: Index contains duplicate entries, cannot reshape

it means there are duplicates in columns pairs for new indexes and columns.

So need pivot_table with some aggregate function like mean:

print (df)
  siren      Groupe  nomination_frequence  demission_frequence
1     b      Autres                2.0000                  191 <-same b,Autres
1     b      Autres                5.0000                   50 <-same b,Autres
2     c  Dirigeants              281.0000                 1283
3     d  Dirigeants               86.7384                 1583
4     e  Dirigeants              136.1180                 1283

liste_nom = ['nomination_frequence','demission_frequence', ...] + ['siren','Groupe']

df = df[liste_nom]

df = df.pivot_table(index='siren', columns='Groupe', aggfunc='mean')
df.columns = df.columns.map('_'.join)
print (df)
       demission_frequence_Autres  demission_frequence_Dirigeants  \
siren
b                           120.5                             NaN (191 + 50)/2 = 120.5
c                             NaN                          1283.0
d                             NaN                          1583.0
e                             NaN                          1283.0

       nomination_frequence_Autres  nomination_frequence_Dirigeants
siren
b                              3.5                              NaN
c                              NaN                         281.0000
d                              NaN                          86.7384
e                              NaN                         136.1180

But if need change columns names by swapping and sorting:

liste_nom = ['nomination_frequence','demission_frequence'] + ['siren','Groupe']
df = df[liste_nom]
df = df.pivot_table(index='siren', columns='Groupe', aggfunc='mean')
df = df.swaplevel(0,1, axis=1).sort_index(axis=1)
df.columns = df.columns.map('_'.join)
print (df)
       Autres_demission_frequence  Autres_nomination_frequence  \
siren
b                           120.5                          3.5
c                             NaN                          NaN
d                             NaN                          NaN
e                             NaN                          NaN

       Dirigeants_demission_frequence  Dirigeants_nomination_frequence
siren
b                                 NaN                              NaN
c                              1283.0                         281.0000
d                              1583.0                          86.7384
e                              1283.0                         136.1180