问:
jquery AJAX Post not working Codeigniter
I am currently learning jquery AJAX, i am trying to change my standar php post to AJAX but not working, it's still prosses with php, not AJAX. Not even in the console show anything. Can anyone check my code ?
I am using Codeigniter. And you can asume the php part is working fine ..

HTML :

```<code><form action="<?=base_url()?>operator_pt/unggah/unggah_semua" id="unggahsemua" method="POST" name="unggahsemua" role="form">

  <?php  foreach($data as $rod)
  $tahun = $rod->id_smt;
  $jurusan = $rod->id_sms;
    ?>
    <div id="form-tahun" class="form-group">
     <input type="hidden" class="form-control" id="tahun" name="tahun" value="<?php echo $tahun;?>">
     </div>
     <div id="form-jurusan" class="form-group">
     <input type="hidden" class="form-control" id="jurusan" name="jurusan" value="<?php echo $jurusan;?>">
        </div>
         Sedang Mengunggah :

        <div id="statmhs"> </div>
        <div id="statidmhs"> </div>
        <div id="statdsnpt"> </div>

<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
</code>```

JS :

```<code>$(document).ready(function() {

    $('#unggahsemua').submit(function(event) {

        $('.form-group').removeClass('has-error');
        $('.help-block').remove();

        var formData = {
             'tahun'              : $('input[name=tahun]').val(),
            'jurusan'             : $('input[name=jurusan]').val(),
        };

        // process the form
        $.ajax({
            type        : 'POST',
            url         : '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
            data        : formData,
            dataType    : 'json',
            encode      : true
        })

            .done(function(data) {

                console.log(data);

                $('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
                $('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
                $('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');

            .fail(function(data) {

                console.log(data);
            });

        event.preventDefault();
    });

});
</code>```

答:
if you use form action="" method="POST" name="" role="form", make sure in config.php change $config['csrf_protection'] = TRUE; to FALSE.
But, if you want to set it TRUE you must use form_open()

Body:
I am currently learning jquery AJAX, i am trying to change my standar php post to AJAX but not working, it's still prosses with php, not AJAX. Not even in the console show anything. Can anyone check my code ?
I am using Codeigniter. And you can asume the php part is working fine ..

HTML :

<form action="<?=base_url()?>operator_pt/unggah/unggah_semua" id="unggahsemua" method="POST" name="unggahsemua" role="form">

  <?php  foreach($data as $rod)
  $tahun = $rod->id_smt;
  $jurusan = $rod->id_sms;
    ?>

     <input type="hidden" class="form-control" id="tahun" name="tahun" value="<?php echo $tahun;?>">

     <input type="hidden" class="form-control" id="jurusan" name="jurusan" value="<?php echo $jurusan;?>">

         Sedang Mengunggah :

JS :

$(document).ready(function() {

    $('#unggahsemua').submit(function(event) {

        $('.form-group').removeClass('has-error');
        $('.help-block').remove();

        var formData = {
             'tahun'              : $('input[name=tahun]').val(),
            'jurusan'             : $('input[name=jurusan]').val(),
        };

        // process the form
        $.ajax({
            type        : 'POST',
            url         : '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
            data        : formData,
            dataType    : 'json',
            encode      : true
        })

            .done(function(data) {

                console.log(data);

                $('#statmhs').append('
' + data.infounggahmhs + '
');
                $('#statidmhs').append('
' + data.infounggahidmhs + '
');
                $('#statdsnpt').append('
' + data.infounggahdsnpt + '
');

            .fail(function(data) {

                console.log(data);
            });

        event.preventDefault();
    });

});


来源: stackexchange

问:
Login to remote site with PHP cURL
I'm new to using cURL and its hard to find good resources for it.
What I'm trying to do is login to a remote site, by having curl do the login form and then send back that it was successful.

The code I have doesn't seem to work and only tries to show the main page of the site.

```<code>    $username="mylogin@gmail.com";
$password="mypassword";
$url="http://www.myremotesite.com/index.php?page=login";
$cookie="cookie.txt";

$postdata = "email=".$username."&password=".$password;

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url);

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);

echo $result;
curl_close($ch);
</code>```

What am I doing wrong. After this is working I want to redirect to another page and get content from my site.

答:
Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :

```<br/>// options<br/>$login_email = 'alabala@gmail.com';<br/>$login_pass = 'alabala4807';<br/>$cookie_file_path = "/tmp/cookies.txt";<br/>$LOGINURL = "http://alabala.com/index.php?route=account/login"; <br/>$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";<br/><br/>// begin script<br/>$ch = curl_init();<br/><br/>// extra headers<br/>$headers[] = "Accept: */*";<br/>$headers[] = "Connection: Keep-Alive";<br/><br/>// basic curl options for all requests<br/>curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers);<br/>curl_setopt($ch, CURLOPT_HEADER,  0);<br/>curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);<br/>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  <br/>       curl_setopt($ch, CURLOPT_USERAGENT, $agent); <br/>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); <br/>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); <br/>curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); <br/>curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); <br/><br/>// set first URL<br/>curl_setopt($ch, CURLOPT_URL, $LOGINURL);<br/><br/>// execute session to get cookies and required form inputs<br/>$content = curl_exec($ch); <br/><br/>// grab the hidden inputs from the form required to login<br/>$fields = getFormFields($content);<br/>$fields['email'] = $login_email;<br/>$fields['password'] = $login_pass;<br/><br/>// set postfields using what we extracted from the form<br/>$POSTFIELDS = http_build_query($fields); <br/>// change URL to login URL<br/>curl_setopt($ch, CURLOPT_URL, $LOGINURL); <br/><br/>// set post options<br/>curl_setopt($ch, CURLOPT_POST, 1); <br/>curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS); <br/><br/>// perform login<br/>$result = curl_exec($ch);  <br/><br/>print $result; <br/><br/>function getFormFields($data)<br/>{<br/>    if (preg_match('/()/is', $data, $matches)) {<br/>      $inputs = getInputs($matches[1]);<br/><br/>      return $inputs;<br/>    } else {<br/>      die('didnt find login form');<br/>     }<br/>}<br/><br/>function getInputs($form)<br/>{<br/>    $inputs = array();<br/>    $elements = preg_match_all("/(]+>)/is", $form, $matches);<br/>    if ($elements > 0) {<br/>        for($i = 0;$i            $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);<br/>            if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {<br/>                $name  = $name[1];<br/><br/>                $value = '';<br/>                if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {<br/>                    $value = $value[1];<br/>                }<br/><br/>                $inputs[$name] = $value;<br/>            }<br/>        }<br/>    }<br/><br/>    return $inputs;<br/>}<br/><br/>$grab_url='http://grab.url/alabala';<br/><br/>//page with the content I want to grab<br/>curl_setopt($ch, CURLOPT_URL, $grab_url);<br/>//do stuff with the info with DomDocument() etc<br/>$html = curl_exec($ch);<br/>curl_close($ch);<br/><br/>var_dump($html); <br/>die;```

ContentLicense: CC BY-SA 2.5

Title: Login to remote site with PHP cURL

Body:
I'm new to using cURL and its hard to find good resources for it.
What I'm trying to do is login to a remote site, by having curl do the login form and then send back that it was successful.

The code I have doesn't seem to work and only tries to show the main page of the site.

    $username="mylogin@gmail.com";
$password="mypassword";
$url="http://www.myremotesite.com/index.php?page=login";
$cookie="cookie.txt";

$postdata = "email=".$username."&password=".$password;

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url);

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);

echo $result;
curl_close($ch);

What am I doing wrong. After this is working I want to redirect to another page and get content from my site.

Body:
Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :

// options
$login_email = 'alabala@gmail.com';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "http://alabala.com/index.php?route=account/login";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers);
curl_setopt($ch, CURLOPT_HEADER,  0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

// perform login
$result = curl_exec($ch);

print $result;

function getFormFields($data)
{
    if (preg_match('/()/is', $data, $matches)) {
      $inputs = getInputs($matches[1]);

      return $inputs;
    } else {
      die('didnt find login form');
     }
}

function getInputs($form)
{
    $inputs = array();
    $elements = preg_match_all("/(]+>)/is", $form, $matches);
    if ($elements > 0) {
        for($i = 0;$i            $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
            if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
                $name  = $name[1];

                $value = '';
                if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
                    $value = $value[1];
                }

                $inputs[$name] = $value;
            }
        }
    }

    return $inputs;
}

$grab_url='http://grab.url/alabala';

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

var_dump($html);
die;

ContentLicense: CC BY-SA 4.0


问:
Insert (INSERT INTO) a table into another table containing a sequence (SERIAL)
I have a main table created as:

```<code>    CREATE TABLE main_data
    (
      id SERIAL NOT NULL,
      name character varying(249),
      telephone character varying(248)
    )
</code>```

While I get a new table backup_date containing only name and telephone which I restore and add to my database.

Now I want to add the backup_date to the main_data so that when the backup_date table is added to the main_table it automatically continues the sequence of id. How can I do that?

NOTE After a lot of searching I can only got this solution;

INSERT INTO users (name, age, id) VALUES ('Mozart', 20, DEFAULT);

as I have huge amount of data in the backup_date I cannot use it.

答:
If I get you right, all you need is:</p>

```<code>insert into main_data (name,telephone) select name,telephone from backup_date
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a main table created as:

    CREATE TABLE main_data
    (
      id SERIAL NOT NULL,
      name character varying(249),
      telephone character varying(248)
    )

While I get a new table backup_date containing only name and telephone which I restore and add to my database.

Now I want to add the backup_date to the main_data so that when the backup_date table is added to the main_table it automatically continues the sequence of id. How can I do that?

NOTE After a lot of searching I can only got this solution;

INSERT INTO users (name, age, id) VALUES ('Mozart', 20, DEFAULT);

as I have huge amount of data in the backup_date I cannot use it.

Body:
If I get you right, all you need is:

insert into main_data (name,telephone) select name,telephone from backup_date


问:
linux clone() returning -1 as child_pid
I have the following program:

```<code>#define _GNU_SOURCE
#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

static char child_stack[2048];

static int child_fn() {
    printf("Pid: %ld\n", (long) getpid());
    return 0;
}

int main() {
    pid_t child_pid = clone(child_fn, child_stack+1024, CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);
    printf("clone()= %ld\n", (long) child_pid);

    waitpid(child_pid, NULL, 0);
    return 0;
}
</code>```

I get the following output

```<code># ./clone
clone()= -1
</code>```

Can anyone help me understand why is it so?

Note: I'm running this under a docker image with ubuntu:latest. Also notice that the prompt is # instead of $, so does it have anything to do with the user who's running this process, probably root in this case?

答:
As mentioned in the comments I used strerror(3) to find why I was getting the error. The error was Operation not permitted. I searched a bit about it and found the solution here - clone: operation not permitted

So to fix it, all I had to do was to run my docker container with --privileged flag

Title: linux clone() returning -1 as child_pid

Body:
I have the following program:

#define _GNU_SOURCE
#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

static char child_stack[2048];

static int child_fn() {
    printf("Pid: %ld\n", (long) getpid());
    return 0;
}

int main() {
    pid_t child_pid = clone(child_fn, child_stack+1024, CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);
    printf("clone()= %ld\n", (long) child_pid);

    waitpid(child_pid, NULL, 0);
    return 0;
}

I get the following output

# ./clone
clone()= -1

Can anyone help me understand why is it so?

Note: I'm running this under a docker image with ubuntu:latest. Also notice that the prompt is # instead of $, so does it have anything to do with the user who's running this process, probably root in this case?


问:
Have you ever seen as i have checked session behaviour in gmail.com ? Please help?
Yesterday morning i open gmail account in Internet Exlorer second tab. I checked my mail and closed that tab (not browser).

Then at the time of evining i again open second tab of browser and enetr gmail.com, it automatically redirect me at my email account without asking login.

I shocked and i thought i should remain browser open for whole night and today open gmail in second tab , it behave similar means without login screen it redirect in my gmail account.

Then i closed that tab and open another browser session and enter gmail i again surprised that i redirect me login page. At the same time i open second tab of first browser and it automatically redirect me at mail account page.

What i councluded by this behaviour is that might be gmail server keep my browser id at their server so that whenever i eneter gmail.com on second tab of first browser, it automatically redirect me at gmail account. I don't know i am right or not?

Please clear me this concept? What happens with my session at gmail server when i closed my browser tab?

As per my opinion it should automatically logout me but why this doesn't happened?

答: You probably ticked the option "stay signed in" the last time you logged in. Go back to gmail, click log out, and log in again, making sure that option is not ticked. Close the tab, come back in an hour, and open gmail again. You should be at the login screen this time.</p>


问:
What's the most readable way to write nested functions in javascript?
Example this code I wrote doesn't seem as readable as it could be:</p>

```<code>function getShortMessages(messages) {
    return messages.filter((messages) => {
        return messages.message.length < 50
    }).map((object) => {
        return object.message
    })
}
</code>```

答:
Seems okay to me to be honest. What you could do is replace the "50" with a variable in your js file.

```<code>var MESSAGE_MAX_LENGTH= 50;
</code>```

And re position a bit the way you address the function

```<code>function getShortMessages(messages) {
    return messages
        .filter( (messageObject) => {
            return messageObject.message.length < MESSAGE_MAX_LENGTH
        })
        .map( (messageObject) => {
            return messageObject.message
        });
}
</code>```

Also I find that when addressing an array of messages and running through the filter function, it is better to not call the object messages but item or messageObject

moreover, object in the map function is a bit ominous, call it messageObject again for example so you know what you are using specifically

Body:
Example this code I wrote doesn't seem as readable as it could be:

function getShortMessages(messages) {
    return messages.filter((messages) => {
        return messages.message.length < 50
    }).map((object) => {
        return object.message
    })
}

Body:
Seems okay to me to be honest. What you could do is replace the "50" with a variable in your js file.

var MESSAGE_MAX_LENGTH= 50;

And re position a bit the way you address the function

function getShortMessages(messages) {
    return messages
        .filter( (messageObject) => {
            return messageObject.message.length < MESSAGE_MAX_LENGTH
        })
        .map( (messageObject) => {
            return messageObject.message
        });
}

Also I find that when addressing an array of messages and running through the filter function, it is better to not call the object messages but item or messageObject

moreover, object in the map function is a bit ominous, call it messageObject again for example so you know what you are using specifically


问:
echo with ajax does't work
I was following an tutorial, and i finish with this code:

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
    $(function($){
      $("#compila").click(function(){
          var code = $(#codigo).html();

          $.post("myajax.php",{code:code},function(return){
            $(#result).html("<b>print </b>"+return);
          });
      });
    });

</script>

<?php
      $code = $_POST["code"];
      echo $code;

 ?>
</code>```

but this code doesn't work. I was using a text area, and i'm trying to send a string of the text area to a
 tag, and print with echo of the php. How i can fix this code?

答: Apart from missing the quotes in you selectors you shouldn't use the reserved word return for a variable.

Title: echo with ajax does't work

Body:
I was following an tutorial, and i finish with this code:

<?php
      $code = $_POST["code"];
      echo $code;

 ?>

but this code doesn't work. I was using a text area, and i'm trying to send a string of the text area to a
 tag, and print with echo of the php. How i can fix this code?


问:
onBackPressed() and Fragments
I am trying to use onBackPressed() in my Fragment so that I can allow the user to roll back in a pile of fragments he navigated in my app.

The problem is that, when I add the method below to my Fragment, it gives me the error: Method does not override method from its superclass.

```<code>@Override
public void onBackPressed() {

    android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack();

}
</code>```

Would you know why?

Thanks!

Here goes the entire Fragment:

```<code>package it.bitrack.fabio.bitrack;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import android.view.KeyEvent;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AssetMngtView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AssetMngtView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AssetMngtView extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    View view;

    ListView assetMngtListView;
    ArrayAdapter<String> listAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public AssetMngtView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AssetMngtView.
     */
    // TODO: Rename and change types and number of parameters
    public static AssetMngtView newInstance(String param1, String param2) {
        AssetMngtView fragment = new AssetMngtView();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onBackPressed() {

        android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStack();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_asset_mngt_view, container, false);

        assetMngtListView = (ListView) view.findViewById(R.id.assetMngtListView);
        setListView();

        return view;
    }

    public void setListView() {

        String[] options = new String[]{"Bind tag & thing", "Create new thing", "Edit existent thing", "Maintain existent thing", "View things notifications"};

        ArrayList<String> optionsList = new ArrayList<String>();
        optionsList.addAll(Arrays.asList(options));

        listAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, optionsList);

        assetMngtListView.setAdapter(listAdapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
</code>```

答: I am sorry if I missunderstood or if I am missing something, but you get the error because onBackPressed() is not a method of the super class (Fragment class in your case) </p>

Title: onBackPressed() and Fragments

Body:
I am trying to use onBackPressed() in my Fragment so that I can allow the user to roll back in a pile of fragments he navigated in my app.

The problem is that, when I add the method below to my Fragment, it gives me the error: Method does not override method from its superclass.

@Override
public void onBackPressed() {

    android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack();

}

Would you know why?

Thanks!

Here goes the entire Fragment:

package it.bitrack.fabio.bitrack;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import android.view.KeyEvent;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AssetMngtView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AssetMngtView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AssetMngtView extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    View view;

    ListView assetMngtListView;
    ArrayAdapter<String> listAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public AssetMngtView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AssetMngtView.
     */
    // TODO: Rename and change types and number of parameters
    public static AssetMngtView newInstance(String param1, String param2) {
        AssetMngtView fragment = new AssetMngtView();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onBackPressed() {

        android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStack();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_asset_mngt_view, container, false);

        assetMngtListView = (ListView) view.findViewById(R.id.assetMngtListView);
        setListView();

        return view;
    }

    public void setListView() {

        String[] options = new String[]{"Bind tag & thing", "Create new thing", "Edit existent thing", "Maintain existent thing", "View things notifications"};

        ArrayList<String> optionsList = new ArrayList<String>();
        optionsList.addAll(Arrays.asList(options));

        listAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, optionsList);

        assetMngtListView.setAdapter(listAdapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}


问:
Trigger to log inserted/updated/deleted values SQL Server 2016
The application adds/updates/deletes rows to table X. Sample below.

```<code>|ID|Type*|Name |Value|Description
|1 |1    |Mike |100  |-
|2 |1    |John |50   |-
|3 |1    |Vince|10   |-
</code>```

*Column Type = 1 - this is data from application

Column Type = 2 - this will be log data

I need trigger to log inserted/updated/deleted values also in a table X.

For example when change in application row number 2 and 3:

```<code>|ID|Type|Name  |Value|Description
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
</code>```

The result on table X should be like this:

```<code>|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION
</code>```

When the application adds another row:

```<code>|ID|Type|Name  |Value|Description
|6 |1   |Paul  |200  |-
</code>```

The result on table X should be like this:

```<code>|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION
|6 |1   |Paul  |200  |-
|7 |2   |Paul  |200  |INSERT OPERATION
</code>```

...

答:
What problem do you face ?.

Those triggers are quite simple:

```<code>CREATE TRIGGER [MY_TABLE_Inserts] ON MY_TABLE AFTER INSERT
AS
BEGIN
  insert into MY_TABLE (TYPE, NAME, VALUE, DESCRIPTION)
         select 2, NAME, VALUE, 'INSERT OPERATION'
         from inserted
         where TYPE = 1;
END

CREATE TRIGGER [MY_TABLE_Inserts] ON MY_TABLE AFTER UPDATE
AS
BEGIN
  insert into MY_TABLE (TYPE, NAME, VALUE, DESCRIPTION)
         select 2, NAME, VALUE, 'UPDATE OPERATION'
         from inserted
         where TYPE = 1;
END

CREATE TRIGGER [MY_TABLE_Inserts] ON MY_TABLE AFTER DELETE
AS
BEGIN
  insert into MY_TABLE (TYPE, NAME, VALUE, DESCRIPTION)
         select 2, NAME, VALUE, 'DELETE OPERATION'
         from deleted
         where TYPE = 1;
END
</code>```

Doesn't something like that works for you ?.

By the way, the WHERE TYPE = 1; prevents to re-log your logging operations.

Body:
The application adds/updates/deletes rows to table X. Sample below.

|ID|Type*|Name |Value|Description
|1 |1    |Mike |100  |-
|2 |1    |John |50   |-
|3 |1    |Vince|10   |-

*Column Type = 1 - this is data from application

Column Type = 2 - this will be log data

I need trigger to log inserted/updated/deleted values also in a table X.

For example when change in application row number 2 and 3:

|ID|Type|Name  |Value|Description
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-

The result on table X should be like this:

|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION

When the application adds another row:

|ID|Type|Name  |Value|Description
|6 |1   |Paul  |200  |-

The result on table X should be like this:

|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION
|6 |1   |Paul  |200  |-
|7 |2   |Paul  |200  |INSERT OPERATION

...

Body:
What problem do you face ?.

Those triggers are quite simple:

CREATE TRIGGER [MY_TABLE_Inserts] ON MY_TABLE AFTER INSERT
AS
BEGIN
  insert into MY_TABLE (TYPE, NAME, VALUE, DESCRIPTION)
         select 2, NAME, VALUE, 'INSERT OPERATION'
         from inserted
         where TYPE = 1;
END

CREATE TRIGGER [MY_TABLE_Inserts] ON MY_TABLE AFTER UPDATE
AS
BEGIN
  insert into MY_TABLE (TYPE, NAME, VALUE, DESCRIPTION)
         select 2, NAME, VALUE, 'UPDATE OPERATION'
         from inserted
         where TYPE = 1;
END

CREATE TRIGGER [MY_TABLE_Inserts] ON MY_TABLE AFTER DELETE
AS
BEGIN
  insert into MY_TABLE (TYPE, NAME, VALUE, DESCRIPTION)
         select 2, NAME, VALUE, 'DELETE OPERATION'
         from deleted
         where TYPE = 1;
END

Doesn't something like that works for you ?.

By the way, the WHERE TYPE = 1; prevents to re-log your logging operations.


问:
How to gulp-regex-replace only the first match?
Below is the content from project.json file. I want the first occurrence of 'version' value to be replaced.

```<code>{
  "title": "Project Title",
  "copyright": "Copyright Info",
  "description": "Project Description",
  "version": "1.0.0",
  "buildOptions": {
    "xmlDoc": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }
  }
}
</code>```

The below code using gulp-regex-replace changes all occurrences of version value to 1.0.1.

```<code>var targetVersion= "1.0.1";
gulp.task('replace', function () {
    return gulp.src(['./src/**/project.json'])
        .pipe(bom())
        .pipe(replace({ regex: '\\n\\s\\s\\"version\\"\\:\\s\\"([0-9a-zA-Z.-]+)\\"', replace: `${targetVersion}` }))
        .pipe(gulp.dest('./src'));
});
</code>```

How can I make this code replace only the first occurrence of version value?

答:
The gulp-regex-replace plugin uses global match:
https://github.com/mikrofusion/gulp-regex-replace/blob/master/index.js#L31

Another similar plugin gulp-replace accepts a custom regexp object:

```<code>replace(/__your_pattern__/, targetVersion);
</code>```

Without the g modifier in the pattern, JS will only match the first occurrence.

Body:
Below is the content from project.json file. I want the first occurrence of 'version' value to be replaced.

{
  "title": "Project Title",
  "copyright": "Copyright Info",
  "description": "Project Description",
  "version": "1.0.0",
  "buildOptions": {
    "xmlDoc": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }
  }
}

The below code using gulp-regex-replace changes all occurrences of version value to 1.0.1.

var targetVersion= "1.0.1";
gulp.task('replace', function () {
    return gulp.src(['./src/**/project.json'])
        .pipe(bom())
        .pipe(replace({ regex: '\\n\\s\\s\\"version\\"\\:\\s\\"([0-9a-zA-Z.-]+)\\"', replace: `${targetVersion}` }))
        .pipe(gulp.dest('./src'));
});

How can I make this code replace only the first occurrence of version value?

Body:
The gulp-regex-replace plugin uses global match:
https://github.com/mikrofusion/gulp-regex-replace/blob/master/index.js#L31

Another similar plugin gulp-replace accepts a custom regexp object:

replace(/__your_pattern__/, targetVersion);

Without the g modifier in the pattern, JS will only match the first occurrence.


答:
in ES 6 you can use shortcuts, like this:

```<code>function getShortMessages(messages) {
    return messages.filter( messages => messages.message.length < 50).map( object => object.message )
}
</code>```

Its depend on you which one is readable. In one line you dont need to use {} nor return and if you use array function, with 1 parameter you also dont need (messages) => , you can use only messages =>

Title: What's the most readable way to write nested functions in javascript?

Body:
in ES 6 you can use shortcuts, like this:

function getShortMessages(messages) {
    return messages.filter( messages => messages.message.length < 50).map( object => object.message )
}

Its depend on you which one is readable. In one line you dont need to use {} nor return and if you use array function, with 1 parameter you also dont need (messages) => , you can use only messages =>


问:
Elasticsearch native or elasticsearch-odm
I'm preparing to build a application (CMS) using ElasticSearch on Nodejs backend.
I'm choosing between elasticsearch native from ES and elasticsearch-odm from npm.
I'm test some example with CURL, Kibana RESTful API and see it simple to useful.
My system used Mongooese for other collections so i wonder if elasticsearch-odm reasonable proposal if it support same...
I am total new in this field, near realtime search as ES.
Please give me any infomation . . .</p>

答:
What's your question?

1: Run ES standalone or as part of the application?
It's better to run Elasticsearch standalone. You won't start ES every time when you start your application. Startingup ES can can take some time (starting, syncing; takes longer when you have a lot of data).

2: Is ES a good replacement for MongoDB?
Depends on your requirement. Elasticsearch is for SEARCH. Don't use is as (primary) database. Elasticsearch is not transactional! (there are more reasons why you won't do that)


问:
Listen to shift+key pression in Angularjs with Firefox
I'm trying to detect SHIFT+TAB pression in angularjs. The code below works well in IE 11 and Chrome, but Firefox keeps saying "evt is undefined".
This error appears with the pression of any key in Firefox. How can I solve this?</p>

```<code>function isShiftTabPressed (event) {
  var keyCode = getKeyCodeFromEvent(event);
  if (listenForShiftKey() && keyCode === 9) {
    return true;
  } else {
    return false;
  }
}

function listenForShiftKey (e) {
  var evt = e || window.event;
  if (evt.shiftKey) {
    return true;
  } else {
    return false;
  }
}

function getKeyCodeFromEvent (event) {
  event = event || window.event;
  return (typeof event.which === 'undefined') ? event.keyCode : event.which;
}
</code>```

答:
if (listenForShiftKey(event) && keyCode === 9)
you are not passing event to function listenForShiftKey()

Body:
I'm trying to detect SHIFT+TAB pression in angularjs. The code below works well in IE 11 and Chrome, but Firefox keeps saying "evt is undefined".
This error appears with the pression of any key in Firefox. How can I solve this?

function isShiftTabPressed (event) {
  var keyCode = getKeyCodeFromEvent(event);
  if (listenForShiftKey() && keyCode === 9) {
    return true;
  } else {
    return false;
  }
}

function listenForShiftKey (e) {
  var evt = e || window.event;
  if (evt.shiftKey) {
    return true;
  } else {
    return false;
  }
}

function getKeyCodeFromEvent (event) {
  event = event || window.event;
  return (typeof event.which === 'undefined') ? event.keyCode : event.which;
}


问:
How to subset netcdf CRU V4.00 data in R using lat-lon?
I want to subset a region from cru global data. The "cmsaf" package , box_mergetime function can subset the CMIP5 and CORDEX .nc data but in CRU .nc data it gives following error.

```<code>>library(cmsaf)
>wd<-getwd()
>box_mergetime("tmp", wd, "cru_ts4.00.1901.1910", "output", 67,98,8,38)

get file information
[1] "vobjtovarid4: error #F: I could not find the requsted var (or dimvar) in the file!"
[1] "var (or dimvar) name: longitude"
[1] "file name: C:/Users/Deepak/Documents/eg/ip/cru_ts4.00.1901.1910.tmp.nc"
Error in vobjtovarid4(nc, varid, verbose = verbose, allowdimvar = TRUE) :
 Variable not found
</code>```

link of data file.

答: The reason for this error message was a missing standard name of longitude and latitude in CRU NetCDF data. I fixed this issue and with cmsaf version 1.8.0 it should work now. The cmsaf package offers similar functions as cdo (e.g., sellonlatbox, timmean, fldmean are included). </p>

Body:
I want to subset a region from cru global data. The "cmsaf" package , box_mergetime function can subset the CMIP5 and CORDEX .nc data but in CRU .nc data it gives following error.

>library(cmsaf)
>wd<-getwd()
>box_mergetime("tmp", wd, "cru_ts4.00.1901.1910", "output", 67,98,8,38)

get file information
[1] "vobjtovarid4: error #F: I could not find the requsted var (or dimvar) in the file!"
[1] "var (or dimvar) name: longitude"
[1] "file name: C:/Users/Deepak/Documents/eg/ip/cru_ts4.00.1901.1910.tmp.nc"
Error in vobjtovarid4(nc, varid, verbose = verbose, allowdimvar = TRUE) :
 Variable not found

link of data file.


问:
ko.observableArray for multiple values set
I am use knockout ovservable array to store select option data:

example:

```<code>var anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Bear" },
    { name: "George", type: "Hippo" },
    { name: "Zippy", type: "Unknown" }
]);
</code>```

but I want like to set it like this whereby data is pass an array:

```<code>anotherObservableArray = ko.observableArray([]);

 somefunction({ function(data) {

    anotherObservableArray(data);

    });

 });
</code>```

what does the data have to contain and how do I go about by setting it to name and type?

data consist of array list?

or perhaps I could do like

```<code> anotherObservableAray().push(name: data[i], type: 'bear');
 anotherObservableAray().push(name: data[i], type: 'Grumpjaw');
</code>```

答:
You can use the standard push and unshift methods to add items to on observable array. If you want to add multiple items at once, just iterate over them:

```<code>var observableArr = ko.observableArray();

function addToObservable(arr) {
    arr.forEach(function(item) {
        observableArr.push(item);
    });
}
</code>```

Body:
I am use knockout ovservable array to store select option data:

example:

var anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Bear" },
    { name: "George", type: "Hippo" },
    { name: "Zippy", type: "Unknown" }
]);

but I want like to set it like this whereby data is pass an array:

anotherObservableArray = ko.observableArray([]);

 somefunction({ function(data) {

    anotherObservableArray(data);

    });

 });

what does the data have to contain and how do I go about by setting it to name and type?

data consist of array list?

or perhaps I could do like

 anotherObservableAray().push(name: data[i], type: 'bear');
 anotherObservableAray().push(name: data[i], type: 'Grumpjaw');

Body:
You can use the standard push and unshift methods to add items to on observable array. If you want to add multiple items at once, just iterate over them:

var observableArr = ko.observableArray();

function addToObservable(arr) {
    arr.forEach(function(item) {
        observableArr.push(item);
    });
}


答:
the problem is that Fragment does not have public void onBackPressed() method.

you are getting the error because your method is annotated with @Override but it is not actually overriding any method in the superclass. the purpose of @Override is exactly this one, letting you know that you think you're overriding something but, actually, you aren't

on a side note, what you are trying to do is unnecessary. if you press the back button and you have fragments in the back stack they will be popped automatically. try this

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

    public static class FragmentA extends Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = new TextView(getActivity());
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setBackgroundColor(0xffff0000);
            return view;
        }
    }

    public static class FragmentB extends Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = new TextView(getActivity());
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setBackgroundColor(0xff00ff00);
            return view;
        }
    }

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

        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
                .add(R.id.fragment_container, new FragmentA(), FragmentA.class.getSimpleName())
                .commit();

        // notice addToBackStack here
        fm.beginTransaction()
                .add(R.id.fragment_container, new FragmentB(), FragmentB.class.getSimpleName())
                .addToBackStack(FragmentB.class.getSimpleName())
                .commit();
    }
}
</code>```

Title: onBackPressed() and Fragments

Body:
the problem is that Fragment does not have public void onBackPressed() method.

you are getting the error because your method is annotated with @Override but it is not actually overriding any method in the superclass. the purpose of @Override is exactly this one, letting you know that you think you're overriding something but, actually, you aren't

on a side note, what you are trying to do is unnecessary. if you press the back button and you have fragments in the back stack they will be popped automatically. try this

public class FragmentsActivity extends AppCompatActivity {

    public static class FragmentA extends Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = new TextView(getActivity());
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setBackgroundColor(0xffff0000);
            return view;
        }
    }

    public static class FragmentB extends Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = new TextView(getActivity());
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setBackgroundColor(0xff00ff00);
            return view;
        }
    }

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

        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
                .add(R.id.fragment_container, new FragmentA(), FragmentA.class.getSimpleName())
                .commit();

        // notice addToBackStack here
        fm.beginTransaction()
                .add(R.id.fragment_container, new FragmentB(), FragmentB.class.getSimpleName())
                .addToBackStack(FragmentB.class.getSimpleName())
                .commit();
    }
}


问:
C# string array from JSON
I'm currently using Newtonsoft's json library to deserialize json from a file.

JSON:

```<code>{
"name":"test",
"description":"test",
"tags":"Maps"
}
</code>```

C#:

```<code>public class RootObject
{
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
}
</code>```

The "tags" has to be an array as it is required for steam.

How can I retrieve the "tags" as an string array?
The console prints out this expection:

```<code>Newtonsoft.Json.JsonSerializationException: Error converting value "Maps" to type 'System.String[]'. Path 'tags', line 4, position 17
</code>```

答:
I would suggest you change Tag into  Dictionary e.g. public Dictionary tags { get; set; }</p>

```<code>public class RootObject
 {
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
    public Dictionary<string, Tag> tags { get; set; }
 }

 public Tag
 {
   public string name{ get; set; }
 }
</code>```

Title: C# string array from JSON

Body:
I'm currently using Newtonsoft's json library to deserialize json from a file.

JSON:

{
"name":"test",
"description":"test",
"tags":"Maps"
}

C#:

public class RootObject
{
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
}

The "tags" has to be an array as it is required for steam.

How can I retrieve the "tags" as an string array?
The console prints out this expection:

Newtonsoft.Json.JsonSerializationException: Error converting value "Maps" to type 'System.String[]'. Path 'tags', line 4, position 17

Body:
I would suggest you change Tag into  Dictionary e.g. public Dictionary tags { get; set; }

public class RootObject
 {
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
    public Dictionary<string, Tag> tags { get; set; }
 }

 public Tag
 {
   public string name{ get; set; }
 }


问:
Getting row or TreePath of JTree node that is not in the viewport
I have a JTree and a custom renderer.

The JTree is a tree of ip addresses by switch and port number.

I have a graph of the ip addresses.

When the user clicks on a graph line, I try to update the JTree to show the line selected by the user.

If the ip selected by the user's mouse click in the graph, the renderer contains that node and other actions happen easily because the row and TreePath are available.

If the list of ip's is large and some are scrolled out of the viewport, I am having a problem finding out what the row or treenode is for the object/ip that I want to select and show in the viewport.

I have an ActionEvent in the JTree that gets some of the text that makes up the nodes' text, returned from getUserObject().

I don't know how to find the row or TreeNode.  If I could find them I could check if the row was visible and if not call makeVisible(treePath) - or use scrollPane.getViewport().getViewRect() and compare it to the rect of the treeNode.

Thanks for any tips or direction ...
Jim

答:
I found a better method for working with a JTree.

The method above works ok for JLists.

Since I have a map of rows, given the row number there is a JTree specific call of Component.

```<code>            scrollRowToVisible( row );
</code>```

and the code becomes

```<code>    if ( ipRowMap.containsKey( ip )) {
        row = ipRowMap.get( ip );
        scrollRowToVisible( row );
    }
</code>```

Body:
I found a better method for working with a JTree.

The method above works ok for JLists.

Since I have a map of rows, given the row number there is a JTree specific call of Component.

            scrollRowToVisible( row );

and the code becomes

    if ( ipRowMap.containsKey( ip )) {
        row = ipRowMap.get( ip );
        scrollRowToVisible( row );
    }


问:
When the Duration.between() in Java DateTime return negative value
I am preaparing for the Java OCP Test, and in the mock test there is a question about Java DateTime like this:

Given that New York is 3 hours ahead of Los Angeles, what will the
  following code print?

```<code>LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);
ZonedDateTime nyZdt = ldt.atZone(nyZone);
ZonedDateTime laZdt = ldt.atZone(laZone);
Duration d = Duration.between(nyZdt, laZdt);
System.out.println(d);
</code>```

And the correct answer is PT3H but I am a little bit confused here is if the book gives the wrong answer or not?

Given is NY 3 hours ahead of LA, does it mean, for example, NY is 5:00 and then LA will be 2:00. So the Duration.between(5,2) should be PT-3H because according to the Javadoc: The result of this method can be a negative period if the end is before the start. To guarantee to obtain a positive duration call abs() on the result., and in this case "2" is before "5" so the result should be PT-3H, not PT3H.

What do you think, which one is correct?

答:
3 hours is correct. Simply run the code..</p>

```<code>@Test
public void test1() throws Exception {

    LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);
    ZonedDateTime nyZdt = ldt.atZone(ZoneId.of("America/New_York"));
    ZonedDateTime laZdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));
    Duration d = Duration.between(nyZdt, laZdt);
    System.out.println(d.toHours());

}
</code>```

Body:
I am preaparing for the Java OCP Test, and in the mock test there is a question about Java DateTime like this:

Given that New York is 3 hours ahead of Los Angeles, what will the
  following code print?

LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);
ZonedDateTime nyZdt = ldt.atZone(nyZone);
ZonedDateTime laZdt = ldt.atZone(laZone);
Duration d = Duration.between(nyZdt, laZdt);
System.out.println(d);

And the correct answer is PT3H but I am a little bit confused here is if the book gives the wrong answer or not?

Given is NY 3 hours ahead of LA, does it mean, for example, NY is 5:00 and then LA will be 2:00. So the Duration.between(5,2) should be PT-3H because according to the Javadoc: The result of this method can be a negative period if the end is before the start. To guarantee to obtain a positive duration call abs() on the result., and in this case "2" is before "5" so the result should be PT-3H, not PT3H.

What do you think, which one is correct?

Body:
3 hours is correct. Simply run the code..

@Test
public void test1() throws Exception {

    LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);
    ZonedDateTime nyZdt = ldt.atZone(ZoneId.of("America/New_York"));
    ZonedDateTime laZdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));
    Duration d = Duration.between(nyZdt, laZdt);
    System.out.println(d.toHours());

}


问:
mdl-radio with ngFor each radio button that is clicked remains selected
I have three product arrays and a variable to hold current one as a selection:

```<code>product_types=['One', 'Two', 'Three']

product_type_one = [
{'description': 'Type one sample one', 'type': 'one'},
{'description': 'Type one sample two', 'type': 'one'},
{'description': 'Type one sample three', 'type': 'one'},
]

product_type_two = [
{'description': 'Type two sample one', 'type': 'two'},
{'description': 'Type two sample two', 'type': 'two'},
{'description': 'Type two sample three', 'type': 'two'},
]

product_type_three = [
{'description': 'Type three sample one', 'type': 'three'},
{'description': 'Type three sample two', 'type': 'three'},
{'description': 'Type three sample three', 'type': 'three'},
]

selectedProduct=null;
</code>```

On my template I am populating radio buttons so that user can select one of the product groups as following:

```<code>  <div class="my-filters" *ngFor="let product of product_types">
    <mdl-radio
    name="productgroup"
    value="product"
    ngModel='selectedProduct'
    (change)="showProduct(product)"
    mdl-ripple>{{product}}</mdl-radio>
  </div><br>

 <mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2">
  <mdl-card-title mdl-card-expand>
   <h4>
     {{product.description}}
   </h4>
 </mdl-card-title>
 <mdl-card-actions mdl-card-border>
  <button mdl-button mdl-colored mdl-ripple (click)="openDialog()">
    view
  </button>
  <mdl-layout-spacer></mdl-layout-spacer>
  <mdl-icon>shopping_cart</mdl-icon>
</mdl-card-actions>
</mdl-card>
</code>```

Until here whatever radio button user clicks, correct array is populated in my mdl-cards, however all the radio buttons that user clicks one after other remain clicked and not just the current selection:

What am I doing wrong?

答:
I updated my for loop like following:</p>

```<code> <div *ngFor="let product of product_types" class="my-filters">
    <mdl-radio name="productgroup" [value]='product' [(ngModel)]="selectedProduct" (change)="showProduct(product)"> {{product}} </mdl-radio> <br>
  </div>
</code>```

Body:
I have three product arrays and a variable to hold current one as a selection:

product_types=['One', 'Two', 'Three']

product_type_one = [
{'description': 'Type one sample one', 'type': 'one'},
{'description': 'Type one sample two', 'type': 'one'},
{'description': 'Type one sample three', 'type': 'one'},
]

product_type_two = [
{'description': 'Type two sample one', 'type': 'two'},
{'description': 'Type two sample two', 'type': 'two'},
{'description': 'Type two sample three', 'type': 'two'},
]

product_type_three = [
{'description': 'Type three sample one', 'type': 'three'},
{'description': 'Type three sample two', 'type': 'three'},
{'description': 'Type three sample three', 'type': 'three'},
]

selectedProduct=null;

On my template I am populating radio buttons so that user can select one of the product groups as following:

    <mdl-radio
    name="productgroup"
    value="product"
    ngModel='selectedProduct'
    (change)="showProduct(product)"
    mdl-ripple>{{product}}</mdl-radio>

 <mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2">
  <mdl-card-title mdl-card-expand>

     {{product.description}}

 </mdl-card-title>
 <mdl-card-actions mdl-card-border>
  <button mdl-button mdl-colored mdl-ripple (click)="openDialog()">
    view
  </button>
  <mdl-layout-spacer></mdl-layout-spacer>
  <mdl-icon>shopping_cart</mdl-icon>
</mdl-card-actions>
</mdl-card>

Until here whatever radio button user clicks, correct array is populated in my mdl-cards, however all the radio buttons that user clicks one after other remain clicked and not just the current selection:

What am I doing wrong?

Body:
I updated my for loop like following:

 <div *ngFor="let product of product_types" class="my-filters">
    <mdl-radio name="productgroup" [value]='product' [(ngModel)]="selectedProduct" (change)="showProduct(product)"> {{product}} </mdl-radio> <br>
  </div>


问:
I need to get json using http when loading the app
I am not getting result when i am loading the app.

but i am getting the result when clicking the button

```<code><button ion-item  (click)="goToDrivePage()">
</code>```

but i need to load automatically when loading the app.
any body help to get result?

答:
You can do it in your app component constructor or ngInit function like</p>

```<code>export class AppComponent implements OnInit {
    ngOnInit() {
            this.dataService.getData()
            .subscribe((data: any) => {
                this.data = data;
            });
        }
//OR
constructor() {
            this.dataService.getData()
            .subscribe((data: any) => {
                this.data = data;
            });
        }
}
</code>```

Body:
I am not getting result when i am loading the app.

but i am getting the result when clicking the button

<button ion-item  (click)="goToDrivePage()">

but i need to load automatically when loading the app.
any body help to get result?

Body:
You can do it in your app component constructor or ngInit function like

export class AppComponent implements OnInit {
    ngOnInit() {
            this.dataService.getData()
            .subscribe((data: any) => {
                this.data = data;
            });
        }
//OR
constructor() {
            this.dataService.getData()
            .subscribe((data: any) => {
                this.data = data;
            });
        }
}


答:
Duration.between returns the difference between the two instants. For LocalDateTime, this means the correct answer requires normalizing the time zones. Since the same local hour in LA is later than in NY, the result is positive.

At 6:00 AM in NY, it's 3:00 AM in LA, which means that 3 hours will elapse until it's 6:00 AM in LA.
Conversely, at 6:00 AM in LA, it's 9:00 AM in NY, which means 3 hours have ellapsed since 6:00 AM NY.

```<code>LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);
ZonedDateTime nyZdt = ldt.atZone(nyZone); // 6:00 AM NY = 3:00 AM LA
ZonedDateTime laZdt = ldt.atZone(laZone); // 6:00 AM LA = 9:00 AM NY
Duration d = Duration.between(nyZdt, laZdt); // 9:00 AM NY - 6:00 AM NY = 3H   OR 3:00 AM LA - 6:00 AM LA = 3H
</code>```

Title: When the Duration.between() in Java DateTime return negative value

Body:
Duration.between returns the difference between the two instants. For LocalDateTime, this means the correct answer requires normalizing the time zones. Since the same local hour in LA is later than in NY, the result is positive.

At 6:00 AM in NY, it's 3:00 AM in LA, which means that 3 hours will elapse until it's 6:00 AM in LA.
Conversely, at 6:00 AM in LA, it's 9:00 AM in NY, which means 3 hours have ellapsed since 6:00 AM NY.

LocalDateTime ldt = LocalDateTime.of(2017, 12, 02, 6, 0, 0);
ZonedDateTime nyZdt = ldt.atZone(nyZone); // 6:00 AM NY = 3:00 AM LA
ZonedDateTime laZdt = ldt.atZone(laZone); // 6:00 AM LA = 9:00 AM NY
Duration d = Duration.between(nyZdt, laZdt); // 9:00 AM NY - 6:00 AM NY = 3H   OR 3:00 AM LA - 6:00 AM LA = 3H


问:
How to specify memory allocation for Pandas Dataframes?
I am trying to merge two big pandas dataframes but it raises a memory error on my 4GB RAM laptop so I tried on in computer lab on 16 GB RAM but it's  still raising the same error (on the same line code crashes ).

I am not able to resolve why pandas raising the same error and not using the 16 GB RAM space. Please help me to resolve it .

```<code>feature_AtomPairs2DFingerprintCount=pd.read_csv("/home/adarsh/big_data_features/AtomPairs2DFingerprintCount.csv")
feature_AtomPairs2DFingerprinter=pd.read_csv("/home/adarsh/big_data_features/AtomPairs2DFingerprinter.csv")

merged_data_2=pd.merge(feature_AtomPairs2DFingerprinter,feature_AtomPairs2DFingerprintCount,how='left')

MERGED_DATA=pd.read_csv('/home/adarsh/comp_des.csv')

total_merged=pd.merge(MERGED_DATA,merged_data_2,how='left')
</code>```

答:
The resource.getrlimit call will tell you the hard and soft limits for various system resources.  For memory

```<code>    soft, hard = resource.getrlimit(resource.RLIMIT_AS)
</code>```

The softlimit is the value which, when reached, the operating system will typically restrict the process or notify it with a signal.  The hard limit represents an upper bound on the values for the softlimit.  The softlimit can be modified with an appropriate call to resource.setrlimit().  The hard limit is typically controlled by a system-wide parameter set the the system administrator.  It cannot be raised by user level processes, although it can be lowered.  This is reported to work on Linux but not MacOS or Windows where it returns -1 for both values.

I suspect that you are running up against the OS's max for process size.

Body:
I am trying to merge two big pandas dataframes but it raises a memory error on my 4GB RAM laptop so I tried on in computer lab on 16 GB RAM but it's  still raising the same error (on the same line code crashes ).

I am not able to resolve why pandas raising the same error and not using the 16 GB RAM space. Please help me to resolve it .

feature_AtomPairs2DFingerprintCount=pd.read_csv("/home/adarsh/big_data_features/AtomPairs2DFingerprintCount.csv")
feature_AtomPairs2DFingerprinter=pd.read_csv("/home/adarsh/big_data_features/AtomPairs2DFingerprinter.csv")

merged_data_2=pd.merge(feature_AtomPairs2DFingerprinter,feature_AtomPairs2DFingerprintCount,how='left')

MERGED_DATA=pd.read_csv('/home/adarsh/comp_des.csv')

total_merged=pd.merge(MERGED_DATA,merged_data_2,how='left')

Body:
The resource.getrlimit call will tell you the hard and soft limits for various system resources.  For memory

    soft, hard = resource.getrlimit(resource.RLIMIT_AS)

The softlimit is the value which, when reached, the operating system will typically restrict the process or notify it with a signal.  The hard limit represents an upper bound on the values for the softlimit.  The softlimit can be modified with an appropriate call to resource.setrlimit().  The hard limit is typically controlled by a system-wide parameter set the the system administrator.  It cannot be raised by user level processes, although it can be lowered.  This is reported to work on Linux but not MacOS or Windows where it returns -1 for both values.

I suspect that you are running up against the OS's max for process size.


问:
How to display json data into the android layout?
MY JSON looks like this. I just need to set these values in the layout of the fragment. So that the details about this product will be displayed. </p>

<p>```<code></p>

```<code>{
  "adid": 5,
  "uid": 1130,
  "userName": "Maëly",
  "cid": 5,
  "brand": null,
  "model": null,
  "title": "Nummular dermatitis",
  "description": "Nam sa dea ss "
  "address": "9795 Debra Center",
  "price": 1544,
  "photo1": "../../../img/mobile/oneplus/3t/3t-1.jpg",
  "photo2": null,
  "photo3": null,
  "photo4": null,
  "ip_add": null,
  "created": 1493921700000,
  "expiryDate": null,
  "published": true,
  "sold": null,
  "featured": true,
  "cond": true,
  "price_neg": true,
  "used_for": "8",
  "views": 1575,
  "city": "Kathmandu",
  "landmark": null,
  "quality": null,
  "alert": null,
  "features": [

  ]
}
</code>```

<p>```</code></p>

答: I'd suggest using a Gson converter. You can generate Gson POJO definitions with jsonschema2pojo - despite the name it also can use an example JSON.</p>

Body:
MY JSON looks like this. I just need to set these values in the layout of the fragment. So that the details about this product will be displayed.

{
  "adid": 5,
  "uid": 1130,
  "userName": "Maëly",
  "cid": 5,
  "brand": null,
  "model": null,
  "title": "Nummular dermatitis",
  "description": "Nam sa dea ss "
  "address": "9795 Debra Center",
  "price": 1544,
  "photo1": "../../../img/mobile/oneplus/3t/3t-1.jpg",
  "photo2": null,
  "photo3": null,
  "photo4": null,
  "ip_add": null,
  "created": 1493921700000,
  "expiryDate": null,
  "published": true,
  "sold": null,
  "featured": true,
  "cond": true,
  "price_neg": true,
  "used_for": "8",
  "views": 1575,
  "city": "Kathmandu",
  "landmark": null,
  "quality": null,
  "alert": null,
  "features": [

  ]
}


问:
VSCode complains syntax of create-react-app
I'm starting to use React in my future projects but there is one problem that I still don't know how to resolve.

So, I created an app using the command 'create-react-app react-app-project', but when I open it inside VSCode, I receive a few syntax warnings with the jshint. For example, the editor complains about the 'import' and the 'jsx'.

There's some jshint configuration that I can import inside my project so these warnings stop?

Thanks for the help!

答:
From the comments, it appears the original issue was solved by disabling the jshint extension.

If you are seeing unwanted errors in a JS file in VSCode and they are not coming from an extension, try setting:

```<code>"javascript.validate.enable": false
</code>```

Body:
From the comments, it appears the original issue was solved by disabling the jshint extension.

If you are seeing unwanted errors in a JS file in VSCode and they are not coming from an extension, try setting:

"javascript.validate.enable": false


问:
Python named placeholders with nested dictionary (JSON)
Im working with format and named placeholders and trying to figure out:
How is it possible to access nested items (eg. JSON objects) using named placeholders in Python?
For example

```<code>data = {
    'first': 'John', 'last': 'Doe',
    'kids': {
        'first': 'number1',
        'second': 'number2',
        'third': 'number3'
    }
}

'{first} {last} {kids}'.format(**data) # Python console
"John Doe {'second': 'number2', 'third': 'number3', 'first': 'number1'}"
</code>```

But how do I write my "named placeholder format", so that I could output

```<code> "John Doe, number1, number2, number3"
</code>```

Any clue as how to get the output from a JSON object is appreciated.

答:
String formatting supports indexing; you don't have to quote keys:

```<code>'{first} {last}, {kids[first]}, {kids[second]}, {kids[third]}'.format(**data)
</code>```

Demo:

```<code>>>> '{first} {last}, {kids[first]}, {kids[second]}, {kids[third]}'.format(**data)
'John Doe, number1, number2, number3'
</code>```

Body:
Im working with format and named placeholders and trying to figure out:
How is it possible to access nested items (eg. JSON objects) using named placeholders in Python?
For example

data = {
    'first': 'John', 'last': 'Doe',
    'kids': {
        'first': 'number1',
        'second': 'number2',
        'third': 'number3'
    }
}

'{first} {last} {kids}'.format(**data) # Python console
"John Doe {'second': 'number2', 'third': 'number3', 'first': 'number1'}"

But how do I write my "named placeholder format", so that I could output

 "John Doe, number1, number2, number3"

Any clue as how to get the output from a JSON object is appreciated.

Body:
String formatting supports indexing; you don't have to quote keys:

'{first} {last}, {kids[first]}, {kids[second]}, {kids[third]}'.format(**data)

Demo:

>>> '{first} {last}, {kids[first]}, {kids[second]}, {kids[third]}'.format(**data)
'John Doe, number1, number2, number3'


答:
To achieve what you want, you should override the onBackPressed() of the Activity associated like that:

```<code>@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
        getSupportFragmentManager().popBackStack();
    } else {
      finish();
    }
}
</code>```

Hope this helps.
Sorry for my english.

Title: onBackPressed() and Fragments

Body:
I am trying to use onBackPressed() in my Fragment so that I can allow the user to roll back in a pile of fragments he navigated in my app.

The problem is that, when I add the method below to my Fragment, it gives me the error: Method does not override method from its superclass.

@Override
public void onBackPressed() {

    android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack();

}

Would you know why?

Thanks!

Here goes the entire Fragment:

package it.bitrack.fabio.bitrack;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import android.view.KeyEvent;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AssetMngtView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AssetMngtView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AssetMngtView extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    View view;

    ListView assetMngtListView;
    ArrayAdapter<String> listAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public AssetMngtView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AssetMngtView.
     */
    // TODO: Rename and change types and number of parameters
    public static AssetMngtView newInstance(String param1, String param2) {
        AssetMngtView fragment = new AssetMngtView();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onBackPressed() {

        android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStack();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_asset_mngt_view, container, false);

        assetMngtListView = (ListView) view.findViewById(R.id.assetMngtListView);
        setListView();

        return view;
    }

    public void setListView() {

        String[] options = new String[]{"Bind tag & thing", "Create new thing", "Edit existent thing", "Maintain existent thing", "View things notifications"};

        ArrayList<String> optionsList = new ArrayList<String>();
        optionsList.addAll(Arrays.asList(options));

        listAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, optionsList);

        assetMngtListView.setAdapter(listAdapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

Body:
To achieve what you want, you should override the onBackPressed() of the Activity associated like that:

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
        getSupportFragmentManager().popBackStack();
    } else {
      finish();
    }
}

Hope this helps.
Sorry for my english.


问:
 larger break than usual?
This hasn't been a problem in the past, I don't know what has happened, but the
 element in my footer separates the text by like, 10px's. Wondering if I have some CSS or a tag I'm not aware of?

Here is my code:

.contentFake {
  background-color: #333;
  height: 200px;
}

.footer {
  width: 100%;
  position: fixed;
  margin-bottom: 0px;
  height: 80px;
  background-color: #1A1A1A;
  display: block;
}

.footerContent {
  width: 80%;
  margin: auto;
  padding: 20px;
  text-align: center;
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='contentFake'>
  <div class='footerContent'>
    <p>
      <font face="Helvetica" size="2" color="white">
        <font size="5" face="Indie Flower"><strong>THIS IS FOOTER</strong></font> <br />
        Home<br />
        Blog <br />
        Photo Feed <br />
        Vlogs <br />
        Farewell <br />
        BACK TO TOP <br /> © Jack Champions FOOTER All Rights Reserved 2017</font>
    </p>
  </div>
</div></code>```

jsfiddle: https://jsfiddle.net/gu1pdh5a/

The code  you run direct here, is the code I wish to see, yet on mine it turns up like this?

答:
Your
 element has default margins (top and bottom), so just overwrite them with new styles for p elements like this for example p {margin: 0;}

Title: <br> larger break than usual?

Body:
This hasn't been a problem in the past, I don't know what has happened, but the
 element in my footer separates the text by like, 10px's. Wondering if I have some CSS or a tag I'm not aware of?

Here is my code:

.contentFake {
  background-color: #333;
  height: 200px;
}

.footer {
  width: 100%;
  position: fixed;
  margin-bottom: 0px;
  height: 80px;
  background-color: #1A1A1A;
  display: block;
}

.footerContent {
  width: 80%;
  margin: auto;
  padding: 20px;
  text-align: center;
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
  border: none;
}

        THIS IS FOOTER

        Home

        Blog

        Photo Feed

        Vlogs

        Farewell

        BACK TO TOP
 © Jack Champions FOOTER All Rights Reserved 2017

jsfiddle: https://jsfiddle.net/gu1pdh5a/

The code  you run direct here, is the code I wish to see, yet on mine it turns up like this?

Body: Your <p> element has default margins (top and bottom), so just overwrite them with new styles for p elements like this for example p {margin: 0;}


问:
how to fetch data in view or display it in a page in codeigniter
this is my profile.php code i want to display it in webpage

```<code><!-- Bridegroom Profile Details -->
<div class="w3ls-list">

    <div class="container">

                <h2>Bridegroom Profile Details</h2>

    <div class="col-md-9 profiles-list-agileits">
        <div class="single_w3_profile">
            <div class="agileits_profile_image">
    <?php foreach ($profile_details as $row) { ?>
                                <img src="<?php echo $row['upload'];?>" alt="profile image" />
                                           <?php } ?>

            </div>

            <div class="clearfix"></div>
        </div>

        <div class="profile_w3layouts_details">

            <div class="agileits_aboutme">
                <h4>Profile</h4>
                <h5>Personal Details:</h5>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Profile for : </label>
                    <div class="col-sm-9 w3_details">

                                               <!--Brother-->
                    </div>
                    <div class="clearfix"> </div>
                </div>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Name : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Gender : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Dob : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Religion : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Mobile : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                                    </div>

                            </div>

        </div>

    </div>
           </div>

    </div>
</code>```

this is my controller home.php
please help to how to diplay this profile

```<code> public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

     $this->load->view('index',$data);
 }
</code>```

答:
Proper Way to fetch data in view or display it in a page in CodeIgniter:

if you know that you are fetching a single record use row_array instead of result_array. Use result_array only when you know that you are fetchig multiple rows form database.

Your Model:

```<code>public function get_single_profile($param1)
{
        $query = $this->db
                ->select('*')
                ->where('id', $param1)
                ->get('profile');
        $profile_data = $query->row_array();
        return $profile_data;
}
</code>```

In Controller:
    Load Model in the __construct

```<code>    public function profile($param1)
    {
        $this->load->model ('your_model');
        $profile_data = $this->your_model->get_single_profile ($param1);

        $this->load->view ('index',['profile_data' => $profile_data]);
    }
</code>```

On the view Page:

```<code><?php if(isset($profile_data) && !empty($profile_data)){ ?>

    <img src="<?php echo $profile_data['upload'];?>" alt="profile image" />
    //And So on...

<?php } ?>
</code>```

Body:
this is my profile.php code i want to display it in webpage

Bridegroom Profile Details

    <?php foreach ($profile_details as $row) { ?>
                                <img src="<?php echo $row['upload'];?>" alt="profile image" />
                                           <?php } ?>

Profile

Personal Details:

                    Profile for :

                    Name :

                    Gender :

                    Dob :

                    Religion :

                    Mobile :

this is my controller home.php
please help to how to diplay this profile

 public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

     $this->load->view('index',$data);
 }

Body:
Proper Way to fetch data in view or display it in a page in CodeIgniter:

if you know that you are fetching a single record use row_array instead of result_array. Use result_array only when you know that you are fetchig multiple rows form database.

Your Model:

public function get_single_profile($param1)
{
        $query = $this->db
                ->select('*')
                ->where('id', $param1)
                ->get('profile');
        $profile_data = $query->row_array();
        return $profile_data;
}

In Controller:
    Load Model in the __construct

    public function profile($param1)
    {
        $this->load->model ('your_model');
        $profile_data = $this->your_model->get_single_profile ($param1);

        $this->load->view ('index',['profile_data' => $profile_data]);
    }

On the view Page:

<?php if(isset($profile_data) && !empty($profile_data)){ ?>

    <img src="<?php echo $profile_data['upload'];?>" alt="profile image" />
    //And So on...

<?php } ?>


问:
Dynamically adjust Textfield width to Content
Is there a way in Qooxdoo to automatically adjust the width of the qx.ui.form.TextField to fit its Content?
It means if someone types in the Textfield it should grow and vice versa.

答:
Here is an example in the Qooxdoo playground that listen to input's updates, use the canvas to calculate the text's length and adjust the textfield's width.

var tt = new qx.ui.form.TextField();
this.getRoot().add(tt);

tt.addListener("input",function(e){
  this.setWidth(parseInt(getTextWidth(e.getData(), "12px Verdana"))+10);
},tt);

function getTextWidth(text, font) {
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}
```

Body:
Here is an <a href="http://www.qooxdoo.org/current/playground/#%7B%22code%22%3A%22var%2520tt%2520%253D%2520new%2520qx.ui.form.TextField()%253B%250Athis.getRoot().add(tt)%253B%250A%250A%250Att.addListener(%2522input%2522%252Cfunction(e)%257B%250A%2520%2520this.setWidth(parseInt(getTextWidth(e.getData()%252C%2520%252212px%2520Verdana%2522))%252B10)%253B%250A%257D%252Ctt)%253B%250A%250Afunction%2520getTextWidth(text%252C%2520font)%2520%257B%250A%2520%2520%2520%2520var%2520canvas%2520%253D%2520getTextWidth.canvas%2520%257C%257C%2520(getTextWidth.canvas%2520%253D%2520document.createElement(%2522canvas%2522))%253B%250A%2520%2520%2520%2520var%2520context%2520%253D%2520canvas.getContext(%25222d%2522)%253B%250A%2520%2520%2520%2520context.font%2520%253D%2520font%253B%250A%2520%2520%2520%2520var%2520metrics%2520%253D%2520context.measureText(text)%253B%250A%2520%2520%2520%2520return%2520metrics.width%253B%250A%257D%250A%250A%250A%22%2C%20%22mode%22%3A%22ria%22%7D" rel="nofollow noreferrer">example in the Qooxdoo playground that listen to input's updates, use the canvas to calculate the text's length and adjust the textfield's width.

var tt = new qx.ui.form.TextField();
this.getRoot().add(tt);

tt.addListener("input",function(e){
  this.setWidth(parseInt(getTextWidth(e.getData(), "12px Verdana"))+10);
},tt);

function getTextWidth(text, font) {
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}


问:
R's cbind functionality in Spark Scala
I have a requirement to cbind [as it happens in R] two dataframes in spark using scala, which do not have a ID column.
Any pointers on any readily available function for it, or some other workaround for it?

Example:

DF1:

```<code>    Name Age
    ABC  10
    BCD  11
</code>```

DF2:

```<code>    Marks
    75
    85
</code>```

Result needed:

```<code>    DF3:
    Name Age Marks
    ABC  10  75
    BCD  11  85
</code>```

答:
This works perfectly as a workaround:

```<code>    df1 = df1.withColumn("id", monotonically_increasing_id())
    df2 = df2.withColumn("id", monotonically_increasing_id())
    df3 = df2.join(df1, "id", "outer").drop("id")
</code>```

For spark 1.6.*, the last line needs to be:

```<code>    df3 = df2.join(df1, df1("id") === df2("id"), "outer").drop("id")
</code>```

Title: R's cbind functionality in Spark Scala

Body:
I have a requirement to cbind [as it happens in R] two dataframes in spark using scala, which do not have a ID column.
Any pointers on any readily available function for it, or some other workaround for it?

Example:

DF1:

    Name Age
    ABC  10
    BCD  11

DF2:

    Marks
    75
    85

Result needed:

    DF3:
    Name Age Marks
    ABC  10  75
    BCD  11  85

Body:
This works perfectly as a workaround:

    df1 = df1.withColumn("id", monotonically_increasing_id())
    df2 = df2.withColumn("id", monotonically_increasing_id())
    df3 = df2.join(df1, "id", "outer").drop("id")

For spark 1.6.*, the last line needs to be:

    df3 = df2.join(df1, df1("id") === df2("id"), "outer").drop("id")


问:
SVProgressHUD Can't show the status
When I use [SVProgressHUD show], delay 2 seconds, then use [SVProgressHUD dismiss], the HUD dismiss.

But when I use [SVProgressHUD showErrorWithStatus:@"test"], the hud can' show.

Can someone stay me why?

```<code>  - (void)viewDidLoad {
       [super viewDidLoad];
       [SVProgressHUD show];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"test"];
       });
   }
</code>```

答:
Remove the line:

```<code>[SVProgressHUD dismiss];
</code>```

Use only:

```<code>[SVProgressHUD showErrorWithStatus:@"test"];
</code>```

I think this is helpful for you.

Title: SVProgressHUD Can't show the status

Body:
When I use [SVProgressHUD show], delay 2 seconds, then use [SVProgressHUD dismiss], the HUD dismiss.

But when I use [SVProgressHUD showErrorWithStatus:@"test"], the hud can' show.

Can someone stay me why?

  - (void)viewDidLoad {
       [super viewDidLoad];
       [SVProgressHUD show];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"test"];
       });
   }

Body:
Remove the line:

[SVProgressHUD dismiss];

Use only:

[SVProgressHUD showErrorWithStatus:@"test"];

I think this is helpful for you.