问:
How to set click listener on a whole ListView (not on the individual items of ListView)?
I want to set onClickListener() on the whole layout space of ListView i.e. if I click anywhere on layout area of a ListView, a specific task should be performed. How can I accomplish that in Android using java?

Notice that I do not want onItemClickListener(), tapping anywhere on the screen should perform the task.

ChatActivity.java

```<code>chatList = (ListView) findViewById(R.id.chat_list);

        adapter = new ChatMessageAdapter(ChatActivity.this, tempList);

        chatList.setAdapter(adapter);

        chatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // code here
                return false;
            }
        });
</code>```

activity_chat.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/parent_layout"
    tools:context=".MainActivity"
    android:layout_marginRight="18dp"
    android:layout_marginLeft="18dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="18dp"
        android:backgroundTint="@color/colorAccent">

        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 1"
            android:textStyle="bold"
            android:gravity="left"/>
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 2"
            android:textStyle="bold"
            android:gravity="right"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ListView
        android:id="@+id/chat_list"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"/>

    </LinearLayout>

</LinearLayout>
</code>```

答:
why you don't perform a onClickListener() on the parent layout of your listview ?

did you even try adding setOnTouchListener() or setOnClickListener the listview ?

```<code>  <LinearLayout
    android:id="@+id/layout_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<ListView
    android:id="@+id/chat_list"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"/>

</LinearLayout>
</code>```

in your java side

```<code>LinearLayout listlayout = (LinearLayout) findViewById(R.id.layout_list);
listlayout.setClickable(true);

listlayout.setOnClickListener(new View.OnClickListener()
 {
  @Override
  public void onClick(View v)
    {
    /// do your stuff here
    }
  });
</code>```

Body:
I want to set onClickListener() on the whole layout space of ListView i.e. if I click anywhere on layout area of a ListView, a specific task should be performed. How can I accomplish that in Android using java?

Notice that I do not want onItemClickListener(), tapping anywhere on the screen should perform the task.

ChatActivity.java

chatList = (ListView) findViewById(R.id.chat_list);

        adapter = new ChatMessageAdapter(ChatActivity.this, tempList);

        chatList.setAdapter(adapter);

        chatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // code here
                return false;
            }
        });

activity_chat.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/parent_layout"
    tools:context=".MainActivity"
    android:layout_marginRight="18dp"
    android:layout_marginLeft="18dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="18dp"
        android:backgroundTint="@color/colorAccent">

        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 1"
            android:textStyle="bold"
            android:gravity="left"/>
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 2"
            android:textStyle="bold"
            android:gravity="right"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ListView
        android:id="@+id/chat_list"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"/>

    </LinearLayout>

</LinearLayout>

Body:
why you don't perform a onClickListener() on the parent layout of your listview ?

did you even try adding setOnTouchListener() or setOnClickListener the listview ?

  <LinearLayout
    android:id="@+id/layout_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<ListView
    android:id="@+id/chat_list"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"/>

</LinearLayout>

in your java side

LinearLayout listlayout = (LinearLayout) findViewById(R.id.layout_list);
listlayout.setClickable(true);

listlayout.setOnClickListener(new View.OnClickListener()
 {
  @Override
  public void onClick(View v)
    {
    /// do your stuff here
    }
  });


来源: stackexchange

问:
Firebase message, Android app in background not intercept push notification after click on message
I use firebase messaging to send push notification. I have a small problem with my android app. In the iOS version, I can easily pass parameters after clicking on a notification when the app is in background.

In Android version I can intercept messages when the app is in the foreground, but not when the app is in the background (I use library com.google.firebase:firebase-messaging:17.3.4):

my AndroidManifest.xml

```<code><activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="OPEN_NOTIFY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
....
<service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
</code>```

My notification payload:

```<code>notification:{
 title: "mytitle",
 text: "MYTEXT",
 "data":{
   "type" : "message",
   "id_message" : res
  },
  "click_action" : "OPEN_NOTIFY"
},to: token
</code>```

When I click on the notification, it should open the MainActivity and I would like to have the id_message

my MyFirebaseMessagingService.java

```<code> @Override
public void onMessageReceived(RemoteMessage remoteMessage){

    //never enters if the app is in background

    if(remoteMessage.getNotification() != null){
       //I READ NOTIFY WHEN APP IS IN FOREGROUND
    }
}
</code>```

I try to get parameters directly from the Inten, but this solution doesn't work

my MainActivity.java:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
   ....
   if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
        }
    }
   ....
}
</code>```

I can't intercept my notify:

output:

```<code>Key: google.sent_time Value: 1540026384768
Key: google.ttl Value: 2419200
Key: from Value: 635549396240
Key: google.message_id Value: 0:1540026384773623%6b8fed3d6b8fed3d
Key: collapse_key Value: ....
</code>```

Am I following the right path? Thank You

答:
According to official Firebase docs, you can't handle notification{} part of notification (you can only set icon of it in manifest), BUT here's solution: send necessary data via data{} part. You can now handle it with MyFirebaseService and show notification if you want and as you want: data will appear in remoteMessage.toIntent().getExtras().
In your case, send notification like this:

```<code>// ignore notification {}
data {
    "type" : "message",
    "id_message" : res
}
to: key
</code>```

(do not place data into notification block)
I can write working code of sending and receiving notification, if you want

ContentLicense: CC BY-SA 4.0

Body:
I use firebase messaging to send push notification. I have a small problem with my android app. In the iOS version, I can easily pass parameters after clicking on a notification when the app is in background.

In Android version I can intercept messages when the app is in the foreground, but not when the app is in the background (I use library com.google.firebase:firebase-messaging:17.3.4):

my AndroidManifest.xml

<activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="OPEN_NOTIFY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
....
<service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

My notification payload:

notification:{
 title: "mytitle",
 text: "MYTEXT",
 "data":{
   "type" : "message",
   "id_message" : res
  },
  "click_action" : "OPEN_NOTIFY"
},to: token

When I click on the notification, it should open the MainActivity and I would like to have the id_message

my MyFirebaseMessagingService.java

 @Override
public void onMessageReceived(RemoteMessage remoteMessage){

    //never enters if the app is in background

    if(remoteMessage.getNotification() != null){
       //I READ NOTIFY WHEN APP IS IN FOREGROUND
    }
}

I try to get parameters directly from the Inten, but this solution doesn't work

my MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
   ....
   if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
        }
    }
   ....
}

I can't intercept my notify:

output:

Key: google.sent_time Value: 1540026384768
Key: google.ttl Value: 2419200
Key: from Value: 635549396240
Key: google.message_id Value: 0:1540026384773623%6b8fed3d6b8fed3d
Key: collapse_key Value: ....

Am I following the right path? Thank You

Body:
According to official Firebase docs, you can't handle notification{} part of notification (you can only set icon of it in manifest), BUT here's solution: send necessary data via data{} part. You can now handle it with MyFirebaseService and show notification if you want and as you want: data will appear in remoteMessage.toIntent().getExtras().
In your case, send notification like this:

// ignore notification {}
data {
    "type" : "message",
    "id_message" : res
}
to: key

(do not place data into notification block)
I can write working code of sending and receiving notification, if you want


问:
Do I need to include css and js files in the lightbox page?
Do I need to load all the css and js files again in my lightbox html code?
The css seems to work fine. But the js functions do not work in the lightbox page. Those js files are included in the parent html page and triggered in the same file.

only the jquery code that I have written in the lightbox html code works in the lightbox page. The other js functions written in the included js files do not work.

Should I use any different methods to trigger the js functions which are included in the parent page in the lightbox page??

Edit

Lightbox html code:

```<code><div id="lightbox-holder">
    <div class="result">
         <p>Total Amount</p>
         <h3>1000</h3>
    </div>

    <div class="equal-sign"> </div>

    <div class="left-stepper">  //Stepper input
      <label class="steper-label">Left stepper</label>
      <input type="text" id="spinner1" class="ui-stepper" value="0" />
    </div>

    <div class="plus-sign"> </div>

    <div class="right-stepper"> //Stepper input
        <label class="steper-label">Right Stepper</label>
        <input type="text" id="spinner2" class="ui-stepper" value="0" />
    </div>
 </div>

 <script type="text/javascript">

  $(document).ready(function (){

        func.init();

        $('#cost_allocation').live('click', function() {
            $(this).hide();
            $('#help_icon').hide();
            $('#breakdown').show();

            $('#ok_button').hide();
            $('#save_button').show();
        });

        $('#save_button').live('click', function(){
            $("#jQLightboxContents").remove();
            $("#jQVeil").remove();

        });
});
</script>
</code>```

This jQuery inside the lightbox page works. But the js functions triggered through func.init() do not work.

The func.init() is for triggering all the js files required for this code to work. For example, the stepper input unit(numeric stepper) code is written in a file named stepper.js  and it is triggered using the init function. This works well in the parent page, but is not displayed in the lightbox page. Should I invoke the init() function in a different way?

答: No, you do not. Since the lightbox us actually in the same page, there is no need to reinclude any files.</p>

ContentLicense: CC BY-SA 3.0

Body:
Do I need to load all the css and js files again in my lightbox html code?
The css seems to work fine. But the js functions do not work in the lightbox page. Those js files are included in the parent html page and triggered in the same file.

only the jquery code that I have written in the lightbox html code works in the lightbox page. The other js functions written in the included js files do not work.

Should I use any different methods to trigger the js functions which are included in the parent page in the lightbox page??

Edit

Lightbox html code:

Total Amount

1000

  //Stepper input
      Left stepper
      <input type="text" id="spinner1" class="ui-stepper" value="0" />

 //Stepper input
        Right Stepper
        <input type="text" id="spinner2" class="ui-stepper" value="0" />

This jQuery inside the lightbox page works. But the js functions triggered through func.init() do not work.

The func.init() is for triggering all the js files required for this code to work. For example, the stepper input unit(numeric stepper) code is written in a file named stepper.js  and it is triggered using the init function. This works well in the parent page, but is not displayed in the lightbox page. Should I invoke the init() function in a different way?


问:
How to check if an id value exists in an object array
Given an array "posts" of objects {id: "x", title: "title"}, i need to verify whether there is a previously entered id before entering a new post (via form in which id is a field).

I tried looping through posts, but it causes problems on entering repeated new data. Thank you for your help, this is driving me mad.

```<code>// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }
    };
});
</code>```

答:
You can use either Array.prototype.some() as Andreas suggested or use Array.prototype.find().

Array.prototype.some() will just return true or false and will not return the matching object.
If you need the object, use find() as follows:

```<code>$("#form").submit(function(event) {
event.preventDefault();
var id = Number($("#idPost").val());
var title = $("#titlePost").val();
var date = new Date($("#data").val());
var objectPresent = posts.find(function(post) {
   return post.id === id;
});
if(!objectPresent) {
   var post = new Post(id, title, date);
} else {
  console.log(objectPresent.id,"is already taken up by ", objectPresent.title);
}
</code>```

});

Body:
Given an array "posts" of objects {id: "x", title: "title"}, i need to verify whether there is a previously entered id before entering a new post (via form in which id is a field).

I tried looping through posts, but it causes problems on entering repeated new data. Thank you for your help, this is driving me mad.

// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }
    };
});

Body:
You can use either Array.prototype.some() as Andreas suggested or use Array.prototype.find().

Array.prototype.some() will just return true or false and will not return the matching object.
If you need the object, use find() as follows:

$("#form").submit(function(event) {
event.preventDefault();
var id = Number($("#idPost").val());
var title = $("#titlePost").val();
var date = new Date($("#data").val());
var objectPresent = posts.find(function(post) {
   return post.id === id;
});
if(!objectPresent) {
   var post = new Post(id, title, date);
} else {
  console.log(objectPresent.id,"is already taken up by ", objectPresent.title);
}

});


问:
How to reformat a given array in php
I am getting variable data of multiple database tables from a html form post. The Post array need to be formated to be used as array to update the data in the table where it's coming from.

The array from the POST:

```<code>Array
(
    [test_id] => 1
    [appl_id] => 1
    [Test_code] => 0
    [test_date] => 2017-03-09
    [test_type] => 46
)
</code>```

The best result of what I need was running it through a foreach loop and formating Key and Value as needed:

```<code>$data = "";
foreach($_POST as $key => $value){
    $data .= "'".$key."' => '".$value."',<br />";
}

TblAdmin::update($table, array($data), $param, $id);
</code>```

but it still comes up with:

```<code>Array
(
    [0] =>'test_id' => '1',
    'appl_id' => '1',
    'Test_code' => '0',
    ....
)
</code>```

and I would need to reformat the array to look like:

```<code>Array
(
    'test_id' => '1',
    'appl_id' => '1',
    'Test_code' => '0',
    'test_date' => '2017-03-09',
    'test_type' => '46',
)
</code>```

答:
You where all right, the Post array works as is. The problem was coming from the fact that some fields in the database are still empty and trying to update fields in MariaDB with a PDO statement having keys without values does not work. Soon as I set empty values to null or 0 everything works fine.
Summary, I was looking for the mistake at the wrong place.</p>

Title: How to reformat a given array in php

Body:
I am getting variable data of multiple database tables from a html form post. The Post array need to be formated to be used as array to update the data in the table where it's coming from.

The array from the POST:

Array
(
    [test_id] => 1
    [appl_id] => 1
    [Test_code] => 0
    [test_date] => 2017-03-09
    [test_type] => 46
)

The best result of what I need was running it through a foreach loop and formating Key and Value as needed:

$data = "";
foreach($_POST as $key => $value){
    $data .= "'".$key."' => '".$value."',
";
}

TblAdmin::update($table, array($data), $param, $id);

but it still comes up with:

Array
(
    [0] =>'test_id' => '1',
    'appl_id' => '1',
    'Test_code' => '0',
    ....
)

and I would need to reformat the array to look like:

Array
(
    'test_id' => '1',
    'appl_id' => '1',
    'Test_code' => '0',
    'test_date' => '2017-03-09',
    'test_type' => '46',
)


问:
Why inheritance works this way in Java?
I'm new to Java and I'm trying to understand what would happen when I assign a child class instance to a parent class instance variable by simulating the following program.

```<code>public class ConfusionWithInheritance {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        DerievedClass d = new DerievedClass();
        BaseClass b = BaseClass.class.cast(d);
        BaseClass b1 = new DerievedClass();
        b.doSomeJob();
        b.printMagic(); //-> Compiler shouted me that it didn't know this method here.
    }
}
class BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value X");
    }
}
class DerievedClass extends BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value Y");
    }
    public void printMagic() {
        System.out.println("Printing magic...");
    }
}
</code>```

1) Why am I allowed to assign an instance of a child class to a parent type variable?

2) From this answer, it's explained that since I'm telling the blue print of the class to be - the parent class - it knows only the methods in the parent class. Then why it's printing the value in the method of child class when I'm invoking childInstance.doSomeJob()?

答:
This boils down to there being a difference between compile time and runtime.

At compile time, the methods available are those in the type the object is declared with.

At runtime, the methods invoked are those in the type the object is instantiated with.

So with an object that's declared as type BaseClass and instantiated as type DerivedClass, the methods available will be those in BaseClass, ie. doSomeJob(), but the method invoked is the one in DerivedClass.

Title: Why inheritance works this way in Java?

Body:
I'm new to Java and I'm trying to understand what would happen when I assign a child class instance to a parent class instance variable by simulating the following program.

public class ConfusionWithInheritance {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        DerievedClass d = new DerievedClass();
        BaseClass b = BaseClass.class.cast(d);
        BaseClass b1 = new DerievedClass();
        b.doSomeJob();
        b.printMagic(); //-> Compiler shouted me that it didn't know this method here.
    }
}
class BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value X");
    }
}
class DerievedClass extends BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value Y");
    }
    public void printMagic() {
        System.out.println("Printing magic...");
    }
}

1) Why am I allowed to assign an instance of a child class to a parent type variable?

2) From this answer, it's explained that since I'm telling the blue print of the class to be - the parent class - it knows only the methods in the parent class. Then why it's printing the value in the method of child class when I'm invoking childInstance.doSomeJob()?


问:
Newly Inserted Hive records do not show in Spark Session of Spark Shell
I ran a simple program of Spark-sql to get data from Hive to Spark session using spark-SQL.

```<code>scala> spark.sql("select count(1) from firsthivestreamtable").show(100,false)
+--------+
|count(1)|
+--------+
|36      |
+--------+
</code>```

Ran insert statements to insert 9 new records in the Hive table (directly on Hive console). Validated that Hive table has additional rows inserted properly.

```<code>hive> select count(1) aa from firsthivestreamtable;
Total MapReduce CPU Time Spent: 4 seconds 520 msec
OK
45
Time taken: 22.173 seconds, Fetched: 1 row(s)
hive>
</code>```

But spark session which was already open doesn't show the newly inserted 9 rows. So, when I do count within spark session, it still shows 36 rows. Why is this happening?

```<code>scala> spark.sql("select count(1) from firsthivestreamtable").show(100,false)
+--------+
|count(1)|
+--------+
|36      |
+--------+
</code>```

What is expected to be done in spark session to get the refreshed(new) data into the session? Actual no of rows in the Hive table now are 45 and not 36 as new data has been inserted.

It is in spark shell and the table in Hive is getting loaded through the Spark structured streaming API.

答:
The clue to the story is that the observed behaviour here in Spark aids in recomputation of the DAG - if required to a Worker Node failure.

The other answer explains the mechanics, this answer the reasoning why.

Body:
I ran a simple program of Spark-sql to get data from Hive to Spark session using spark-SQL.

scala> spark.sql("select count(1) from firsthivestreamtable").show(100,false)
+--------+
|count(1)|
+--------+
|36      |
+--------+

Ran insert statements to insert 9 new records in the Hive table (directly on Hive console). Validated that Hive table has additional rows inserted properly.

hive> select count(1) aa from firsthivestreamtable;
Total MapReduce CPU Time Spent: 4 seconds 520 msec
OK
45
Time taken: 22.173 seconds, Fetched: 1 row(s)
hive>

But spark session which was already open doesn't show the newly inserted 9 rows. So, when I do count within spark session, it still shows 36 rows. Why is this happening?

scala> spark.sql("select count(1) from firsthivestreamtable").show(100,false)
+--------+
|count(1)|
+--------+
|36      |
+--------+

What is expected to be done in spark session to get the refreshed(new) data into the session? Actual no of rows in the Hive table now are 45 and not 36 as new data has been inserted.

It is in spark shell and the table in Hive is getting loaded through the Spark structured streaming API.


问:
How to update/change object in array?
I have array with object in localstorage
image

Some a function return object with new data. I need to write new data to object in localstorage (identify by ID).

I tried but... See my code below

```<code>      const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

      const links = JSON.parse(localStorage.getItem('links'));
      const item = links.find(item => item.id === result.id);
      //localStorage.setItem('links', JSON.stringify(item));
</code>```

答:
You should get data from the storage, find an index of the target item, merge old object with a new one and store the result at the specific index, and then set the whole array at the same key. Here is a part of the most important steps:

```<code>const newData = {
  id: 'ID_2',
  NEW_DATA: 'NEW_DATA'
};

/**
 * Get old data from storage
 */

const dataFromStorage = JSON.parse(localStorage.getItem('links'));

/**
 * Merge old object with a new one (find by ID)
 */

const index = dataFromStorage.findIndex(d => d.id === newData.id);
dataFromStorage[index] = Object.assign({}, dataFromStorage[index], newData)

/**
 * Update full array in storage
 */

localStorage.setItem('links', JSON.stringify(dataFromStorage));
</code>```

And here is a link to JSFIDDLE with fully working example (check the local storage after execution).

Title: How to update/change object in array?

Body:
I have array with object in localstorage
image

Some a function return object with new data. I need to write new data to object in localstorage (identify by ID).

I tried but... See my code below

      const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

      const links = JSON.parse(localStorage.getItem('links'));
      const item = links.find(item => item.id === result.id);
      //localStorage.setItem('links', JSON.stringify(item));

Body:
You should get data from the storage, find an index of the target item, merge old object with a new one and store the result at the specific index, and then set the whole array at the same key. Here is a part of the most important steps:

const newData = {
  id: 'ID_2',
  NEW_DATA: 'NEW_DATA'
};

/**
 * Get old data from storage
 */

const dataFromStorage = JSON.parse(localStorage.getItem('links'));

/**
 * Merge old object with a new one (find by ID)
 */

const index = dataFromStorage.findIndex(d => d.id === newData.id);
dataFromStorage[index] = Object.assign({}, dataFromStorage[index], newData)

/**
 * Update full array in storage
 */

localStorage.setItem('links', JSON.stringify(dataFromStorage));

And here is a link to JSFIDDLE with fully working example (check the local storage after execution).


问:
Why is my script working, when I execute it manually, but with crontab it doesn't work?
My Raspberry Pi 3 (running debain stretch) is connected to a relay board.

Two Python Scripts are turning it on/off.
When I run the script manually it works, when I let crontab do it only "on" seems to work. I can not figure out what I did wrong.

I've read some posts and included a shebang, made the file writable,...

on.py

#!/usr/bin/python3
from gpiozero import OutputDevice
light = OutputDevice(2)
light.on()
```

<p>off.py</p>

<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3
from gpiozero import OutputDevice
light = OutputDevice(2)
light.off()
</code>```

at "crontab -e" i've written:

```<code>0 11 * * * /home/pi/Desktop/off.py
</code>```

答:
Trap the detailed text of the error, as python sees it.
This updated version of your cron should do the trick:

```<code>0 11 * * * /home/pi/Desktop/off.py 1> /tmp/myerr.txt 2>&1
</code>```

...and when it fails again, use a text editor to see if an error message is in /tmp/myerr.txt.

The following suggestions will help if the error is a problem with python locating/executing your gpio library.

One way to tell python the location of the library you're using is with some like this:

```<code>PYTHONPATH=/foo/bar/baz python somescript.py somecommand
</code>```

as detailed in this well-voted answer.

Make sure to use absolute path(s) to files/folders in PYTHONPATH in both your cron invocation and your manual invocation;  this will eliminate the possibility that cron can't find your library because of a relative path issue.

As an alternaive to PYTHONPATH, you could use sys.path.append as detailed here.

This link and this link may be helpful for gpiozero installation issus.

Body:
My Raspberry Pi 3 (running debain stretch) is connected to a relay board.

Two Python Scripts are turning it on/off.
When I run the script manually it works, when I let crontab do it only "on" seems to work. I can not figure out what I did wrong.

I've read some posts and included a shebang, made the file writable,...

on.py

#!/usr/bin/python3
from gpiozero import OutputDevice
light = OutputDevice(2)
light.on()

off.py

#!/usr/bin/python3
from gpiozero import OutputDevice
light = OutputDevice(2)
light.off()

at "crontab -e" i've written:

0 11 * * * /home/pi/Desktop/off.py

Body:
Trap the detailed text of the error, as python sees it.
This updated version of your cron should do the trick:

0 11 * * * /home/pi/Desktop/off.py 1> /tmp/myerr.txt 2>&1

...and when it fails again, use a text editor to see if an error message is in /tmp/myerr.txt.

The following suggestions will help if the error is a problem with python locating/executing your gpio library.

One way to tell python the location of the library you're using is with some like this:

PYTHONPATH=/foo/bar/baz python somescript.py somecommand

as detailed in this well-voted answer.

Make sure to use absolute path(s) to files/folders in PYTHONPATH in both your cron invocation and your manual invocation;  this will eliminate the possibility that cron can't find your library because of a relative path issue.

As an alternaive to PYTHONPATH, you could use sys.path.append as detailed here.

This link and this link may be helpful for gpiozero installation issus.


问:
Using Machine Learning for Price Prediction
What Machine Learning Method should i Use to predict Prices like Stocks,gold and etc?

I Prefer using Python but I Can't Find the Starting Point as it Seems so Complicated to me and I've no Clue How to Start it.

答:
Talking about the machine learning method, Regression Method is used for Price prediction as it is used to predict a continuous variable. There are wide range of techniques for regression in machine learning. Starting from simple linear regression, SVR, RandomForest, CatBoost to RNN. Based on target problem, available datasets and computing resources, one of the algorithms can be used.

Yes, Python is the best language to get started into machinbre learning. And definitely, Linear Regression is the best way to start for this regression task if you are new. Gradually, you can start exploring other techniques in scikit-learn before directly jumping into RNN. Scikit-learn is the best machine learning library from beginners to professionals.


问:
I want to get the userid from firebase when i enter the email in ionic
I'm setting up a search method. So i want to get the userid from the authentication when i enter the email of specific account.

Note : I have registered users using createUserWithEmailAndPassword method..

答:
In order for a search function you will need a list of all users. And you can get the uid of the user by its email.

You can do this by using the firebase admin sdk.
https://firebase.google.com/docs/auth/admin/manage-users

It has a listusers function:

```<code>admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch(function(error) {
      console.log('Error listing users:', error);
    });
</code>```

And also have getuserbyemail function:

```<code>admin.auth().getUserByEmail(email)
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully fetched user data:', userRecord.toJSON());
  })
  .catch(function(error) {
   console.log('Error fetching user data:', error);
  });
</code>```

Body:
In order for a search function you will need a list of all users. And you can get the uid of the user by its email.

You can do this by using the firebase admin sdk.
https://firebase.google.com/docs/auth/admin/manage-users

It has a listusers function:

admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch(function(error) {
      console.log('Error listing users:', error);
    });

And also have getuserbyemail function:

admin.auth().getUserByEmail(email)
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully fetched user data:', userRecord.toJSON());
  })
  .catch(function(error) {
   console.log('Error fetching user data:', error);
  });


问:
Java [unchecked] unchecked case warning
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

```<code>Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }
</code>```

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

答:
You are not checking whether the object returned by

```<code>in.readObject();
</code>```

is really an

```<code>ArrayList<Dot>
</code>```

Use

```<code>ArrayList<Dot> dotList = null;
Object obj = in.readObject();
if (obj instanceof ArrayList<Dot>)
{
dotList = (ArrayList<Dot>) obj;
}
</code>```

Title: Java [unchecked] unchecked case warning

Body:
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

Body:
You are not checking whether the object returned by

in.readObject();

is really an

ArrayList<Dot>

Use

ArrayList<Dot> dotList = null;
Object obj = in.readObject();
if (obj instanceof ArrayList<Dot>)
{
dotList = (ArrayList<Dot>) obj;
}


问:
Not getting the desired output (conditionals+functions)
I'm a new to Python and a piece of code doesn't seem to work as desired.
Here is the code:

```<code>#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if type(string_input) == int:
    print("Input can not be an integer")
else:
    print(length_function(string_input))
</code>```

Whenever I type an integer in the result, it gives me the the number of digits in that integer. However, I want to display a message that "Input can not be an integer".

Is there any error in my code or is there another way of doing this. Please respond. Thank You!

答:
Even integers are taken as strings for example instead of 10 it is taking "10".</p>

```<code>def RepresentsInt(s):
try:
    int(s)
    return True
except ValueError:
    return False

def length_function(string):
length = len(string)
return length

string_input=input("Enter the string: ")
if RepresentsInt(String_input):
    print("Input can not be an integer")
else:
    print(length_function(string_input))
</code>```

Body:
I'm a new to Python and a piece of code doesn't seem to work as desired.
Here is the code:

#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if type(string_input) == int:
    print("Input can not be an integer")
else:
    print(length_function(string_input))

Whenever I type an integer in the result, it gives me the the number of digits in that integer. However, I want to display a message that "Input can not be an integer".

Is there any error in my code or is there another way of doing this. Please respond. Thank You!

Body:
Even integers are taken as strings for example instead of 10 it is taking "10".

def RepresentsInt(s):
try:
    int(s)
    return True
except ValueError:
    return False

def length_function(string):
length = len(string)
return length

string_input=input("Enter the string: ")
if RepresentsInt(String_input):
    print("Input can not be an integer")
else:
    print(length_function(string_input))


问:
How to uninstall NPM modules from the devDependencies in node.js?
How can I uninstall npm modules with devDependencies in Node.js?

答:
Use command:

1)npm uninstall <name of the module>

Also you can use:

1) npm uninstall <name of the module>: to remove the module from node_modules, but not package.json

2) npm uninstall <name of the module> --save: to also remove it from dependencies in package.json

3) npm uninstall <name of the module> --save-dev: to also remove it from devDependencies in package.json

4) npm -g uninstall <name of the module> --save: to remove it globally


问:
Pretrained keras model is returing the same result in android
I have created an image classifier in Keras, later I saved the model in pb format to use it in android.

However, in the python code, it can classify the image properly. But in android whatever image I gave as input the output is always the same .

This is how I have trained my model

```<code>rom keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

# Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')

classifier.fit_generator(training_set,
                         steps_per_epoch = 8000,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 2000)
classifier.summary()
classifier.save('saved_model.h5')

</code>```

Later I convert that keras model(saved_model.h5) to tensorflow model by using this

This is how I have converted my bitmap float array

```<code>    public static float[] getPixels(Bitmap bitmap) {

        final int IMAGE_SIZE = 64;

        int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];
        float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];

        if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
            // rescale the bitmap if needed
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
        }

        bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

        for (int i = 0; i < intValues.length; ++i) {
            final int val = intValues[i];
        // bitwise shifting - without our image is shaped [1, 64, 64, 1] but we need [1, 168, 168, 3]
            floatValues[i * 3 + 2] = Color.red(val) / 255.0f;
            floatValues[i * 3 + 1] = Color.green(val) / 255.0f;
            floatValues[i * 3] = Color.blue(val) / 255.0f;
        }
        return floatValues;
    }

</code>```

Later, I tried to classify image using tensorflow in android , like following .

```<code>TensorFlowInferenceInterface tensorFlowInferenceInterface;
tensorFlowInferenceInterface = new TensorFlowInferenceInterface(getAssets(),"model.pb");
float[] output = new float[2];
tensorFlowInferenceInterface.feed("conv2d_11_input",
                getPixels(bitmap), 1,64,64,3);
tensorFlowInferenceInterface.run(new String[]{"dense_12/Sigmoid"});
tensorFlowInferenceInterface.fetch("dense_12/Sigmoid",output);
</code>```

Whatever image I gave the value of the output is  [1,0]

Is there anything I have missed?

答:
The color components returned by Color.red(int), Color.blue(int) and Color.green(int) are integers in the range [0, 255] (see doc). The same thing holds when reading images using ImageDataGenerator of Keras. However, as I stated in comments section, in prediction phase you need to do the same preprocessing steps as done in training phase. You are scaling the image pixels by 1./255 in training (using rescale = 1./255 in ImageDataGenerator) and therefore, according to the first point I mentioned, this must also be done in prediction:

```<code>floatValues[i * 3 + 2] = Color.red(val) / 255.0;
floatValues[i * 3 + 1] = Color.green(val) / 255.0;
floatValues[i * 3] = Color.blue(val) / 255.0;
</code>```

Body:
I have created an image classifier in Keras, later I saved the model in pb format to use it in android.

However, in the python code, it can classify the image properly. But in android whatever image I gave as input the output is always the same .

This is how I have trained my model

rom keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

# Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')

classifier.fit_generator(training_set,
                         steps_per_epoch = 8000,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 2000)
classifier.summary()
classifier.save('saved_model.h5')

Later I convert that keras model(saved_model.h5) to tensorflow model by using this

This is how I have converted my bitmap float array

    public static float[] getPixels(Bitmap bitmap) {

        final int IMAGE_SIZE = 64;

        int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];
        float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];

        if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
            // rescale the bitmap if needed
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
        }

        bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

        for (int i = 0; i < intValues.length; ++i) {
            final int val = intValues[i];
        // bitwise shifting - without our image is shaped [1, 64, 64, 1] but we need [1, 168, 168, 3]
            floatValues[i * 3 + 2] = Color.red(val) / 255.0f;
            floatValues[i * 3 + 1] = Color.green(val) / 255.0f;
            floatValues[i * 3] = Color.blue(val) / 255.0f;
        }
        return floatValues;
    }

Later, I tried to classify image using tensorflow in android , like following .

TensorFlowInferenceInterface tensorFlowInferenceInterface;
tensorFlowInferenceInterface = new TensorFlowInferenceInterface(getAssets(),"model.pb");
float[] output = new float[2];
tensorFlowInferenceInterface.feed("conv2d_11_input",
                getPixels(bitmap), 1,64,64,3);
tensorFlowInferenceInterface.run(new String[]{"dense_12/Sigmoid"});
tensorFlowInferenceInterface.fetch("dense_12/Sigmoid",output);

Whatever image I gave the value of the output is  [1,0]

Is there anything I have missed?

Body:
The color components returned by Color.red(int), Color.blue(int) and Color.green(int) are integers in the range [0, 255] (see doc). The same thing holds when reading images using ImageDataGenerator of Keras. However, as I stated in comments section, in prediction phase you need to do the same preprocessing steps as done in training phase. You are scaling the image pixels by 1./255 in training (using rescale = 1./255 in ImageDataGenerator) and therefore, according to the first point I mentioned, this must also be done in prediction:

floatValues[i * 3 + 2] = Color.red(val) / 255.0;
floatValues[i * 3 + 1] = Color.green(val) / 255.0;
floatValues[i * 3] = Color.blue(val) / 255.0;


问:
how to pass a function or functions between src blocks in org-mode (do not use :session, use :var or others instead)
I want to share a function between different src blocks in org-mode. Certainly, we could use :session in org-mode. However, it may cause errors if the variable names are the same.

I would like to use the function repeatedly in different sessions. How can I do it? I try :var, but I failed to pass functions, such as :var theme_ls1=theme; :var theme_ls1()=theme.

It would be better if the function keeps the form theme_ls() in the second src block. Maybe can we include src blocks in a single org file.

I show a correct example by using :session.

```<code>* block 1
  #+NAME: theme
  #+BEGIN_SRC R :session info :exports none
    ## Theme for plot
    theme_ls1 <- function(..., bg='white'){
    require(grid)
    theme_classic(...) +
        theme(
        panel.background=element_rect(fill='transparent', color='blue'),
        panel.border=element_rect(fill='transparent', color='transparent'),
        panel.grid=element_blank(),
        plot.margin=unit(c(0.4,0.4,0.4,0.4),"mm")
        )
    }
  #+END_SRC

* block 2
  #+BEGIN_SRC R :exports results :results output graphics :session info :file exp1.1.png :width 400 :height 300
    #!/usr/bin/env Rscript
    ## library
    library(ggplot2)

    ## data
    dt <- data.frame(x=-6:6, y=-6:6)

    ## pic
    pp1 <- ggplot(data=dt, aes(x=x, y=y))+
    geom_point()+
    scale_x_continuous(limits=c(-6,6), breaks=-6:6)+
    scale_y_continuous(limits=c(-6,6), breaks=-6:6)+
    theme_ls1()
    pp1
  #+END_SRC

</code>```

Ref: https://emacs.stackexchange.com/questions/19073/org-mode-passing-variables-between-code-blocks-without-sessions , but different

答:
I don't really understand why you wouldn't want to use a session here -- having variable conflicts should be a problem -- otherwise I think a proper design would put your reusable code in a proper namespace.

But, it seems an ugly workaround could be to use eval(parse(...)), which is generally considered bad practice.

```<code>* block 1
#+NAME: theme
#+BEGIN_SRC R :exports none :results output
## Theme for plot
theme_ls1 <- function(..., bg='white'){
    require(grid)
    theme_classic(...) +
        theme(
            panel.background=element_rect(fill='transparent', color='blue'),
            panel.border=element_rect(fill='transparent', color='transparent'),
            panel.grid=element_blank(),
            plot.margin=unit(c(0.4,0.4,0.4,0.4),"mm")
        )
}
theme_ls1
#+END_SRC

* block 2
#+BEGIN_SRC R :exports results :results output graphics :var theme_ls1=theme :file exp1.1.png :width 400 :height 300

library(ggplot2)
theme_ls1 <- eval(parse(text=theme_ls1))

## data
dt <- data.frame(x=-6:6, y=-6:6)

## pic
pp1 <- ggplot(data=dt, aes(x=x, y=y)) +
    geom_point() +
    scale_x_continuous(limits=c(-6,6), breaks=-6:6) +
    scale_y_continuous(limits=c(-6,6), breaks=-6:6) +
    theme_ls1()
pp1
#+END_SRC
</code>```

Body:
I want to share a function between different src blocks in org-mode. Certainly, we could use :session in org-mode. However, it may cause errors if the variable names are the same.

I would like to use the function repeatedly in different sessions. How can I do it? I try :var, but I failed to pass functions, such as :var theme_ls1=theme; :var theme_ls1()=theme.

It would be better if the function keeps the form theme_ls() in the second src block. Maybe can we include src blocks in a single org file.

I show a correct example by using :session.

* block 1
  #+NAME: theme
  #+BEGIN_SRC R :session info :exports none
    ## Theme for plot
    theme_ls1 <- function(..., bg='white'){
    require(grid)
    theme_classic(...) +
        theme(
        panel.background=element_rect(fill='transparent', color='blue'),
        panel.border=element_rect(fill='transparent', color='transparent'),
        panel.grid=element_blank(),
        plot.margin=unit(c(0.4,0.4,0.4,0.4),"mm")
        )
    }
  #+END_SRC

* block 2
  #+BEGIN_SRC R :exports results :results output graphics :session info :file exp1.1.png :width 400 :height 300
    #!/usr/bin/env Rscript
    ## library
    library(ggplot2)

    ## data
    dt <- data.frame(x=-6:6, y=-6:6)

    ## pic
    pp1 <- ggplot(data=dt, aes(x=x, y=y))+
    geom_point()+
    scale_x_continuous(limits=c(-6,6), breaks=-6:6)+
    scale_y_continuous(limits=c(-6,6), breaks=-6:6)+
    theme_ls1()
    pp1
  #+END_SRC

Ref: https://emacs.stackexchange.com/questions/19073/org-mode-passing-variables-between-code-blocks-without-sessions , but different

Body:
I don't really understand why you wouldn't want to use a session here -- having variable conflicts should be a problem -- otherwise I think a proper design would put your reusable code in a proper namespace.

But, it seems an ugly workaround could be to use eval(parse(...)), which is generally considered bad practice.

* block 1
#+NAME: theme
#+BEGIN_SRC R :exports none :results output
## Theme for plot
theme_ls1 <- function(..., bg='white'){
    require(grid)
    theme_classic(...) +
        theme(
            panel.background=element_rect(fill='transparent', color='blue'),
            panel.border=element_rect(fill='transparent', color='transparent'),
            panel.grid=element_blank(),
            plot.margin=unit(c(0.4,0.4,0.4,0.4),"mm")
        )
}
theme_ls1
#+END_SRC

* block 2
#+BEGIN_SRC R :exports results :results output graphics :var theme_ls1=theme :file exp1.1.png :width 400 :height 300

library(ggplot2)
theme_ls1 <- eval(parse(text=theme_ls1))

## data
dt <- data.frame(x=-6:6, y=-6:6)

## pic
pp1 <- ggplot(data=dt, aes(x=x, y=y)) +
    geom_point() +
    scale_x_continuous(limits=c(-6,6), breaks=-6:6) +
    scale_y_continuous(limits=c(-6,6), breaks=-6:6) +
    theme_ls1()
pp1
#+END_SRC


问:
Does Lucene.Net 4.8.0 support Azure Blob Storage to create index?
I am using Lucene.Net 4.8.0 but it's not supporting to create the index and store it in Azure Blob Storage Container. Is there any workaround for that? Or have I overlooked any feature that is already available? Below is the code snippet that I used and the screen shot with the compilation error. Any solution probably with the sample code snippet will be much appreciated.

Note: The below code is working perfectly in Lucene.Net 3.0.3.

```<code>CloudStorageAccount storageAccount =
CloudStorageAccount.Parse(AzureConfig.StorageConnectionString);
IndexWriter indexWriter = new IndexWriter(azureDir, indexWriterConfig);
</code>```

答:
I had the same issue and we need wait or open code on github and make changes.
If you trying to use AzureDirectory (like i see that) make the same path with changes on the Azure Directory. I would like advise you that the interfaces on 4.8 changes and probabily will be necessary hard work to change.

Body:
I am using Lucene.Net 4.8.0 but it's not supporting to create the index and store it in Azure Blob Storage Container. Is there any workaround for that? Or have I overlooked any feature that is already available? Below is the code snippet that I used and the screen shot with the compilation error. Any solution probably with the sample code snippet will be much appreciated.

Note: The below code is working perfectly in Lucene.Net 3.0.3.

CloudStorageAccount storageAccount =
CloudStorageAccount.Parse(AzureConfig.StorageConnectionString);
IndexWriter indexWriter = new IndexWriter(azureDir, indexWriterConfig);


问:
Why Python doesnt see an existing module
I made an app for analysing data, all in one file, but i read that it needs to be made in objective style. Trying to make it objective I get an error that module doesnt have attribute (which it has)

Tried to disable linting and organise code in a different way but end up with this error all the time

file - analyser.py

```<code>import argparse
import helper

class analyser:

    def __init__(self):
        pass

    def cli(self):

     #some code

if __name__ == '__main__':
    analyser.cli
    helper.analyse(arguments)
</code>```

file - helper.py

```<code>import csv

class helper:

    def __init__(self):
        pass

    def analyse(self, arguments):

    #code
</code>```

I get
AttributeError: module 'analyser' has no attribute 'analyse'

答:
The module helper does not have an attribute analyse. However, the class helper does have one. You can do one of the following to access the analyse function:

```<code>from helper import helper
...
helper.analyse(arguments)
</code>```

Or

```<code>import helper
...
helper.helper.analyse(arguments)
</code>```

At the moment, the 2 classes helper and analyser are redundant. You may be better off just using functions. Object-oriented programming is useful in certain circumstances to encapsulate data and for abstraction, but functional programming has its own uses and it is good to know when to use either.

Body:
I made an app for analysing data, all in one file, but i read that it needs to be made in objective style. Trying to make it objective I get an error that module doesnt have attribute (which it has)

Tried to disable linting and organise code in a different way but end up with this error all the time

file - analyser.py

import argparse
import helper

class analyser:

    def __init__(self):
        pass

    def cli(self):

     #some code

if __name__ == '__main__':
    analyser.cli
    helper.analyse(arguments)

file - helper.py

import csv

class helper:

    def __init__(self):
        pass

    def analyse(self, arguments):

    #code

I get
AttributeError: module 'analyser' has no attribute 'analyse'

Body:
The module helper does not have an attribute analyse. However, the class helper does have one. You can do one of the following to access the analyse function:

from helper import helper
...
helper.analyse(arguments)

Or

import helper
...
helper.helper.analyse(arguments)

At the moment, the 2 classes helper and analyser are redundant. You may be better off just using functions. Object-oriented programming is useful in certain circumstances to encapsulate data and for abstraction, but functional programming has its own uses and it is good to know when to use either.


问:
Readtimeout error for API data with Sodapy client
I'm trying to make API calls on the consumer complaint dataset, available online (hhttps://data.consumerfinance.gov/dataset/Consumer-Complaints/s6ew-h6mp) with the SodaPy library (https://github.com/xmunoz/sodapy). I just want to get the csv data, the webpage says it has 906182 rows,

I've followed the example on GitHub as best as I can, but it's just not working. Here's the code:

```<code>from sodapy import Socrata

client = Socrata("data.consumerfinance.gov", "apptoken", username="myusername", password="mypassword")

results = client.get("s6ew-h6mp")
</code>```

I want to get the entire dataset,but I keep getting the following error:

```<code>ReadTimeout: HTTPSConnectionPool(host='data.consumerfinance.gov', port=443): Read timed out. (read timeout=10)
</code>```

Any clues on how to work through this?

答:
Looking into the source code on GitHub, the constructor of Socrata has a parameter for the time out. The following code example will increase the timeout time from 10 to 25 seconds:

```<code>from sodapy import Socrata
client = Socrata("data.consumerfinance.gov", "apptoken", timeout=25)
results = client.get("s6ew-h6mp")
</code>```

Body:
I'm trying to make API calls on the consumer complaint dataset, available online (hhttps://data.consumerfinance.gov/dataset/Consumer-Complaints/s6ew-h6mp) with the SodaPy library (https://github.com/xmunoz/sodapy). I just want to get the csv data, the webpage says it has 906182 rows,

I've followed the example on GitHub as best as I can, but it's just not working. Here's the code:

from sodapy import Socrata

client = Socrata("data.consumerfinance.gov", "apptoken", username="myusername", password="mypassword")

results = client.get("s6ew-h6mp")

I want to get the entire dataset,but I keep getting the following error:

ReadTimeout: HTTPSConnectionPool(host='data.consumerfinance.gov', port=443): Read timed out. (read timeout=10)

Any clues on how to work through this?

Body:
Looking into the source code on GitHub, the constructor of Socrata has a parameter for the time out. The following code example will increase the timeout time from 10 to 25 seconds:

from sodapy import Socrata
client = Socrata("data.consumerfinance.gov", "apptoken", timeout=25)
results = client.get("s6ew-h6mp")


问:
Provide a timeout in Python program
I am writing a program in python that accepts two inputs.

Once the user gives the first input, he gets 10 seconds to give the second input.
If the user is able to provide the second value within those 10 seconds and presses the enter key, the timer stops and goes to the next part of the program.

Is there any functionality in python that allows me to provide an interrupt after the 10 seconds and stop accepting the second input. And if the second input is given, stop the timer.

答:
You can create a custom Timer class and start it in a diffrent thread. Once the timeout occurs (after 10 seconds), you can send a SIGINT signal back to the parent thread, which will raise the KeyboardInterrupt exception that we catch in the main() function. Otherwise you can stop the Timer, after user enters the second input in the right time, which will then stop the Timer thread. Further, we can check if the KeyboardInterrupt happened due to timeout or user action.

Note: While we are sending the signal to the main process, we also need to check, on which platform we are running the programm. See signal.CTRL_C_EVENT and signal.SIGINT.

Demo: https://repl.it/repls/StandardBuoyantProtools

Solution:

```<code>import time
import threading
import os
import signal

class Timer(threading.Thread):
    _timeout = False
    _timer = 0
    _stopped = False

    def __init__(self, delay):
        super(Timer, self).__init__()
        self.restart(delay)

    def is_timeout(self):
        return self._timeout

    def stop(self):
        self._stopped = True

    def restart(self, delay):
        self._stopped = False
        self._timer = time.time() + delay

    def run(self):

        while not self._stopped:
            time.sleep(0.1)
            if time.time() >= self._timer:
                break
        if not self._stopped:
            self._timeout = True

            # check os name
            if os.name == 'nt':
                # we are on Windows
                os.kill(os.getpid(), signal.CTRL_C_EVENT)
            else:
                # we are on a Posix/Unix (or very unlikely on java) system
                os.kill(os.getpid(), signal.SIGINT)

def main():
    first_input = input('First input:')

    delay = 10
    timer = Timer(delay)
    timer.daemon = True

    try:
        print('\nStarting the timer for the second input %r second(s)' % delay)
        timer.start()

        second_input = input('Second input:')

        print('\nWell done. Stopping the timer!\n')
        timer.stop()

        print('Input values: %r %r\n' % (first_input, second_input))

        # do your stuff here...

    except KeyboardInterrupt:
        if timer.is_timeout():
            print("\nTimeout!")
        else:
            print("\nUser interrupted the input")

main()
</code>```

Title: Provide a timeout in Python program

Body:
You can create a custom Timer class and start it in a diffrent thread. Once the timeout occurs (after 10 seconds), you can send a SIGINT signal back to the parent thread, which will raise the KeyboardInterrupt exception that we catch in the main() function. Otherwise you can stop the Timer, after user enters the second input in the right time, which will then stop the Timer thread. Further, we can check if the KeyboardInterrupt happened due to timeout or user action.

Note: While we are sending the signal to the main process, we also need to check, on which platform we are running the programm. See signal.CTRL_C_EVENT and signal.SIGINT.

Demo: https://repl.it/repls/StandardBuoyantProtools

Solution:

import time
import threading
import os
import signal

class Timer(threading.Thread):
    _timeout = False
    _timer = 0
    _stopped = False

    def __init__(self, delay):
        super(Timer, self).__init__()
        self.restart(delay)

    def is_timeout(self):
        return self._timeout

    def stop(self):
        self._stopped = True

    def restart(self, delay):
        self._stopped = False
        self._timer = time.time() + delay

    def run(self):

        while not self._stopped:
            time.sleep(0.1)
            if time.time() >= self._timer:
                break
        if not self._stopped:
            self._timeout = True

            # check os name
            if os.name == 'nt':
                # we are on Windows
                os.kill(os.getpid(), signal.CTRL_C_EVENT)
            else:
                # we are on a Posix/Unix (or very unlikely on java) system
                os.kill(os.getpid(), signal.SIGINT)

def main():
    first_input = input('First input:')

    delay = 10
    timer = Timer(delay)
    timer.daemon = True

    try:
        print('\nStarting the timer for the second input %r second(s)' % delay)
        timer.start()

        second_input = input('Second input:')

        print('\nWell done. Stopping the timer!\n')
        timer.stop()

        print('Input values: %r %r\n' % (first_input, second_input))

        # do your stuff here...

    except KeyboardInterrupt:
        if timer.is_timeout():
            print("\nTimeout!")
        else:
            print("\nUser interrupted the input")

main()


问:
URL rewriting problem during browser back
I am following the scottgu's tutorial and it's working fine except when I press the browser back button.

WHen I go back to the previous page, it does not display data for that page, I cannot debug the page also using breakpoint is VS, when I go back and refresh the page, the data is shown.

How to rectify this ?

tutorial:  http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

I am using Approach 2: Using an HttpModule to Perform URL Rewriting

EDIT: It's working fine in Chrome.

I show "data does not exist" when the data does not exist.I removed that from my webpage and ran that page in IE 9, but it funny that IE still displays "data does not exist".  I cleared the browser history also. Still did not work.

EDIT: I uninstalled IE 9 to IE 8 and it works perfectly.

Moderators: Please see what can be done to this question(delete ?) as there is no answer possible to this question.

答:
It was due to IE 9

I rolled back to IE 8 and it worked smooth.


问:
Check for multiple numbers in an array
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:

```<code>  var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
  var string = "";
  var len = array.length;
</code>```

After declaring the variables, i start to loop them:

```<code>  for (var i = 0; i < len; i ++) {
     for (var j = 0; j < len; j ++) {
        //console.log(array[i], array[j]);
     }
  }
</code>```

Console prints me value in this order:

```<code>3 3
3 6
3 67
. .
6 3
6 6
6 67
. .
</code>```

I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.

答:
You need to iterate in the outer loop until the element before the last item and in the inner loop start from the actual index plus one, to prevent to check the same element.

If duplicate is found, push the value to the duplicates array.

var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
    len = array.length,
    i, j,
    duplicates = [];

for (i = 0; i < len - 1; i++) {
  for (j = i + 1; j < len; j++) {
    if (array[i] === array[j]) duplicates.push(array[i]);
  }
}

console.log(duplicates);```
</div>
</div>
</p>

<p>A shorter approach by using a <code>Set</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
    found = new Set,
    duplicates = array.filter(v => found.has(v) || !found.add(v));

console.log(duplicates);</code>```

Title: Check for multiple numbers in an array

Body:
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:

  var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
  var string = "";
  var len = array.length;

After declaring the variables, i start to loop them:

  for (var i = 0; i < len; i ++) {
     for (var j = 0; j < len; j ++) {
        //console.log(array[i], array[j]);
     }
  }

Console prints me value in this order:

3 3
3 6
3 67
. .
6 3
6 6
6 67
. .

I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.

Body:
You need to iterate in the outer loop until the element before the last item and in the inner loop start from the actual index plus one, to prevent to check the same element.

If duplicate is found, push the value to the duplicates array.

var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
    len = array.length,
    i, j,
    duplicates = [];

for (i = 0; i < len - 1; i++) {
  for (j = i + 1; j < len; j++) {
    if (array[i] === array[j]) duplicates.push(array[i]);
  }
}

console.log(duplicates);

A shorter approach by using a Set

var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
    found = new Set,
    duplicates = array.filter(v => found.has(v) || !found.add(v));

console.log(duplicates);


问:
How to check which RecyclerView has been clicked
I have a view with two RecyclerViews. They have different ArrayLists, but the same kind of adapters. In the OnClick method in my activity, I want to get which of the Recyclers has been clicked, and then get the item selected.

I tried using view instanceof RecylcerView but that didn't do the trick.

答:
You can add onClickListener to the child layout of relativeLayout.

Considering, first RecyclerView has a LinearLayout, and second one has RelativeLayout inside them (What I mean here is that I have considered LinearLayout is the parent layout of individual item in first RecyclerView and RelativeLayout is the parent layout of individual item in second RecyclerView).

```<code>linLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        getParentName(v);
    }
});
    relLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        getParentName(v);
    }
});
private void getParentName (View v){
    View view = (View) v.getParent();
    switch (view.getId()) {
        case R.id.linLayout:
            Toast.makeText(MainActivity.this, "First One", Toast.LENGTH_SHORT).show();
            break;
        case R.id.relLayout:
            Toast.makeText(MainActivity.this, "Second One", Toast.LENGTH_SHORT).show();
            break;
    }
}
</code>```

We know that if it is LinearLayout then its parent is first RecyclerView.
If it is RelativeLayout then its parent is second RecyclerView.

But by using this above mentioned method, we can make root layout of individual child views to have same Layout (LinearLayout or RelativeLayout) and see that the above funtion works.

Body:
You can add onClickListener to the child layout of relativeLayout.

Considering, first RecyclerView has a LinearLayout, and second one has RelativeLayout inside them (What I mean here is that I have considered LinearLayout is the parent layout of individual item in first RecyclerView and RelativeLayout is the parent layout of individual item in second RecyclerView).

linLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        getParentName(v);
    }
});
    relLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        getParentName(v);
    }
});
private void getParentName (View v){
    View view = (View) v.getParent();
    switch (view.getId()) {
        case R.id.linLayout:
            Toast.makeText(MainActivity.this, "First One", Toast.LENGTH_SHORT).show();
            break;
        case R.id.relLayout:
            Toast.makeText(MainActivity.this, "Second One", Toast.LENGTH_SHORT).show();
            break;
    }
}

We know that if it is LinearLayout then its parent is first RecyclerView.
If it is RelativeLayout then its parent is second RecyclerView.

But by using this above mentioned method, we can make root layout of individual child views to have same Layout (LinearLayout or RelativeLayout) and see that the above funtion works.


问:
Flask doesn't print to console
I'm new to flask, and I'm trying to add print info to debug server side code.
When launch my flask app with debug=True, i can't get any info print to console

I tried to use logging instead, but no success.
So how to debug flask program with console.

```<code>@app.route('/getJSONResult', methods=['GET', 'POST'])
def getJSONResult():

    if request.method == 'POST':
        uut = request.form['uut']
        notes = request.form['notes']
        temperature = request.form['temperature']

        logging.info("enter getJSONReuslt")
        print('enter getJSONReuslt')
        filter_by_query = {k: v for k, v in {
            'uut': uut, 'notes': notes, 'temperature': temperature}.items() if v != ""}
        s = session.query(UUT_TEST_INFO).filter_by(**filter_by_query).first()
        return jsonify(s.serialize)

if __name__ == '__main__':
    app.secret_key = ''.join(random.choice(
        string.ascii_uppercase + string.digits) for x in range(32))
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /qyer HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:51] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:21:58] "POST /getJSONResult HTTP/1.1" 500 -
</code>```

I fixed server side 500 error issue, now request get 200 code, and console displays following info

```<code>$ python project.py
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
WARNING:werkzeug: * Debugger is active!
INFO:werkzeug: * Debugger pin code: 158-624-607
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:33] "GET /qyer HTTP/1.1" 200 -
INFO:root:Enter getJSONResult
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:43] "POST /getJSONResult HTTP/1.1" 200 -
</code>```

Still no info from print command

答:
You can force to flush stdout directly from print:

```<code>print('enter getJSONReuslt', flush=True)
</code>```

This way you don't have to print to sys.stderr (which flushes by default).

The reason for your problem is line buffering. Line buffering makes I/O more efficient with the drawback of not immediately showing prints under some conditions.

Title: Flask doesn't print to console

Body:
I'm new to flask, and I'm trying to add print info to debug server side code.
When launch my flask app with debug=True, i can't get any info print to console

I tried to use logging instead, but no success.
So how to debug flask program with console.

@app.route('/getJSONResult', methods=['GET', 'POST'])
def getJSONResult():

    if request.method == 'POST':
        uut = request.form['uut']
        notes = request.form['notes']
        temperature = request.form['temperature']

        logging.info("enter getJSONReuslt")
        print('enter getJSONReuslt')
        filter_by_query = {k: v for k, v in {
            'uut': uut, 'notes': notes, 'temperature': temperature}.items() if v != ""}
        s = session.query(UUT_TEST_INFO).filter_by(**filter_by_query).first()
        return jsonify(s.serialize)

if __name__ == '__main__':
    app.secret_key = ''.join(random.choice(
        string.ascii_uppercase + string.digits) for x in range(32))
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /qyer HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:51] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:21:58] "POST /getJSONResult HTTP/1.1" 500 -

I fixed server side 500 error issue, now request get 200 code, and console displays following info

$ python project.py
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
WARNING:werkzeug: * Debugger is active!
INFO:werkzeug: * Debugger pin code: 158-624-607
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:33] "GET /qyer HTTP/1.1" 200 -
INFO:root:Enter getJSONResult
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:43] "POST /getJSONResult HTTP/1.1" 200 -

Still no info from print command

Body:
You can force to flush stdout directly from print:

print('enter getJSONReuslt', flush=True)

This way you don't have to print to sys.stderr (which flushes by default).

The reason for your problem is line buffering. Line buffering makes I/O more efficient with the drawback of not immediately showing prints under some conditions.


问:
How do I place the image beneath the paragraph when I resize the browser screen?
So I have a paragraph on the left side of the screen and my image on the right side of the screen. It is responsive but not the way I want it to be. When I resize the browser screen, I want the picture to display beneath the paragraph i.e. I want the paragraph to be on top of the image and the image should be below the paragraph. When I try to resize the window, the image just becomes short but does not move to the next line.

I am currently using  CSS grid system to display the paragraph on the left and the image on the right. I also have the whole thing inside a container. I am also using flex box to make it responsive but that just wont help. I have also tried to use media queries but I just don't know how to tell the media query to move the image below the paragraph.

答:
If you are using Flexbox, try using flex-wrap, this will force elements to the next line or 'underneath' if their max-width is reached.

CSS:

```<code>.container {
    display: flex;
    flex-wrap: wrap;
    img {
        width: 100px;
    }
    p {
        width: 100px;
    }
}
</code>```

HTML:

```<code><div class="container">
    <img src="your_image.jpg" alt="">
    <p>Here is your text</p>
</div>
</code>```

Body:
If you are using Flexbox, try using flex-wrap, this will force elements to the next line or 'underneath' if their max-width is reached.

CSS:

.container {
    display: flex;
    flex-wrap: wrap;
    img {
        width: 100px;
    }
    p {
        width: 100px;
    }
}

HTML:

<div class="container">
    <img src="your_image.jpg" alt="">
    <p>Here is your text</p>
</div>


问:
Writing Scrapy Python Output to JSON file
I'm new to Python and web scraping. In this program I want to write final output (product name and price from all 3 links) to JSON file. Please help!</p>

```<code>    import scrapy
    from time import sleep
    import csv, os, json
    import random

    class spider1(scrapy.Spider):
        name = "spider1"

        def start_requests(self):
            list = [
                "https://www. example.com/item1",
                "https://www. example.com/item2",
                "https://www. example.com/item3"]

            for i in list:
                yield scrapy.Request(i, callback=self.parse)
                sleep(random.randint(0, 5))

        def parse(self, response):
            product_name = response.css('#pd-h1-cartridge::text')[0].extract()
            product_price = response.css(
                '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
                '::text')[3].extract()

            name = str(product_name).strip()
            price = str(product_price).replace('\n', "")

data = {name, price}

yield data

extracted_data = []
    while i < len(data):

        extracted_data.append()
        sleep(5)
    f = open('data.json', 'w')
    json.dump(extracted_data, f, indent=4)
</code>```

答:
You don't need to create a file scrapy can do it, Firstly create a ItemLoader and Item when you return the item in the last parse, if you need this data in a json format, you can add a parameter -o when crawl the spider

for example:

```<code>scrapy crawl <spidername> -o <filename>.json
</code>```

Body:
I'm new to Python and web scraping. In this program I want to write final output (product name and price from all 3 links) to JSON file. Please help!

    import scrapy
    from time import sleep
    import csv, os, json
    import random

    class spider1(scrapy.Spider):
        name = "spider1"

        def start_requests(self):
            list = [
                "https://www. example.com/item1",
                "https://www. example.com/item2",
                "https://www. example.com/item3"]

            for i in list:
                yield scrapy.Request(i, callback=self.parse)
                sleep(random.randint(0, 5))

        def parse(self, response):
            product_name = response.css('#pd-h1-cartridge::text')[0].extract()
            product_price = response.css(
                '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
                '::text')[3].extract()

            name = str(product_name).strip()
            price = str(product_price).replace('\n', "")

data = {name, price}

yield data

extracted_data = []
    while i < len(data):

        extracted_data.append()
        sleep(5)
    f = open('data.json', 'w')
    json.dump(extracted_data, f, indent=4)

Body:
You don't need to create a file scrapy can do it, Firstly create a ItemLoader and Item when you return the item in the last parse, if you need this data in a json format, you can add a parameter -o when crawl the spider

for example:

scrapy crawl <spidername> -o <filename>.json


问:
Log4J - Is there any point in explicitly specifying the class name in the call to LogManager.getLogger()?
I'm working on some legacy code with a lot of code like

```<code>private final Logger logger = LogManager.getLogger(ThisClassName.class);
</code>```

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

```<code>LogManager.getLogger(getClass());
</code>```

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

答: If you're making the Logger static, you can't use getClass().

OwnerDisplayName: nc

ContentLicense: CC BY-SA 2.5

Body:
I'm working on some legacy code with a lot of code like

private final Logger logger = LogManager.getLogger(ThisClassName.class);

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

LogManager.getLogger(getClass());

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

OwnerDisplayName: mmyers


问:
How to write ... after 5 characters
I'm beginner and I have a question. I would like that if my text is more than 5 characters, that it writes 5 characters + ... . It's for shortening a name in navbar if its too long, it causes bugs in my nav.

Here's an example of desired result:

My text: TheTest

output: TheTe...

I think I could do this with strlen() but have no idea how to do this. Maybe with an overflow ?

I tried to do it with text-overflow: ellipsis; but it didn't work either
Can you help me please ?

答:
just check the length to see if its more than 5 character or not

```<code>$mesage="This is text String";

if(strlen($mesage)>5){

    echo substr($mesage,0,5)."...";
}
else{

    echo $mesage;
}
</code>```

More infos about strlen(): http://www.php.net/manual/de/function.strlen.php

 substr():           https://www.php.net/manual/en/function.substr.php

Title: How to write ... after 5 characters

Body:
just check the length to see if its more than 5 character or not

$mesage="This is text String";

if(strlen($mesage)>5){

    echo substr($mesage,0,5)."...";
}
else{

    echo $mesage;
}

More infos about strlen(): http://www.php.net/manual/de/function.strlen.php

 substr():           https://www.php.net/manual/en/function.substr.php


问:
How can i see the username of my followers in instagram
I want to see the list of my followers in Instagram by python. I write this code

```<code>from InstagramAPI import InstagramAPI
username="*******"
InstagramAPI = InstagramAPI(username, "******")
InstagramAPI.login()
InstagramAPI.getProfileData()
followers = InstagramAPI.getTotalSelfFollowers()
print (followers[0])
</code>```

It works fine and show

```<code>{u'username': u'yasinyasinyasinl', u'has_anonymous_profile_picture': True, u'profile_pic_url': u'https://instagram.fevn1-1.fna.fbcdn.net/vp/19319123fc5a0016b6fd518cfa7058ce/5D7C0DF1/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.fevn1-1.fna.fbcdn.net', u'full_name': u'yasin', u'pk': 5580539929, u'is_verified': False, u'is_private': True}
</code>```

I want to get all the keys
I try

```<code>for a,b in followers[0]:
  print (followers[0].keys())
</code>```

But it did not work.
What should I do?

and

```<code>print (followers[0].get(username))
None
</code>```

答:
Guessing from your question, I take it that followers is a list with dict elements.

This means that followers[0] will be a single dict containing the information for one of your followers. If you want to display that username, just fetch it without a loop using followers[0]['username'].

If you want to display all your followers, loop over the list instead:

```<code>for follower in followers:
  print(follower['username'])
</code>```

Extra hint: know that you can easily get a list of your follower's usernames using Python's beautiful list comprehension: [follower['username'] for follower in followers].

Hope this help!

Body:
I want to see the list of my followers in Instagram by python. I write this code

from InstagramAPI import InstagramAPI
username="*******"
InstagramAPI = InstagramAPI(username, "******")
InstagramAPI.login()
InstagramAPI.getProfileData()
followers = InstagramAPI.getTotalSelfFollowers()
print (followers[0])

It works fine and show

{u'username': u'yasinyasinyasinl', u'has_anonymous_profile_picture': True, u'profile_pic_url': u'https://instagram.fevn1-1.fna.fbcdn.net/vp/19319123fc5a0016b6fd518cfa7058ce/5D7C0DF1/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.fevn1-1.fna.fbcdn.net', u'full_name': u'yasin', u'pk': 5580539929, u'is_verified': False, u'is_private': True}

I want to get all the keys
I try

for a,b in followers[0]:
  print (followers[0].keys())

But it did not work.
What should I do?

and

print (followers[0].get(username))
None

Body:
Guessing from your question, I take it that followers is a list with dict elements.

This means that followers[0] will be a single dict containing the information for one of your followers. If you want to display that username, just fetch it without a loop using followers[0]['username'].

If you want to display all your followers, loop over the list instead:

for follower in followers:
  print(follower['username'])

Extra hint: know that you can easily get a list of your follower's usernames using Python's beautiful list comprehension: [follower['username'] for follower in followers].

Hope this help!


问:
Finding the elements in list such that elements should not have similar numbers
Consider a list = [23,52,44,32,78]
23,52,32 all these elements have at least one digit common so the set i want to filter is [44,78] as they don't have any common numbers.

Another example: [52,12,255,211,223,123,64,87,999] would be filtered as [64,87,999]

My current idea is to convert all the numbers into list like [2,3],[5,2]... and take a intersection of those but i couldn't understand how to compare all these sub-lists and filter out the desired numbers.

```<code>def convert_into_sublist(i):
    sublist = [int(x) for x in str(i)]

def intersection(l1, l2):
    l3 = [value for value in l1 if value in l2]
    if(len(l3)==0):
        return 1
</code>```

答:
handle the numbers as a list of characters and use set conversion and test if disjoint. Maybe not the most performant one-liner but works:

```<code>lst = [23,52,44,32,78]
# optional: remove duplicates:
lst = set(lst)

unique = [l for l in lst if all(set(str(x)).isdisjoint(str(l)) for x in lst if x != l)]
</code>```

result:

```<code>>>> unique
[44, 78]
</code>```

maybe slightly faster: convert to string once, process strings, convert back to integers in the end:

```<code>lst = [str(x) for x in lst]
unique = [int(l) for l in lst if all(set(x).isdisjoint(l) for x in lst if x != l)]
</code>```

Body:
Consider a list = [23,52,44,32,78]
23,52,32 all these elements have at least one digit common so the set i want to filter is [44,78] as they don't have any common numbers.

Another example: [52,12,255,211,223,123,64,87,999] would be filtered as [64,87,999]

My current idea is to convert all the numbers into list like [2,3],[5,2]... and take a intersection of those but i couldn't understand how to compare all these sub-lists and filter out the desired numbers.

def convert_into_sublist(i):
    sublist = [int(x) for x in str(i)]

def intersection(l1, l2):
    l3 = [value for value in l1 if value in l2]
    if(len(l3)==0):
        return 1

Body:
handle the numbers as a list of characters and use set conversion and test if disjoint. Maybe not the most performant one-liner but works:

lst = [23,52,44,32,78]
# optional: remove duplicates:
lst = set(lst)

unique = [l for l in lst if all(set(str(x)).isdisjoint(str(l)) for x in lst if x != l)]

result:

>>> unique
[44, 78]

maybe slightly faster: convert to string once, process strings, convert back to integers in the end:

lst = [str(x) for x in lst]
unique = [int(l) for l in lst if all(set(x).isdisjoint(l) for x in lst if x != l)]


问:
How to check if an id value exists in an object array
Given an array "posts" of objects {id: "x", title: "title"}, i need to verify whether there is a previously entered id before entering a new post (via form in which id is a field).

I tried looping through posts, but it causes problems on entering repeated new data. Thank you for your help, this is driving me mad.

```<code>// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }
    };
});
</code>```

答:
This should work:</p>

```<code>if (postExists(posts, id)){
    // invlaid post entry
} else {
    // add new post
}

function postExists(posts, id) {
    return posts.some(function(post){
        return post.id == id;
    });
}
</code>```

Body:
Given an array "posts" of objects {id: "x", title: "title"}, i need to verify whether there is a previously entered id before entering a new post (via form in which id is a field).

I tried looping through posts, but it causes problems on entering repeated new data. Thank you for your help, this is driving me mad.

// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }
    };
});

Body:
This should work:

if (postExists(posts, id)){
    // invlaid post entry
} else {
    // add new post
}

function postExists(posts, id) {
    return posts.some(function(post){
        return post.id == id;
    });
}