问:
How to save a Array with (Multiple Types) in NSUserDefaults
This is pretty simple but can't seem to find the correct information to solve saving an array like this in User Defaults.

It says it's not a property that NSUser Defaults Excepts.

Code:

```<code>    var notificationList: [(type: String,imageName: String, text: String, date: String, seen: Bool)] = [(type: "Default",imageName: "ClearPartioned", text: "", date: "", seen: true)]

    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        UserDefaults.standard.set(notificationList, forKey: "notificationList")
        UserDefaults.standard.synchronize()

        print("\(notificationList)")

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }
</code>```

Update:

This is closer but gives error found in this question here. These are the closet answers I have been able to find and there either out dated or crash the system.

Code:

```<code>    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        let encodedData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(encodedData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }
</code>```

Update 2: This is best answer implementation From Dhiru

Code:

```<code>  if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
        print("making notification list")

        let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(notificationData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        let decodedData  = UserDefaults.standard.object(forKey: "notificationList") as! Data
        let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as AnyObject

        print("\(notificationList)")
    }
</code>```

Its giving me an error that crashes system

```<code>   *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1c011f380'
   libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

Im sure this code would fix it but this is horribly implemented with multiple errors below because I have no clue how to use this code.

Code:

```<code>   func (coder aDecoder: NSCoder) {
        if let notificationList = aDecoder.decodeObjectForKey("notificationList") {
            self.notificationList = notificationList
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let notificationList = notificationList {
            aCoder.encodeObject(notificationList, forKey: "notificationList")
        }
    }
</code>```

答:
You have to store your Object  in form of Data
Convert into data using
NSKeyedArchiver.archivedData(withRootObject:)

Convert back to Object using
 NSKeyedUnarchiver.unarchiveObject(with:)

Saving Data for UserDefaults

```<code>let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
UserDefaults.standard.set(notificationData, forKey: "notificationList")
</code>```

Retrive Data from User UserDefaults

```<code>let decodedData  = UserDefaults.standard.object(forKey: "notificationList") as! Data
let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as! AnyObject
</code>```

Body:
This is pretty simple but can't seem to find the correct information to solve saving an array like this in User Defaults.

It says it's not a property that NSUser Defaults Excepts.

Code:

    var notificationList: [(type: String,imageName: String, text: String, date: String, seen: Bool)] = [(type: "Default",imageName: "ClearPartioned", text: "", date: "", seen: true)]

    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        UserDefaults.standard.set(notificationList, forKey: "notificationList")
        UserDefaults.standard.synchronize()

        print("\(notificationList)")

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }

Update:

This is closer but gives error found in this question here. These are the closet answers I have been able to find and there either out dated or crash the system.

Code:

    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        let encodedData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(encodedData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }

Update 2: This is best answer implementation From Dhiru

Code:

  if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
        print("making notification list")

        let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(notificationData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        let decodedData  = UserDefaults.standard.object(forKey: "notificationList") as! Data
        let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as AnyObject

        print("\(notificationList)")
    }

Its giving me an error that crashes system

   *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1c011f380'
   libc++abi.dylib: terminating with uncaught exception of type NSException

Im sure this code would fix it but this is horribly implemented with multiple errors below because I have no clue how to use this code.

Code:

   func (coder aDecoder: NSCoder) {
        if let notificationList = aDecoder.decodeObjectForKey("notificationList") {
            self.notificationList = notificationList
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let notificationList = notificationList {
            aCoder.encodeObject(notificationList, forKey: "notificationList")
        }
    }

Body:
You have to store your Object  in form of Data
Convert into data using
NSKeyedArchiver.archivedData(withRootObject:)

Convert back to Object using
 NSKeyedUnarchiver.unarchiveObject(with:)

Saving Data for UserDefaults

let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
UserDefaults.standard.set(notificationData, forKey: "notificationList")

Retrive Data from User UserDefaults

let decodedData  = UserDefaults.standard.object(forKey: "notificationList") as! Data
let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as! AnyObject


来源: stackexchange

问:
Can't show result as select option Codeigniter 3
My Model name mymodel.php

```<code>.....
function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by($order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        } .....
</code>```

My controller name donate.php

```<code>.....
    function index()
    {
      $data = array(
                        'rekening' => $this->mymodel->all('rekening', 'id_rekening ASC'),
                        );
                    $this->load->view('client/donate/index', $data);
                } .....
</code>```

And this My View in path view/client/donate/index

```<code><?php foreach ($rekening as $rek): ?>
                <option value="<?php echo $rek->id_rekening; ?>" <?php echo set_select('ke_rekening', $rek->id_rekening); ?>><?php echo $rek->bank .' - '. $rek->atas_nama_rekening; ?></option>
              <?php endforeach ?>
</code>```

But why cant show in select option? I use codeigniter 3,
Show image

答:
I think you have to pass value like this in modal.

```<code>function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by("id_rekening",$order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My Model name mymodel.php

.....
function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by($order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        } .....

My controller name donate.php

.....
    function index()
    {
      $data = array(
                        'rekening' => $this->mymodel->all('rekening', 'id_rekening ASC'),
                        );
                    $this->load->view('client/donate/index', $data);
                } .....

And this My View in path view/client/donate/index

<?php foreach ($rekening as $rek): ?>
                <option value="<?php echo $rek->id_rekening; ?>" <?php echo set_select('ke_rekening', $rek->id_rekening); ?>><?php echo $rek->bank .' - '. $rek->atas_nama_rekening; ?></option>
              <?php endforeach ?>

But why cant show in select option? I use codeigniter 3,
Show image

Body:
I think you have to pass value like this in modal.

function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by("id_rekening",$order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        }


问:
How would I use JSP to write directly to a separate HTML page?
I was requested to built this project in JSP and one stipulation is that this project cannot have a database.  I am trying to write a JSP form to allow users to add, remove and edit links on a separate HTML page.  I have very, very limited JSP experience and I was hoping that someone could point me to a decent tutorial.  I would greatly appreciate some direction. I am relatively comfortable with JavaScript, JQuery and the DOM in general.   </p>

答:
If a fullworthy SQL database server is not an option for some reason, then you can always use an embedded SQL database server, like JavaDB, H2 or SQLite. It that is also even not an option, then you can always head to a textbased file in a predefinied format like CSV, XML or even JSON. There are lot of tools available which can convert between Java objects and CSV, XML and JSON. Even more, it's relatively easy to homegrow it. If that is even not an option for some odd reason, then you can as last resort use Java serialization.

At least, HTML is definitely not a suitable format for "data storage".

ContentLicense: CC BY-SA 2.5


问:
in php, what will happen if CURLOPT_CAPATH is not set when CURLOPT_SSL_VERIFYPEER is set to true
The problem is about using curl in PHP.
Some other answers said that curl will reject any ssl connection, however, I can send https requests as normal.
curl.cainfo in php.ini is not set.
Will curl use system default ca bundle when CURLOPT_CAPATH is not set?</p>

答:
Here you can use CURLOPT_CAPATH Like below.

You have to give path of your SSL Certificate in this line curl_setopt($curl_handle, CURLOPT_CAINFO, "/etc/pki/tls/cert.pem");

```<code>$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$link);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_handle, CURLOPT_CAINFO, "/etc/pki/tls/cert.pem");
$buffer = curl_exec($curl_handle);
$buffer_decode = json_decode($buffer);
curl_close($curl_handle);
</code>```

Body:
Here you can use CURLOPT_CAPATH Like below.

You have to give path of your SSL Certificate in this line curl_setopt($curl_handle, CURLOPT_CAINFO, "/etc/pki/tls/cert.pem");

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$link);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_handle, CURLOPT_CAINFO, "/etc/pki/tls/cert.pem");
$buffer = curl_exec($curl_handle);
$buffer_decode = json_decode($buffer);
curl_close($curl_handle);


问:
EHost 'ip' is not allowed to connect to this MySQL serverConnection
I have two Instances: A and B

I am trying to connect Instance A to Instance B's mysql db.

On both instances I have added 3600 to the security group

I have edited Instance B's /etc/mysql/my.cnf and added 0.0.0.0 as the bind-address and restarted mysql

```<code>[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address       = 127.0.0.1
bind-address           = 0.0.0.0
#
# * Fine Tuning
#
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
</code>```

But when I'm on Instance A terminal and try telnet [Instance B public ip] 3306 I get

EHost '[Instance A public ip]' is not allowed to connect to this MySQL
  serverConnection closed by foreign host.

Did I miss a step or did something wrong or something?

答:
You are supposed to grant the permission to IP to avoid seeing this error</p>

```<code>mysql -u root -p
Enter password
: <enter password>

>GRANT ALL ON *.* to root@'xx.xx.xx.xx' IDENTIFIED BY 'root';

>FLUSH PRIVILEGES;
</code>```

Body:
I have two Instances: A and B

I am trying to connect Instance A to Instance B's mysql db.

On both instances I have added 3600 to the security group

I have edited Instance B's /etc/mysql/my.cnf and added 0.0.0.0 as the bind-address and restarted mysql

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address       = 127.0.0.1
bind-address           = 0.0.0.0
#
# * Fine Tuning
#
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8

But when I'm on Instance A terminal and try telnet [Instance B public ip] 3306 I get

EHost '[Instance A public ip]' is not allowed to connect to this MySQL
  serverConnection closed by foreign host.

Did I miss a step or did something wrong or something?

Body:
You are supposed to grant the permission to IP to avoid seeing this error

mysql -u root -p
Enter password
: <enter password>

>GRANT ALL ON *.* to root@'xx.xx.xx.xx' IDENTIFIED BY 'root';

>FLUSH PRIVILEGES;


问:
How to parallelize a bash script containing nested for loops on huge dataset with GNU parallel?
I'm actually launching many connections to IP addresses thanks to OpenSSL in order to detect if a server accept or not a specified cipher. I'm launching this script on 1 000 000 servers (which are contained in "listeIpShuffle.txt"). So, my script contains 2 for loop: the first one is used to get each line of my file containing IP addresses, and the second one to test for each cipher available in my OpenSSL version if the server accept or reject it.

I saw on GNU parallel's doc that it is possible to parallelize these kind of loop:

```<code>  *(for x in `cat xlist` ; do
    for y in `cat ylist` ; do
      do_something $x $y
    done
  done) | process_output*
</code>```

... can be written like this:

```<code>*parallel do_something {1} {2} :::: xlist ylist | process_output*
</code>```

But I'm failing trying to apply this on my script... Indeed my file containing my IP addresses is too big, and I get the famous "Too many arguments" error...
How can I handle this problem and make my script parallel?

Thanks in advance!

Here is my script :

```<code>#!/usr/bin/env bash

#on recupere toutes les ciphers d'openssl
ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g')
fichier="./serveursMail/listeIpShuffle.txt"
port=":25"
>resultDeprecatedCipher.txt
nbInconnu=0
echo Cipher list de $(openssl version).

for ligne in $(<$fichier)
do
    ligneIp=$(echo $ligne | tr "|" "\n")
    ip=($ligneIp)
    ipPort=$ip$port
    dns=$(echo $ligneIp |cut -f 2 -d ' ')

    ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g')

    for cipher in ${ciphers[@]}
    do
        if [[ $nbInconnu < 4 ]] ; then
            echo -n Test $ligneIp " : " $cipher...

            result=$(echo -n | timeout 10s openssl s_client -starttls smtp -cipher "$cipher" -connect $ipPort -servername $dns 2>&1) #pas de reponse apres dasn les 15sec => FAIL

            if [[ "$result" =~ ":error:" ]] ; then
            error=$(echo -n $result | cut -d':' -f6)
            echo NON \($error\)
            let "nbInconnu=0"
            else
                if [[ "$result" =~ "Cipher is ${cipher}" || "$result" =~ "Cipher    :" ]] ; then
                    echo OUI
                    let "nbInconnu=0"
                    echo $ligneIp " : " $cipher >> resultDeprecatedCipher.txt
                else
                    echo REPONSE INCONNUE
                    let "nbInconnu++" #incrementation
                    echo $nbInconnu
                    echo $result
                fi
            fi
        else
          let "nbInconnu=0"
          break
        fi
    done
done
</code>```

答:
```<code>echo alt3.gmail-smtp-in.l.google.com > serverlist
echo fo-ds-ats.member.g02.yahoodns.net >> serverlist

doit() {
    ip="$1"
    port="$2"
    cipher="$3"
    openssl s_client -starttls smtp -cipher "$cipher" -connect $ip:$port -servername $ip < /dev/null
}
export -f doit
parallel --tag --timeout 10 --retries 4 doit $1 :::: serverlist ::: 25 ::: $(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g') >tmp_results
# Post process tmp_results as needed
</code>```

To not overload a single server add --shuf. To run as many as possible in parallel add -j0.

Body:
I'm actually launching many connections to IP addresses thanks to OpenSSL in order to detect if a server accept or not a specified cipher. I'm launching this script on 1 000 000 servers (which are contained in "listeIpShuffle.txt"). So, my script contains 2 for loop: the first one is used to get each line of my file containing IP addresses, and the second one to test for each cipher available in my OpenSSL version if the server accept or reject it.

I saw on GNU parallel's doc that it is possible to parallelize these kind of loop:

  *(for x in `cat xlist` ; do
    for y in `cat ylist` ; do
      do_something $x $y
    done
  done) | process_output*

... can be written like this:

*parallel do_something {1} {2} :::: xlist ylist | process_output*

But I'm failing trying to apply this on my script... Indeed my file containing my IP addresses is too big, and I get the famous "Too many arguments" error...
How can I handle this problem and make my script parallel?

Thanks in advance!

Here is my script :

#!/usr/bin/env bash

#on recupere toutes les ciphers d'openssl
ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g')
fichier="./serveursMail/listeIpShuffle.txt"
port=":25"
>resultDeprecatedCipher.txt
nbInconnu=0
echo Cipher list de $(openssl version).

for ligne in $(<$fichier)
do
    ligneIp=$(echo $ligne | tr "|" "\n")
    ip=($ligneIp)
    ipPort=$ip$port
    dns=$(echo $ligneIp |cut -f 2 -d ' ')

    ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g')

    for cipher in ${ciphers[@]}
    do
        if [[ $nbInconnu < 4 ]] ; then
            echo -n Test $ligneIp " : " $cipher...

            result=$(echo -n | timeout 10s openssl s_client -starttls smtp -cipher "$cipher" -connect $ipPort -servername $dns 2>&1) #pas de reponse apres dasn les 15sec => FAIL

            if [[ "$result" =~ ":error:" ]] ; then
            error=$(echo -n $result | cut -d':' -f6)
            echo NON \($error\)
            let "nbInconnu=0"
            else
                if [[ "$result" =~ "Cipher is ${cipher}" || "$result" =~ "Cipher    :" ]] ; then
                    echo OUI
                    let "nbInconnu=0"
                    echo $ligneIp " : " $cipher >> resultDeprecatedCipher.txt
                else
                    echo REPONSE INCONNUE
                    let "nbInconnu++" #incrementation
                    echo $nbInconnu
                    echo $result
                fi
            fi
        else
          let "nbInconnu=0"
          break
        fi
    done
done

Body:
echo alt3.gmail-smtp-in.l.google.com > serverlist
echo fo-ds-ats.member.g02.yahoodns.net >> serverlist

doit() {
    ip="$1"
    port="$2"
    cipher="$3"
    openssl s_client -starttls smtp -cipher "$cipher" -connect $ip:$port -servername $ip < /dev/null
}
export -f doit
parallel --tag --timeout 10 --retries 4 doit $1 :::: serverlist ::: 25 ::: $(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g') >tmp_results
# Post process tmp_results as needed

To not overload a single server add --shuf. To run as many as possible in parallel add -j0.


问:
Messages not loading on clicking Firebase notification
I have a created a Firebase application using the tutorial given here. As I am a beginner to Android, please help me solving this. My app has a only one activity.

When I send a message from my Firebase console, I am able to see the message and the toast on screen when the app is open. However, if the app is not running, I am able to see the notification from Firebase in Notifications Bar but on clicking it neither the toast comes or the message gets shown on the screen.
Everything works well only for the very first time the app is installed.
How can I solve this problem? Kindly help. Below are my codes:

Activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.unss.pramod.firebasetest.activity.MainActivity">

    <TextView
        android:id="@+id/txt_push_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:textColor="@color/colorPrimary"
        android:textSize="26dp" />

    <TextView
        android:id="@+id/txt_reg_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
</RelativeLayout>
</code>```

Main Activity.java

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

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

        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}
</code>```

Firebase Instance ID service.java

```<code>public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
}
</code>```

Firebase messaging service.java

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}
</code>```

Config.java

```<code>public class Config {

    // global topic to receive app wide push notifications
    public static final String TOPIC_GLOBAL = "global";

    // broadcast receiver intent filters
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String PUSH_NOTIFICATION = "pushNotification";

    // id to handle the notification in the notification tray
    public static final int NOTIFICATION_ID = 100;
    public static final int NOTIFICATION_ID_BIG_IMAGE = 101;

    public static final String SHARED_PREF = "ah_firebase";
}
</code>```

Kindly help in solving this problem.

答:
The onMessageReceived method will be called only when your application is opened/foreground when you send "Notification type message". If want to run onMessageReceived either your application in close then send "Data message". Click here to learn more about data message. Send data notification from server.
JSON sample for data message taken from https://stackoverflow.com/a/38795553/3529309

```<code>{
  "to": "/topics/dev_journal",
   "data": {
       "text":"text",
       "title":"",
       "line1":"Journal",
       "line2":"test"
   }
}
</code>```

Use push.php class from tutorial link you mentioned to send data message.

Body:
I have a created a Firebase application using the tutorial given here. As I am a beginner to Android, please help me solving this. My app has a only one activity.

When I send a message from my Firebase console, I am able to see the message and the toast on screen when the app is open. However, if the app is not running, I am able to see the notification from Firebase in Notifications Bar but on clicking it neither the toast comes or the message gets shown on the screen.
Everything works well only for the very first time the app is installed.
How can I solve this problem? Kindly help. Below are my codes:

Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.unss.pramod.firebasetest.activity.MainActivity">

    <TextView
        android:id="@+id/txt_push_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:textColor="@color/colorPrimary"
        android:textSize="26dp" />

    <TextView
        android:id="@+id/txt_reg_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

Main Activity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

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

        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}

Firebase Instance ID service.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
}

Firebase messaging service.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}

Config.java

public class Config {

    // global topic to receive app wide push notifications
    public static final String TOPIC_GLOBAL = "global";

    // broadcast receiver intent filters
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String PUSH_NOTIFICATION = "pushNotification";

    // id to handle the notification in the notification tray
    public static final int NOTIFICATION_ID = 100;
    public static final int NOTIFICATION_ID_BIG_IMAGE = 101;

    public static final String SHARED_PREF = "ah_firebase";
}

Kindly help in solving this problem.

Body:
The onMessageReceived method will be called only when your application is opened/foreground when you send "Notification type message". If want to run onMessageReceived either your application in close then send "Data message". Click here to learn more about data message. Send data notification from server.
JSON sample for data message taken from https://stackoverflow.com/a/38795553/3529309

{
  "to": "/topics/dev_journal",
   "data": {
       "text":"text",
       "title":"",
       "line1":"Journal",
       "line2":"test"
   }
}

Use push.php class from tutorial link you mentioned to send data message.


问:
csv parser in erlang
for my application i have to parse CSV file using Erlang.following is the code which will parse CSV using Erlang:-

```<code>parse_file(Fn) ->
{ok, Data} = file:read_file(Fn),
parse(binary_to_list(Data)).

parse(Data) -> lists:reverse(parse(Data, [])).

parse([], Acc) -> Acc;
parse(Data, Acc) ->
{Line, Tail} = parse_line(Data),
parse(Tail, [Line|Acc]).

parse_line(Data) ->
{Line, Tail} = parse_line(Data, []),
{lists:reverse(Line), Tail}.

parse_line([13,10|Data], Acc) -> {Acc, Data};
parse_line([10|Data], Acc) -> {Acc, Data};
parse_line([13|Data], Acc) -> {Acc, Data};
parse_line([], Acc) -> {Acc, []};
parse_line([$,,$,|Data], Acc) -> parse_line(Data, [""|Acc]);
parse_line([$,|Data], Acc) -> parse_line(Data, Acc);
parse_line(Data, Acc) ->
{Fld, Tail} = parse_field(Data),
parse_line(Tail, [Fld|Acc]).

parse_field([34|Data]) ->
{Fld, Tail} = parse_fieldq(Data, ""),
{lists:reverse(Fld), Tail};
parse_field(Data) ->
{Fld, Tail} = parse_field(Data, ""),
{lists:reverse(Fld), Tail}.

parse_field([$,|Tail], Acc) -> {Acc, [$,|Tail]};
parse_field([13|Tail], Acc) -> {Acc, [13|Tail]};
parse_field([10|Tail], Acc) -> {Acc, [10|Tail]};
parse_field([], Acc) -> {Acc, []};
parse_field([Ch|Tail], Acc) -> parse_field(Tail, [Ch|Acc]).

parse_fieldq([34,34|Tail], Acc) -> parse_fieldq(Tail, [34|Acc]);
parse_fieldq([34|Tail], Acc) -> {Acc, Tail};
parse_fieldq([Ch|Tail], Acc) -> parse_fieldq(Tail, [Ch|Acc]).
</code>```

this code works fine but having two issues:-
1-since the code parse using double quote ("") and comma(,) and separate each value..but in following example if First name consist of double quote sting within it then the parser will create one more field.

```<code>"Type","First Name","Last Name","Email"
"Contact","Ashwani  Garg ------"All Pain Will End."","","itisashwani4u@gmail.com"

result:-
[["contact"],["Ashwani  Garg ------"],["All Pain Will End."],[],["itisashwani4u@gmail.com"]]

expected result:-
[["contact"],["Ashwani  Garg ------All Pain Will End."],[],["itisashwani4u@gmail.com"]]
</code>```

2-for the following kind of csv its for value,its truncate some value:-
First Name,Last Name,Middle Name,Name,Nickname,E-mail Address,Home Street,Home City,Home Postal Code,Home State,Home Country/Region,Home Phone,Home Fax,Mobile Phone,Personal Web Page,Business Street,Business City,Business Postal Code,Business State,Business Country/Region,Business Web Page,Business Phone,Business Fax,Pager,Company,Job Title,Department,Office Location,Notes

```<code>    Affection,,,Affection,,,,,,,,+919845141544,,+919845141544,,,,,,,,,,,,,,,
    result:-
    [["Affection"],[],[],["Affection"],[],[],[],[],[],[],[],["+919845141544"],[],["+919845141544"],[],[],[],[],[],[],[]]
    expected result:-
   [["Affection"],[],[],["Affection"],[],[],[],[],[],[],[],["+919845141544"],[],["+919845141544"],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
</code>```

Please help me ...for refernce please use the following link:-
  http://ppolv.wordpress.com/2008/02/25/parsing-csv-in-erlang/

答:
Wisher's answer isn't bad, except it loses the last element of every csv line. Here's fix for that. It still does not deal with embedded quotes though.</p>

```<code>-module(csv).

-export([read/1]).

read(File) ->
    try
        {ok, Bin} = file:read_file(File),
        {ok, parse(binary_to_list(Bin), [], [], [])}
    catch
        Class:Error ->
            {Class, Error}
    end.

parse([], _FBuff, _RBuff, Result) ->
    lists:reverse(Result);
parse([$" | Rest], _FBuff, RBuff, Result) ->
    {F, Rest1} = parse_q(Rest, []),
    parse(Rest1, [], [F | RBuff], Result);
parse([$,, $\s| Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [lists:reverse(FBuff) | RBuff], Result);
parse([$, | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [lists:reverse(FBuff) | RBuff], Result);
parse([$\r, $\n | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [], [lists:reverse([lists:reverse(FBuff) | RBuff]) | Result]);
parse([$\n | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [], [lists:reverse([lists:reverse(FBuff) | RBuff]) | Result]);
parse([A | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [A | FBuff], RBuff, Result).

parse_q([$", $, | Rest], Result) ->
    {lists:reverse(Result), Rest};
parse_q([A | Rest], Result) ->
    parse_q(Rest, [A | Result]).
</code>```

Title: csv parser in erlang

Body:
for my application i have to parse CSV file using Erlang.following is the code which will parse CSV using Erlang:-

parse_file(Fn) ->
{ok, Data} = file:read_file(Fn),
parse(binary_to_list(Data)).

parse(Data) -> lists:reverse(parse(Data, [])).

parse([], Acc) -> Acc;
parse(Data, Acc) ->
{Line, Tail} = parse_line(Data),
parse(Tail, [Line|Acc]).

parse_line(Data) ->
{Line, Tail} = parse_line(Data, []),
{lists:reverse(Line), Tail}.

parse_line([13,10|Data], Acc) -> {Acc, Data};
parse_line([10|Data], Acc) -> {Acc, Data};
parse_line([13|Data], Acc) -> {Acc, Data};
parse_line([], Acc) -> {Acc, []};
parse_line([$,,$,|Data], Acc) -> parse_line(Data, [""|Acc]);
parse_line([$,|Data], Acc) -> parse_line(Data, Acc);
parse_line(Data, Acc) ->
{Fld, Tail} = parse_field(Data),
parse_line(Tail, [Fld|Acc]).

parse_field([34|Data]) ->
{Fld, Tail} = parse_fieldq(Data, ""),
{lists:reverse(Fld), Tail};
parse_field(Data) ->
{Fld, Tail} = parse_field(Data, ""),
{lists:reverse(Fld), Tail}.

parse_field([$,|Tail], Acc) -> {Acc, [$,|Tail]};
parse_field([13|Tail], Acc) -> {Acc, [13|Tail]};
parse_field([10|Tail], Acc) -> {Acc, [10|Tail]};
parse_field([], Acc) -> {Acc, []};
parse_field([Ch|Tail], Acc) -> parse_field(Tail, [Ch|Acc]).

parse_fieldq([34,34|Tail], Acc) -> parse_fieldq(Tail, [34|Acc]);
parse_fieldq([34|Tail], Acc) -> {Acc, Tail};
parse_fieldq([Ch|Tail], Acc) -> parse_fieldq(Tail, [Ch|Acc]).

this code works fine but having two issues:-
1-since the code parse using double quote ("") and comma(,) and separate each value..but in following example if First name consist of double quote sting within it then the parser will create one more field.

"Type","First Name","Last Name","Email"
"Contact","Ashwani  Garg ------"All Pain Will End."","","itisashwani4u@gmail.com"

result:-
[["contact"],["Ashwani  Garg ------"],["All Pain Will End."],[],["itisashwani4u@gmail.com"]]

expected result:-
[["contact"],["Ashwani  Garg ------All Pain Will End."],[],["itisashwani4u@gmail.com"]]

2-for the following kind of csv its for value,its truncate some value:-
First Name,Last Name,Middle Name,Name,Nickname,E-mail Address,Home Street,Home City,Home Postal Code,Home State,Home Country/Region,Home Phone,Home Fax,Mobile Phone,Personal Web Page,Business Street,Business City,Business Postal Code,Business State,Business Country/Region,Business Web Page,Business Phone,Business Fax,Pager,Company,Job Title,Department,Office Location,Notes

    Affection,,,Affection,,,,,,,,+919845141544,,+919845141544,,,,,,,,,,,,,,,
    result:-
    [["Affection"],[],[],["Affection"],[],[],[],[],[],[],[],["+919845141544"],[],["+919845141544"],[],[],[],[],[],[],[]]
    expected result:-
   [["Affection"],[],[],["Affection"],[],[],[],[],[],[],[],["+919845141544"],[],["+919845141544"],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

Please help me ...for refernce please use the following link:-
  http://ppolv.wordpress.com/2008/02/25/parsing-csv-in-erlang/

Body:
Wisher's answer isn't bad, except it loses the last element of every csv line. Here's fix for that. It still does not deal with embedded quotes though.

-module(csv).

-export([read/1]).

read(File) ->
    try
        {ok, Bin} = file:read_file(File),
        {ok, parse(binary_to_list(Bin), [], [], [])}
    catch
        Class:Error ->
            {Class, Error}
    end.

parse([], _FBuff, _RBuff, Result) ->
    lists:reverse(Result);
parse([$" | Rest], _FBuff, RBuff, Result) ->
    {F, Rest1} = parse_q(Rest, []),
    parse(Rest1, [], [F | RBuff], Result);
parse([$,, $\s| Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [lists:reverse(FBuff) | RBuff], Result);
parse([$, | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [lists:reverse(FBuff) | RBuff], Result);
parse([$\r, $\n | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [], [lists:reverse([lists:reverse(FBuff) | RBuff]) | Result]);
parse([$\n | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [], [], [lists:reverse([lists:reverse(FBuff) | RBuff]) | Result]);
parse([A | Rest], FBuff, RBuff, Result) ->
    parse(Rest, [A | FBuff], RBuff, Result).

parse_q([$", $, | Rest], Result) ->
    {lists:reverse(Result), Rest};
parse_q([A | Rest], Result) ->
    parse_q(Rest, [A | Result]).


问:
Simon Game how to proceed?
So I am trying to build a Simon Game.
First of all I created a random array with 20 values that varies between 1 and 4 (That would identify each color of the game).
So 1 would be red, 2 would be blue, 3 would be green and 4 would be yellow.
So I got the array which is something like this:

```<code>var arrayRandomColors = [1, 3, 1, 2, 4, 3, 2, 1, 3, 2, 1, 2, 4, 1, 2, 3, 4, 1, 3, 2]
</code>```

Now this is de order of sounds and colors of my Simon Game. However, I now need to go over there array like this:

```<code>Level 1 - [1] -> Level 2 - [1, 3] -> Level 3 - [1, 3, 1] ->  Level 4 - [1, 3, 1, 2]... etc. And then each time it loops over these arrays it plays a sequence o sounds that corresponds to the current level.
</code>```

So that's what I did:

```<code>var j=2;
    var arrayPlay = [];
    for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        console.log(arrayPlay); //[1] -> [1,3] -> [1,3,1]...etc
        arrayPlay = [];
    }
</code>```

So far, I managed to get all the arrays I want. However, I got stuck about how to proceed, because I need to go over this numbers slowly, showing the colors being selected and playing a sound while it loops, and the for loop is just too fast. I thought about doing something like this:

```<code>for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        //console.log(arrayPlay);
        for (var k=0; k<arrayPlay.length; k++){
            var id = setInterval(function(){
                console.log("entrou");
            if (arrayPlay[k] == 1){
                $red.css("background-color", "#ffc1c1");
                $red.delay(500);
                $red.css("background-color", "red");
            }
            else if (arrayPlay[k] == 2){
                $blue.css("background-color", "#a5b0f7");
                $blue.delay(500);
                $blue.css("background-color", "blue");
            }
            else if (arrayPlay[k] == 3){
                $green.css("background-color", "#aff7a5");
                $green.delay(500)
                $green.css("background-color", "green");
            }
            else if (arrayPlay[k] == 4){
                $yellow.css("background-color", "#fffb91");
                $yellow.delay(500);
                $yellow.css("background-color", "yellow");
            }

            }, 500);
        }
        arrayPlay = [];
        console.log("\n");
    }
</code>```

But it doesn't work. Can anyone help me out?

答:
You could use setTimeout(), as described here. That says:

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
  setTimeout(function(){ alert("Hello"); }, 3000);

.(w3Schools references are not the best ones and not good seen here, but it is not a more elaborate thing, so this link should help.)

Title: Simon Game how to proceed?

Body:
So I am trying to build a Simon Game.
First of all I created a random array with 20 values that varies between 1 and 4 (That would identify each color of the game).
So 1 would be red, 2 would be blue, 3 would be green and 4 would be yellow.
So I got the array which is something like this:

var arrayRandomColors = [1, 3, 1, 2, 4, 3, 2, 1, 3, 2, 1, 2, 4, 1, 2, 3, 4, 1, 3, 2]

Now this is de order of sounds and colors of my Simon Game. However, I now need to go over there array like this:

Level 1 - [1] -> Level 2 - [1, 3] -> Level 3 - [1, 3, 1] ->  Level 4 - [1, 3, 1, 2]... etc. And then each time it loops over these arrays it plays a sequence o sounds that corresponds to the current level.

So that's what I did:

var j=2;
    var arrayPlay = [];
    for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        console.log(arrayPlay); //[1] -> [1,3] -> [1,3,1]...etc
        arrayPlay = [];
    }

So far, I managed to get all the arrays I want. However, I got stuck about how to proceed, because I need to go over this numbers slowly, showing the colors being selected and playing a sound while it loops, and the for loop is just too fast. I thought about doing something like this:

for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        //console.log(arrayPlay);
        for (var k=0; k<arrayPlay.length; k++){
            var id = setInterval(function(){
                console.log("entrou");
            if (arrayPlay[k] == 1){
                $red.css("background-color", "#ffc1c1");
                $red.delay(500);
                $red.css("background-color", "red");
            }
            else if (arrayPlay[k] == 2){
                $blue.css("background-color", "#a5b0f7");
                $blue.delay(500);
                $blue.css("background-color", "blue");
            }
            else if (arrayPlay[k] == 3){
                $green.css("background-color", "#aff7a5");
                $green.delay(500)
                $green.css("background-color", "green");
            }
            else if (arrayPlay[k] == 4){
                $yellow.css("background-color", "#fffb91");
                $yellow.delay(500);
                $yellow.css("background-color", "yellow");
            }

            }, 500);
        }
        arrayPlay = [];
        console.log("\n");
    }

But it doesn't work. Can anyone help me out?


问:
component backend menu with variable
How to create backend menu link with variable e.g. userID to own component?

I know that is possible to make xml file in view but how to insert variable there?

Thanks.

答: For your front ent component you will aslo add its backend component. Links in Joomla 1.5 are normally managed in the MySQL table called jos_components. Take a look at the fields in jos components called: link,menuid,parent,admin_menu_link, admin_menu_alt.</p>

Title: component backend menu with variable


问:
C# Task.WaitAll() in .Net and Mono
Why does this code behave different on Windows and Linux (using Mono)?

```<code>static void Main(string[] args)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    Task[] tasks = new Task[1];

    tasks[0] = Task.Run(() =>
    {
        IPHostEntry iphe = Dns.GetHostEntry("8.8.8.8.dnsrbl.org");
    });
    Task.WaitAll(tasks, 2000);
    Console.WriteLine("Done in " + stopwatch.ElapsedMilliseconds + " ms");
}
</code>```

8.8.8.8.dnsrbl.ru is an example of a query that will eventually time out. I believe there is no working DNS server (or its firewall is blocking me).

Anyway, the point is not getting a result from the DNS server, the point is how Task.WaitAll() behaves on Windows and Mono when waiting for a task containing a call to Dns.GetHostEntry().

On Windows the program takes more or less 2 seconds to run when the query is not returning any result within the timeout period (2s). That is, Task.WaitAll with timeout seems to work. Running this program on Linux with Mono takes 2 seconds to get the output, but the program does not terminate until the task exits.  Why is that?

It seems like I get the same execution time regardless if I use Time.WaitAll with timeout or not.

The clue is in Dns.GetHostEntry() because Task.WaitAll() works as expected if I start a task with a Thread.Sleep() simulating a long running task.
This works as expected:

```<code>tasks[0] = Task.Run(() => Thread.Sleep(10000));
</code>```

Is there a way to force Task.WaitAll(Task[] tasks, int millisecondsTimeout) to actually time out when running in Mono?

Edit: Task.WaitAll() does in fact return after the timeout period, but the program doesn't terminate when running in Mono (until Dns.GetHostEntry times out).

And it's not the compiler. I get the same result whether I compile with Visual Studio or the Mono C# compiler.

答:
I’ll answer my own question although credit should go to Evk who guided me on the right track (thanks mate!)

The subject on this question is bad to say the least. The problem has nothing to do with Task.WaitAll but rather the Mono implementation of Dns.GetHostEntry. As Evk said in a comment:

That means (most likely) that Dns.GetHostEntry on linux starts new
  non-background thread. Program cannot complete until all
  non-background threads are finished.

The GetHostEntry() method is located in the source file Dns.cs and when called with a string it calls GetHostByName which then calls GetHostByName_internal which is an external C function located in w32socket.c. Finally mono_get_address_info (in networking-posix.c) is called and we are down in the libc function getaddrinfo. Phew!

I cannot see any new non-background threads being started, but I found this:

```<code>MONO_ENTER_GC_SAFE;
ret = getaddrinfo (hostname, service_name, &hints, &info);
MONO_EXIT_GC_SAFE;
</code>```

MONO_ENTER_GC_SAFE and MONO_EXIT_GC_SAFE are macros defined in mono-threads-api.h

```<code>#define MONO_ENTER_GC_SAFE  \
    do {    \
        gpointer __gc_safe_dummy;   \
        gpointer __gc_safe_cookie = mono_threads_enter_gc_safe_region (&__gc_safe_dummy)

#define MONO_EXIT_GC_SAFE   \
        mono_threads_exit_gc_safe_region (__gc_safe_cookie, &__gc_safe_dummy);  \
    } while (0)
</code>```

I did not dig any further, but I believe Evk is right.

So, the answer to my question: Dns.GetHostEntry() cannot be terminated or cancelled in Mono. A program calling this method will not terminate until all queries has been processed or timed out. That’s the way it is. My guess is that is has to do with the garbage collector (GC) which probably runs in non-background thread and hence cannot be cancelled/terminated.

Edit: (A few days later) The reason for this was obvious once I got down to the man-page for getaddrinfo. This function returns a linked list to the result. This list is of course allocated on the heap, and has to be freed at some point to avoid memory leakage. The function for that is freeaddrinfo.

Anyway, thanks again to Evk!

So how can we fire multiple DNS queries in parallel with a timeout (using Mono)? Easy! This function can be called in a Task and it will be happy to obey WaitAll with timeout:

```<code>private static string host(string query)
{
    ProcessStartInfo psi = new ProcessStartInfo("host", query);
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    Process p = Process.Start(psi);
    return p.StandardOutput.ReadToEnd();
}
</code>```

Title: C# Task.WaitAll() in .Net and Mono

Body:
Why does this code behave different on Windows and Linux (using Mono)?

static void Main(string[] args)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    Task[] tasks = new Task[1];

    tasks[0] = Task.Run(() =>
    {
        IPHostEntry iphe = Dns.GetHostEntry("8.8.8.8.dnsrbl.org");
    });
    Task.WaitAll(tasks, 2000);
    Console.WriteLine("Done in " + stopwatch.ElapsedMilliseconds + " ms");
}

8.8.8.8.dnsrbl.ru is an example of a query that will eventually time out. I believe there is no working DNS server (or its firewall is blocking me).

Anyway, the point is not getting a result from the DNS server, the point is how Task.WaitAll() behaves on Windows and Mono when waiting for a task containing a call to Dns.GetHostEntry().

On Windows the program takes more or less 2 seconds to run when the query is not returning any result within the timeout period (2s). That is, Task.WaitAll with timeout seems to work. Running this program on Linux with Mono takes 2 seconds to get the output, but the program does not terminate until the task exits.  Why is that?

It seems like I get the same execution time regardless if I use Time.WaitAll with timeout or not.

The clue is in Dns.GetHostEntry() because Task.WaitAll() works as expected if I start a task with a Thread.Sleep() simulating a long running task.
This works as expected:

tasks[0] = Task.Run(() => Thread.Sleep(10000));

Is there a way to force Task.WaitAll(Task[] tasks, int millisecondsTimeout) to actually time out when running in Mono?

Edit: Task.WaitAll() does in fact return after the timeout period, but the program doesn't terminate when running in Mono (until Dns.GetHostEntry times out).

And it's not the compiler. I get the same result whether I compile with Visual Studio or the Mono C# compiler.

Body:
I’ll answer my own question although credit should go to Evk who guided me on the right track (thanks mate!)

The subject on this question is bad to say the least. The problem has nothing to do with Task.WaitAll but rather the Mono implementation of Dns.GetHostEntry. As Evk said in a comment:

That means (most likely) that Dns.GetHostEntry on linux starts new
  non-background thread. Program cannot complete until all
  non-background threads are finished.

The GetHostEntry() method is located in the source file Dns.cs and when called with a string it calls GetHostByName which then calls GetHostByName_internal which is an external C function located in w32socket.c. Finally mono_get_address_info (in networking-posix.c) is called and we are down in the libc function getaddrinfo. Phew!

I cannot see any new non-background threads being started, but I found this:

MONO_ENTER_GC_SAFE;
ret = getaddrinfo (hostname, service_name, &hints, &info);
MONO_EXIT_GC_SAFE;

MONO_ENTER_GC_SAFE and MONO_EXIT_GC_SAFE are macros defined in mono-threads-api.h

#define MONO_ENTER_GC_SAFE  \
    do {    \
        gpointer __gc_safe_dummy;   \
        gpointer __gc_safe_cookie = mono_threads_enter_gc_safe_region (&__gc_safe_dummy)

#define MONO_EXIT_GC_SAFE   \
        mono_threads_exit_gc_safe_region (__gc_safe_cookie, &__gc_safe_dummy);  \
    } while (0)

I did not dig any further, but I believe Evk is right.

So, the answer to my question: Dns.GetHostEntry() cannot be terminated or cancelled in Mono. A program calling this method will not terminate until all queries has been processed or timed out. That’s the way it is. My guess is that is has to do with the garbage collector (GC) which probably runs in non-background thread and hence cannot be cancelled/terminated.

Edit: (A few days later) The reason for this was obvious once I got down to the man-page for getaddrinfo. This function returns a linked list to the result. This list is of course allocated on the heap, and has to be freed at some point to avoid memory leakage. The function for that is freeaddrinfo.

Anyway, thanks again to Evk!

So how can we fire multiple DNS queries in parallel with a timeout (using Mono)? Easy! This function can be called in a Task and it will be happy to obey WaitAll with timeout:

private static string host(string query)
{
    ProcessStartInfo psi = new ProcessStartInfo("host", query);
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    Process p = Process.Start(psi);
    return p.StandardOutput.ReadToEnd();
}


问:
Swift 4: How to create an array with the most recent emoji used?
I am trying to figure out how to get the unicode strings of the most recent emoji like in the messages app to display in a UICollectionView. I have figured out how to put regular emoji into a UICollectionView, and would just need a string array with the most recent emoji used. I tried using the answer from Access most recently used emojis list in iOS but it returned nil when running on my phone.</p>

答:
After a bit of tinkering, I managed to solve the problem for iOS 11 in xcode 9 beta:

```<code>if let prefs = UserDefaults(suiteName: "com.apple.EmojiPreferences") {
        if let defaults = prefs.dictionary(forKey: "EMFDefaultsKey"){
            if let recents = defaults["EMFRecentsKey"] as? [String]{
                emojiList.append(recents)
            }
        }
    }
</code>```

However, like Access most recently used emojis list in iOS, "there is no guarantee that the App Store reviewers will allow this usage, nor there is any guarantee that it will work in the past or future versions."

Body:
After a bit of tinkering, I managed to solve the problem for iOS 11 in xcode 9 beta:

if let prefs = UserDefaults(suiteName: "com.apple.EmojiPreferences") {
        if let defaults = prefs.dictionary(forKey: "EMFDefaultsKey"){
            if let recents = defaults["EMFRecentsKey"] as? [String]{
                emojiList.append(recents)
            }
        }
    }

However, like Access most recently used emojis list in iOS, "there is no guarantee that the App Store reviewers will allow this usage, nor there is any guarantee that it will work in the past or future versions."


问:
Goto GridView section after click edit button
I use c# GridView control to show data from database. When I click in edit button page is reload and field is editable, but in my page, GridView is at the bottom of the page. I have few big table and can't place GridView higher.
How I can achive effect, that when I click on edit button, after reload, user will be in gridview section insted top of page?

Thank you in advance for your help.

答:
You set the MaintainScrollPositionOnPostBack property in the @Page directive to true.

The page directive is the first line of your .aspx code. Add the attribute here with the value of "true"

```<code><%@ Page Language="C#" MaintainScrollPositionOnPostback="true"
</code>```

The page will now maintain the scroll position and upon post pack the page will return to that scroll position.

The property can also be set programmatically in the page load event:

```<code>this.MaintainScrollPositionOnPostBack = true;
</code>```

Body:
You set the MaintainScrollPositionOnPostBack property in the @Page directive to true.

The page directive is the first line of your .aspx code. Add the attribute here with the value of "true"

<%@ Page Language="C#" MaintainScrollPositionOnPostback="true"

The page will now maintain the scroll position and upon post pack the page will return to that scroll position.

The property can also be set programmatically in the page load event:

this.MaintainScrollPositionOnPostBack = true;


问:
Public Properties instead of PRIVATE fields
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

```<code>class myClass{

public int AValue{get; set;}
}
</code>```

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

```<code>class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}
</code>```

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)

答: In the way you presented it (writing get and set method) is good, but you have two methods - one for setting the value of the field and one for getting this value. Using properties, it's more natural to me, since you "encapsulate" set and get method under one name and accessing it is better this way (in my opinion).

Body:
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

class myClass{

public int AValue{get; set;}
}

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)


问:
How to have subforms load after the the main form in access 2010
I have an Access 2010 database, with document information in a primary table.

I have forms that display specific document type information (credit card statements, invoices, etc.) from the table.

I have a main form, with separate subforms, each subform representing a specific document type.
I want to be able to filter from the main form, so that each document type subform displays only the documents that fall within a user-specified dollar amount range.

I'm thinking, that if I can get the sub forms to open after the main form (the reverse of this is the default order), I can set the filter in the open event of each sub form, from the main form, and get my desired results.

What I have found to cause the sub forms to open after the main form, is to remove the SourceObject from the Data tab of the Properties sheet of the sub form; and then assign the sub form name to the SourceObject property in vba in the open event of the main form.

The example I have is Me.MySubForm.Form.SourceObject = "frmSubFormName", where everything on the left is verbatim, and frmSubFormName is the name of my subform.

This isn't getting past the compiler - it's complaining about MySubForm, and unfortunately the post/blog with the example doesn't indicate what "MySubForm" is, in assigning the SourceObject property to my sub form name.

Any thoughts on this approach to the filtering?

Can anyone shed light on the syntax of setting the SourceObject; or perhaps provide another way of having the sub forms load after the main form?

Thanks in advance.

答:
Remove the Form class object reference. Recommend naming the subform container control different from the object it holds, such as ctrSomething

Me.ctrSomething.SourceObject = "frmSubFormName"


答:
You can use MaintainScrollPositionOnPostBack on your Page_Load method:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    this.MaintainScrollPositionOnPostBack = true;
    .....
}
</code>```

MaintainScrollPositionOnPostBack Gets or sets a value indicating whether to return the user to the same position in the client browser after postback.

Title: Goto GridView section after click edit button

Body:
I use c# GridView control to show data from database. When I click in edit button page is reload and field is editable, but in my page, GridView is at the bottom of the page. I have few big table and can't place GridView higher.
How I can achive effect, that when I click on edit button, after reload, user will be in gridview section insted top of page?

Thank you in advance for your help.

Body:
You can use MaintainScrollPositionOnPostBack on your Page_Load method:

protected void Page_Load(object sender, EventArgs e)
{
    this.MaintainScrollPositionOnPostBack = true;
    .....
}

MaintainScrollPositionOnPostBack Gets or sets a value indicating whether to return the user to the same position in the client browser after postback.


问:
Repeatedly show dynamic dropdowns
I want to repeatedly show drop downs in a table in order to take its value and update specific records.

I have able to make dynamic dropdown using this

```<code>function getEmployeeTaskStatusMain(){
   var go_path = "Employee_Switch_Person.php?action=getEmployeeTaskStatusMain&vars=0";
    $jq.get(go_path,
        {
        }, function(data)
        {
            if(JSON.parse(data).length == 0){
                console.log(data);
                return data;
            }
            else {
                var dataToAppend;
                dataToAppend = "<select name='EmployeeTaskStatus' class='EmployeeTaskStatus form-control'>"
                dataToAppend += "<option value='0'>Select Status</option>";

                //console.log(" " + data);
                dataParse = JSON.parse(data);

                for (var i = 0; i < dataParse.length; i++)
                {
                    //console.log(dataParse[i]);
                    dataToAppend += "<option value=" + dataParse[i].TaskStatusMainId + ">" + dataParse[i].TaskStatusMain + "</option>";

                }

                dataToAppend +="</select>";
                $jq(".taskStatusMain").html(dataToAppend);
                //getEmployeeTaskStatusDetail(0);
                return dataParse;
            }
        });
}
</code>```

But do i need to repeat the above function for every table row in order to show the dropdown in each row with dynamic id(so that i can get it selected value)?

The table (is also making dynamically) where i have to show dropdown with each record and i want to take each dropdown selected value in order to update specfic record. what is the handy way?

Remember, There are two drop downs one dropwdown value updating on another dropdown value selection.

答:
Why don't you return this data in the users array and render it in the HTML file inside the for loop for each user and loop through his status to render the drop down?
And then update that row using the on change event for the select tag</p>

```<code><tr>
   <th>status></th>
</tr>
foreach($users as $user){
  <tr>
   <td>
     <select>
       foreach($user->status as $status-item){
         <option>$status-item->name</option>
       }
     </select>
   </td>
  </tr>
}
</code>```

Title: Repeatedly show dynamic dropdowns

Body:
I want to repeatedly show drop downs in a table in order to take its value and update specific records.

I have able to make dynamic dropdown using this

function getEmployeeTaskStatusMain(){
   var go_path = "Employee_Switch_Person.php?action=getEmployeeTaskStatusMain&vars=0";
    $jq.get(go_path,
        {
        }, function(data)
        {
            if(JSON.parse(data).length == 0){
                console.log(data);
                return data;
            }
            else {
                var dataToAppend;
                dataToAppend = "<select name='EmployeeTaskStatus' class='EmployeeTaskStatus form-control'>"
                dataToAppend += "<option value='0'>Select Status</option>";

                //console.log(" " + data);
                dataParse = JSON.parse(data);

                for (var i = 0; i < dataParse.length; i++)
                {
                    //console.log(dataParse[i]);
                    dataToAppend += "<option value=" + dataParse[i].TaskStatusMainId + ">" + dataParse[i].TaskStatusMain + "</option>";

                }

                dataToAppend +="</select>";
                $jq(".taskStatusMain").html(dataToAppend);
                //getEmployeeTaskStatusDetail(0);
                return dataParse;
            }
        });
}

But do i need to repeat the above function for every table row in order to show the dropdown in each row with dynamic id(so that i can get it selected value)?

The table (is also making dynamically) where i have to show dropdown with each record and i want to take each dropdown selected value in order to update specfic record. what is the handy way?

Remember, There are two drop downs one dropwdown value updating on another dropdown value selection.

Body:
Why don't you return this data in the users array and render it in the HTML file inside the for loop for each user and loop through his status to render the drop down?
And then update that row using the on change event for the select tag

<tr>
   <th>status></th>
</tr>
foreach($users as $user){
  <tr>
   <td>
     <select>
       foreach($user->status as $status-item){
         <option>$status-item->name</option>
       }
     </select>
   </td>
  </tr>
}


问:
style a textbox into the following format?
I have a field called WATER METER READING(Right now its a textbox to take 6 numbers) on my HTml page, but I need to change its format to display as  [][][][][][] (6 separate small (single digit forms)).... all 6 fields required and all need to be a number.

finally it should look like this.

Water Meter Reading:* [][][][][][]

Any suggestions how to display the values like this.

答: If I understand your question correctly it seems to me you want 6 separate fields, WATER_METER_READING_1 through WATER_METER_READING_6 and you can combine them into one field WATER_METER_READING when the form is submitted to the server. Consequently to load the data into the 6 fields if you need to edit the form you can just split the field WATER_METER_READING on the server side into the appropriate field. </p>


问:
How to save Outlook mails as .msg file with categories and other details?
It is easy to save emails in Outlook VBA with MailItem.SaveAs

But I don't see any option to save additional details like i.e. the Author and Categories.

The 3rd party program MessageSave allows to save mails with Categories and Author in .msg format. In Windows Explorer the columns Author and Categories show the same information like in Outlook.

Does anybody know how to save messages using Outlook VBA including these additional information?

I bought MessageSave and it's a good program but they don't allow their save function to be used in VBA. The only workaround is to let MessageSave save messages when they "arrive" in a specific folder. If necessary I can use this function but this is just a workaround.

Here is a sample how the emails saved with MessageSave are shown in Windows Explorer:

答:
here is a process i followed:   (win7 64)

web search "windows vba set extended file property"

first hit: StackOverfow 16989882

web search: "DSOFile.OleDocumentProperties"

hit microsoft: The Dsofile.dll files lets you edit Office document properties when you do not have Office installed

https://support.microsoft.com/en-us/help/224351/the-dsofile.dll-files-lets-you-edit-office-document-properties-when-yo

that is not a typo ... it ends in "when-yo"

download: DsoFileSetup_KB224351_x86.exe

open DsoFileSetup_KB224351_x86.exe using 7-zip program  (from 7-zip.org)

copy dsofile.dll from DsoFileSetup_KB224351_x86.exe (using 7-zip) into a folder  desktop (named "testFiles" in this example) (this could be anywhere ... maybe windows system32 or syswow64 ... i only tried on desktop )

open command prompt window as administrator

navigate to folder that contains dsofile.dll

execute following:  regsvr32 dsofile.dll

should receive success confirmation

start outlook ... vba editor ... tools ... references

and find "DSO OLE Document Properties Reader 2.1" and check the box on left

back to vba editor ... create new module

paste in the following:   (this is just a minimal test script)

```<code>Sub extendedProperties()

    Dim objFile As OleDocumentProperties
    Set objFile = CreateObject("DSOFile.OleDocumentProperties")

    objFile.Open ("C:\Users\js\Desktop\testFiles\myMessage.msg")  ' adjust to match your system
    objFile.SummaryProperties.Subject = "My Subject"
    objFile.Save

    Set objFile = Nothing
End Sub
</code>```

copy (drag&drop) an email "myMessage" from outlook to folder (on desktop in this example)

right-click on folder column header ... click on more ... find "subject" ...
click checkbox

ran script

subject column should contain "My Subject" next to myMessage.msg (or whatever your message is named)

there may be a simpler way ... maybe windows PowerShell has a command that could be called from vba

Body:
here is a process i followed:   (win7 64)

web search "windows vba set extended file property"

first hit: StackOverfow 16989882

web search: "DSOFile.OleDocumentProperties"

hit microsoft: The Dsofile.dll files lets you edit Office document properties when you do not have Office installed

https://support.microsoft.com/en-us/help/224351/the-dsofile.dll-files-lets-you-edit-office-document-properties-when-yo

that is not a typo ... it ends in "when-yo"

download: DsoFileSetup_KB224351_x86.exe

open DsoFileSetup_KB224351_x86.exe using 7-zip program  (from 7-zip.org)

copy dsofile.dll from DsoFileSetup_KB224351_x86.exe (using 7-zip) into a folder  desktop (named "testFiles" in this example) (this could be anywhere ... maybe windows system32 or syswow64 ... i only tried on desktop )

open command prompt window as administrator

navigate to folder that contains dsofile.dll

execute following:  regsvr32 dsofile.dll

should receive success confirmation

start outlook ... vba editor ... tools ... references

and find "DSO OLE Document Properties Reader 2.1" and check the box on left

back to vba editor ... create new module

paste in the following:   (this is just a minimal test script)

Sub extendedProperties()

    Dim objFile As OleDocumentProperties
    Set objFile = CreateObject("DSOFile.OleDocumentProperties")

    objFile.Open ("C:\Users\js\Desktop\testFiles\myMessage.msg")  ' adjust to match your system
    objFile.SummaryProperties.Subject = "My Subject"
    objFile.Save

    Set objFile = Nothing
End Sub

copy (drag&drop) an email "myMessage" from outlook to folder (on desktop in this example)

right-click on folder column header ... click on more ... find "subject" ...
click checkbox

ran script

subject column should contain "My Subject" next to myMessage.msg (or whatever your message is named)

there may be a simpler way ... maybe windows PowerShell has a command that could be called from vba


答:
You can group by City and Time stamp and sum the Sales

```<code>data.groupBy("City", "TimeStamp").agg(sum(col("Sale")).as("TotalSale")).show
</code>```

Hope this helps!

Title: Spark dataset related

Body:
My data set is looking like this by  following code

+------+---------------+----+
|  City|      Timestamp|Sale|
+------+---------------+----+
|City 3|6/30/2017 16:04|  28|
|City 4| 7/4/2017 16:04|  12|
|City 2|7/13/2017 16:04|   8|
|City 4|7/16/2017 16:04|  21|
|City 4| 7/3/2017 16:04|  24|
|City 2|7/17/2017 16:04|  34|
|City 3| 7/9/2017 16:04|  13|
|City 3|7/18/2017 16:04|  26|
|City 3| 7/6/2017 16:04|  16|
|City 3|7/15/2017 16:04|  29|
|City 4|7/18/2017 16:04|  39|
|City 2| 7/1/2017 16:04|  19|
|City 2|7/18/2017 16:04|  19|
|City 4| 7/4/2017 16:04|  24|
|City 2| 7/4/2017 16:04|   9|
|City 4|7/15/2017 16:04|  20|
|City 3|7/12/2017 16:04|  19|
|City 1| 7/9/2017 16:04|  13|
|City 1|7/13/2017 16:04|  25|
|City 4|7/10/2017 16:04|  10|
+------+---------------+----+

We need to calculate the sum of Sale of each City in week base.

Body:
You can group by City and Time stamp and sum the Sales

data.groupBy("City", "TimeStamp").agg(sum(col("Sale")).as("TotalSale")).show

Hope this helps!


问:
How to build electron app using angular 2
I am pretty new to angular2, TS and electron and want to start making a native app using electron and angular2, however, still, I have not 100% achieve that.
following is what I have done after installing angular, TS:

clone angular quickstart seed from their official website and removed unwanted files

install electron and its typing for my project

create a separate folder under src for electron and defined main.ts for electron (which is responsible for creating electron app window and managing electron app lifecycle, this main is separate from angular's main.ts in root folder)

in system.config.js I have made an entry inside map property for electron to be able to import it(I am not sure if this step is required since electron is not a library and it is a framework, so I suppose electron should be always available and I need to import electron's component from it)

in package.json's start script I have added a script to lead the app in electron shel "start": "tsc && concurrently \"npm run build:watch\" \"npm run serve\" \"electron src/electron/main.js\"",

but I do not know how to access electron's API inside angular's component, any help will be appreciated

UPDATE

I have included package.json file for information such as entry point versions , script and etc

```<code>{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "tsc && concurrently \"npm run build:watch\" \"npm run serve\" \"electron src/electron/main.js\"",
"electron": "electron",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@angular/common": "~4.0.0",
"@angular/compiler": "~4.0.0",
"@angular/core": "~4.0.0",
"@angular/forms": "~4.0.0",
"@angular/http": "~4.0.0",
"@angular/platform-browser": "~4.0.0",
"@angular/platform-browser-dynamic": "~4.0.0",
"@angular/router": "~4.0.0",
"@types/electron": "^1.4.35",
"angular-in-memory-web-api": "~0.3.0",
"core-js": "^2.4.1",
"electron": "^1.6.2",
"rxjs": "5.0.1",
"systemjs": "0.19.40",
"zone.js": "^0.8.4"
 },
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.1.0",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.14",
"rimraf": "^2.5.4",
"@types/node": "^6.0.46",
"@types/jasmine": "2.5.36"
 },
"repository": {}
 }
</code>```

答:
not easy to point where is wrong, need to see all your files and structure

but check Angular4Election  this is angular quickstart with election

Body:
I am pretty new to angular2, TS and electron and want to start making a native app using electron and angular2, however, still, I have not 100% achieve that.
following is what I have done after installing angular, TS:

clone angular quickstart seed from their official website and removed unwanted files

install electron and its typing for my project

create a separate folder under src for electron and defined main.ts for electron (which is responsible for creating electron app window and managing electron app lifecycle, this main is separate from angular's main.ts in root folder)

in system.config.js I have made an entry inside map property for electron to be able to import it(I am not sure if this step is required since electron is not a library and it is a framework, so I suppose electron should be always available and I need to import electron's component from it)

in package.json's start script I have added a script to lead the app in electron shel "start": "tsc && concurrently \"npm run build:watch\" \"npm run serve\" \"electron src/electron/main.js\"",

but I do not know how to access electron's API inside angular's component, any help will be appreciated

UPDATE

I have included package.json file for information such as entry point versions , script and etc

{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "tsc && concurrently \"npm run build:watch\" \"npm run serve\" \"electron src/electron/main.js\"",
"electron": "electron",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@angular/common": "~4.0.0",
"@angular/compiler": "~4.0.0",
"@angular/core": "~4.0.0",
"@angular/forms": "~4.0.0",
"@angular/http": "~4.0.0",
"@angular/platform-browser": "~4.0.0",
"@angular/platform-browser-dynamic": "~4.0.0",
"@angular/router": "~4.0.0",
"@types/electron": "^1.4.35",
"angular-in-memory-web-api": "~0.3.0",
"core-js": "^2.4.1",
"electron": "^1.6.2",
"rxjs": "5.0.1",
"systemjs": "0.19.40",
"zone.js": "^0.8.4"
 },
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.1.0",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.14",
"rimraf": "^2.5.4",
"@types/node": "^6.0.46",
"@types/jasmine": "2.5.36"
 },
"repository": {}
 }